169 use PermissibleDelegateTrait;
171 private const MOVES_PER_TICK = 2;
172 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
175 private const MAX_CHAT_CHAR_LENGTH = 512;
181 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
182 private const MAX_REACH_DISTANCE_CREATIVE = 13;
183 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
184 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
186 public const TAG_FIRST_PLAYED =
"firstPlayed";
187 public const TAG_LAST_PLAYED =
"lastPlayed";
188 private const TAG_GAME_MODE =
"playerGameType";
189 private const TAG_SPAWN_WORLD =
"SpawnLevel";
190 private const TAG_SPAWN_X =
"SpawnX";
191 private const TAG_SPAWN_Y =
"SpawnY";
192 private const TAG_SPAWN_Z =
"SpawnZ";
193 public const TAG_LEVEL =
"Level";
194 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
204 $lname = strtolower($name);
205 $len = strlen($name);
206 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
211 public bool $spawned =
false;
213 protected string $username;
214 protected string $displayName;
215 protected string $xuid =
"";
216 protected bool $authenticated;
219 protected ?Inventory $currentWindow =
null;
221 protected array $permanentWindows = [];
222 protected PlayerCursorInventory $cursorInventory;
223 protected PlayerCraftingInventory $craftingGrid;
224 protected CreativeInventory $creativeInventory;
226 protected int $messageCounter = 2;
228 protected int $firstPlayed;
229 protected int $lastPlayed;
230 protected GameMode $gamemode;
236 protected array $usedChunks = [];
241 private array $activeChunkGenerationRequests = [];
246 protected array $loadQueue = [];
247 protected int $nextChunkOrderRun = 5;
250 private array $tickingChunks = [];
252 protected int $viewDistance = -1;
253 protected int $spawnThreshold;
254 protected int $spawnChunkLoadCount = 0;
255 protected int $chunksPerTick;
256 protected ChunkSelector $chunkSelector;
257 protected ChunkLoader $chunkLoader;
258 protected ChunkTicker $chunkTicker;
261 protected array $hiddenPlayers = [];
263 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
264 protected ?
float $lastMovementProcess =
null;
266 protected int $inAirTicks = 0;
268 protected float $stepHeight = 0.6;
270 protected ?Vector3 $sleeping =
null;
271 private ?
Position $spawnPosition =
null;
273 private bool $respawnLocked =
false;
276 protected bool $autoJump =
true;
277 protected bool $allowFlight =
false;
278 protected bool $blockCollision =
true;
279 protected bool $flying =
false;
282 protected ?
int $lineHeight =
null;
283 protected string $locale =
"en_US";
285 protected int $startAction = -1;
291 protected array $usedItemsCooldown = [];
293 private int $lastEmoteTick = 0;
295 protected int $formIdCounter = 0;
297 protected array $forms = [];
299 protected \Logger $logger;
304 $username = TextFormat::clean($playerInfo->getUsername());
305 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
308 $this->networkSession = $session;
309 $this->playerInfo = $playerInfo;
310 $this->authenticated = $authenticated;
312 $this->username = $username;
313 $this->displayName = $this->username;
314 $this->locale = $this->playerInfo->getLocale();
316 $this->uuid = $this->playerInfo->getUuid();
317 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
319 $this->creativeInventory = CreativeInventory::getInstance();
321 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
322 if($this->
server->isOp($this->username)){
323 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
326 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
327 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
330 $this->chunkLoader =
new class implements
ChunkLoader{};
332 $world = $spawnLocation->
getWorld();
334 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
335 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
336 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
337 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
338 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
340 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
344 $this->setNameTag($this->username);
347 private function callDummyItemHeldEvent() : void{
348 $slot = $this->inventory->getHeldItemIndex();
357 protected function initEntity(
CompoundTag $nbt) : void{
358 parent::initEntity($nbt);
359 $this->addDefaultWindows();
361 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
362 function(Inventory $unused,
int $slot) :
void{
363 if($slot === $this->inventory->getHeldItemIndex()){
364 $this->setUsingItem(
false);
366 $this->callDummyItemHeldEvent();
370 $this->setUsingItem(
false);
371 $this->callDummyItemHeldEvent();
375 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
376 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
378 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
379 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
381 $this->internalSetGameMode($this->
server->getGamemode());
384 $this->keepMovement =
true;
386 $this->setNameTagVisible();
387 $this->setNameTagAlwaysVisible();
388 $this->setCanClimb();
390 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
391 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
395 public function getLeaveMessage() : Translatable|string{
397 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
403 public function isAuthenticated() : bool{
404 return $this->authenticated;
429 return parent::getUniqueId();
436 return $this->firstPlayed;
443 return $this->lastPlayed;
446 public function hasPlayedBefore() : bool{
447 return $this->lastPlayed - $this->firstPlayed > 1;
460 if($this->allowFlight !== $value){
461 $this->allowFlight = $value;
462 $this->getNetworkSession()->syncAbilities($this);
473 return $this->allowFlight;
485 if($this->blockCollision !== $value){
486 $this->blockCollision = $value;
487 $this->getNetworkSession()->syncAbilities($this);
496 return $this->blockCollision;
499 public function setFlying(
bool $value) : void{
500 if($this->flying !== $value){
501 $this->flying = $value;
502 $this->resetFallDistance();
503 $this->getNetworkSession()->syncAbilities($this);
507 public function isFlying() : bool{
508 return $this->flying;
511 public function setAutoJump(
bool $value) : void{
512 if($this->autoJump !== $value){
513 $this->autoJump = $value;
514 $this->getNetworkSession()->syncAdventureSettings();
518 public function hasAutoJump() : bool{
519 return $this->autoJump;
522 public function spawnTo(Player $player) : void{
523 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
524 parent::spawnTo($player);
528 public function getServer() : Server{
533 return $this->lineHeight ?? 7;
537 if($height !== null && $height < 1){
538 throw new \InvalidArgumentException(
"Line height must be at least 1");
540 $this->lineHeight = $height;
543 public function canSee(
Player $player) : bool{
544 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
547 public function hidePlayer(Player $player) : void{
548 if($player === $this){
551 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
552 $player->despawnFrom($this);
555 public function showPlayer(Player $player) : void{
556 if($player === $this){
559 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
560 if($player->isOnline()){
561 $player->spawnTo($this);
565 public function canCollideWith(Entity $entity) : bool{
569 public function canBeCollidedWith() : bool{
570 return !$this->isSpectator() && parent::canBeCollidedWith();
573 public function resetFallDistance() : void{
574 parent::resetFallDistance();
575 $this->inAirTicks = 0;
578 public function getViewDistance() : int{
579 return $this->viewDistance;
582 public function setViewDistance(
int $distance) : void{
583 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
585 if($newViewDistance !== $this->viewDistance){
586 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
590 $this->viewDistance = $newViewDistance;
592 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
594 $this->nextChunkOrderRun = 0;
596 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
598 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
601 public function isOnline() : bool{
602 return $this->isConnected();
605 public function isConnected() : bool{
606 return $this->networkSession !== null && $this->networkSession->isConnected();
609 public function getNetworkSession() : NetworkSession{
610 if($this->networkSession === null){
611 throw new \LogicException(
"Player is not connected");
613 return $this->networkSession;
620 return $this->username;
627 return $this->displayName;
630 public function setDisplayName(
string $name) : void{
634 $this->displayName = $ev->getNewName();
645 return $this->locale;
648 public function getLanguage() :
Language{
649 return $this->
server->getLanguage();
656 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
660 if($ev->isCancelled()){
661 $this->sendSkin([$this]);
665 $this->setSkin($ev->getNewSkin());
666 $this->sendSkin($this->server->getOnlinePlayers());
675 public function sendSkin(?array $targets =
null) : void{
676 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
683 return $this->startAction > -1;
686 public function setUsingItem(
bool $value) : void{
687 $this->startAction = $value ? $this->
server->getTick() : -1;
688 $this->networkPropertiesDirty =
true;
696 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
703 $this->checkItemCooldowns();
704 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
711 $this->checkItemCooldowns();
712 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
719 $ticks = $ticks ?? $item->getCooldownTicks();
721 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
722 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
726 protected function checkItemCooldowns() : void{
727 $serverTick = $this->
server->getTick();
728 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
729 if($cooldownUntil <= $serverTick){
730 unset($this->usedItemsCooldown[$itemId]);
735 protected function setPosition(Vector3 $pos) : bool{
736 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
737 if(parent::setPosition($pos)){
738 $newWorld = $this->getWorld();
739 if($oldWorld !== $newWorld){
740 if($oldWorld !==
null){
741 foreach($this->usedChunks as $index => $status){
742 World::getXZ($index, $X, $Z);
743 $this->unloadChunk($X, $Z, $oldWorld);
747 $this->usedChunks = [];
748 $this->loadQueue = [];
749 $this->getNetworkSession()->onEnterWorld();
758 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
759 $world = $world ?? $this->getWorld();
760 $index = World::chunkHash($x, $z);
761 if(isset($this->usedChunks[$index])){
762 foreach($world->getChunkEntities($x, $z) as $entity){
763 if($entity !== $this){
764 $entity->despawnFrom($this);
767 $this->getNetworkSession()->stopUsingChunk($x, $z);
768 unset($this->usedChunks[$index]);
769 unset($this->activeChunkGenerationRequests[$index]);
771 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
772 $world->unregisterChunkListener($this, $x, $z);
773 unset($this->loadQueue[$index]);
774 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
775 unset($this->tickingChunks[$index]);
778 protected function spawnEntitiesOnAllChunks() : void{
779 foreach($this->usedChunks as $chunkHash => $status){
780 if($status === UsedChunkStatus::SENT){
781 World::getXZ($chunkHash, $chunkX, $chunkZ);
782 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
787 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
788 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
789 if($entity !== $this && !$entity->isFlaggedForDespawn()){
790 $entity->spawnTo($this);
800 if(!$this->isConnected()){
804 Timings::$playerChunkSend->startTiming();
807 $world = $this->getWorld();
809 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
810 foreach($this->loadQueue as $index => $distance){
811 if($count >= $limit){
817 World::getXZ($index, $X, $Z);
818 assert(is_int($X) && is_int($Z));
822 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
823 $this->activeChunkGenerationRequests[$index] =
true;
824 unset($this->loadQueue[$index]);
825 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
826 $world->registerChunkListener($this, $X, $Z);
827 if(isset($this->tickingChunks[$index])){
828 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
831 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
832 function() use ($X, $Z, $index, $world) :
void{
833 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
836 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
842 unset($this->activeChunkGenerationRequests[$index]);
843 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
845 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
846 $this->usedChunks[$index] = UsedChunkStatus::SENT;
847 if($this->spawnChunkLoadCount === -1){
848 $this->spawnEntitiesOnChunk($X, $Z);
849 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
850 $this->spawnChunkLoadCount = -1;
852 $this->spawnEntitiesOnAllChunks();
854 $this->getNetworkSession()->notifyTerrainReady();
856 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
859 static function() :
void{
865 Timings::$playerChunkSend->stopTiming();
868 private function recheckBroadcastPermissions() : void{
870 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
871 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
872 ] as $permission => $channel){
873 if($this->hasPermission($permission)){
874 $this->
server->subscribeToBroadcastChannel($channel, $this);
876 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
889 $this->spawned =
true;
890 $this->recheckBroadcastPermissions();
891 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
892 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
893 $this->recheckBroadcastPermissions();
897 $ev =
new PlayerJoinEvent($this,
898 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
901 if($ev->getJoinMessage() !==
""){
902 $this->server->broadcastMessage($ev->getJoinMessage());
905 $this->noDamageTicks = 60;
909 if($this->getHealth() <= 0){
910 $this->logger->debug(
"Quit while dead, forcing respawn");
911 $this->actuallyRespawn();
922 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
923 $world = $this->getWorld();
924 foreach($oldTickingChunks as $hash => $_){
925 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
927 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
928 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
931 foreach($newTickingChunks as $hash => $_){
932 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
934 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
935 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
945 if(!$this->isConnected() || $this->viewDistance === -1){
949 Timings::$playerChunkOrder->startTiming();
953 $unloadChunks = $this->usedChunks;
955 $world = $this->getWorld();
956 $tickingChunkRadius = $world->getChunkTickRadius();
958 foreach($this->chunkSelector->selectChunks(
959 $this->server->getAllowedViewDistance($this->viewDistance),
960 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
961 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
962 ) as $radius => $hash){
963 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
964 $newOrder[$hash] =
true;
966 if($radius < $tickingChunkRadius){
967 $tickingChunks[$hash] =
true;
969 unset($unloadChunks[$hash]);
972 foreach($unloadChunks as $index => $status){
973 World::getXZ($index, $X, $Z);
974 $this->unloadChunk($X, $Z);
977 $this->loadQueue = $newOrder;
979 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
980 $this->tickingChunks = $tickingChunks;
982 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
983 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
986 Timings::$playerChunkOrder->stopTiming();
994 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1002 return $this->usedChunks;
1009 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1016 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1017 return $status === UsedChunkStatus::SENT;
1024 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1025 $this->nextChunkOrderRun = PHP_INT_MAX;
1026 $this->orderChunks();
1029 if(count($this->loadQueue) > 0){
1030 $this->requestChunks();
1038 if($this->hasValidCustomSpawn()){
1039 return $this->spawnPosition;
1041 $world = $this->
server->getWorldManager()->getDefaultWorld();
1043 return $world->getSpawnLocation();
1047 public function hasValidCustomSpawn() : bool{
1048 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1060 $world = $this->getWorld();
1062 $world = $pos->getWorld();
1064 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1066 $this->spawnPosition =
null;
1068 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1071 public function isSleeping() : bool{
1072 return $this->sleeping !== null;
1075 public function sleepOn(Vector3 $pos) : bool{
1076 $pos = $pos->floor();
1077 $b = $this->getWorld()->getBlock($pos);
1079 $ev =
new PlayerBedEnterEvent($this, $b);
1081 if($ev->isCancelled()){
1085 if($b instanceof Bed){
1087 $this->getWorld()->setBlock($pos, $b);
1090 $this->sleeping = $pos;
1091 $this->networkPropertiesDirty =
true;
1093 $this->setSpawn($pos);
1095 $this->getWorld()->setSleepTicks(60);
1100 public function stopSleep() : void{
1101 if($this->sleeping instanceof Vector3){
1102 $b = $this->getWorld()->getBlock($this->sleeping);
1103 if($b instanceof Bed){
1104 $b->setOccupied(
false);
1105 $this->getWorld()->setBlock($this->sleeping, $b);
1107 (
new PlayerBedLeaveEvent($this, $b))->call();
1109 $this->sleeping =
null;
1110 $this->networkPropertiesDirty =
true;
1112 $this->getWorld()->setSleepTicks(0);
1114 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1118 public function getGamemode() : GameMode{
1119 return $this->gamemode;
1122 protected function internalSetGameMode(GameMode $gameMode) : void{
1123 $this->gamemode = $gameMode;
1125 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1126 $this->hungerManager->setEnabled($this->isSurvival());
1128 if($this->isSpectator()){
1129 $this->setFlying(
true);
1130 $this->setHasBlockCollision(
false);
1132 $this->onGround =
false;
1136 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1138 if($this->isSurvival()){
1139 $this->setFlying(
false);
1141 $this->setHasBlockCollision(
true);
1142 $this->setSilent(
false);
1143 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1151 if($this->gamemode === $gm){
1157 if($ev->isCancelled()){
1161 $this->internalSetGameMode($gm);
1163 if($this->isSpectator()){
1164 $this->despawnFromAll();
1166 $this->spawnToAll();
1169 $this->getNetworkSession()->syncGameMode($this->gamemode);
1180 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1190 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1200 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1203 public function isSpectator() : bool{
1204 return $this->gamemode === GameMode::SPECTATOR;
1211 return $this->gamemode !== GameMode::CREATIVE;
1215 if($this->hasFiniteResources()){
1216 return parent::getDrops();
1223 if($this->hasFiniteResources()){
1224 return parent::getXpDropAmount();
1230 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1231 if($this->gamemode === GameMode::SPECTATOR){
1232 $this->onGround =
false;
1234 $bb = clone $this->boundingBox;
1235 $bb->minY = $this->location->y - 0.2;
1236 $bb->maxY = $this->location->y + 0.2;
1240 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1242 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1250 protected function checkNearEntities() : void{
1251 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1252 $entity->scheduleUpdate();
1254 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1258 $entity->onCollideWithPlayer($this);
1262 public function getInAirTicks() : int{
1263 return $this->inAirTicks;
1275 Timings::$playerMove->startTiming();
1277 $this->actuallyHandleMovement($newPos);
1279 Timings::$playerMove->stopTiming();
1283 private function actuallyHandleMovement(Vector3 $newPos) : void{
1284 $this->moveRateLimit--;
1285 if($this->moveRateLimit < 0){
1289 $oldPos = $this->location;
1290 $distanceSquared = $newPos->distanceSquared($oldPos);
1294 if($distanceSquared > 225){
1306 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1307 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1309 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1311 $this->nextChunkOrderRun = 0;
1314 if(!$revert && $distanceSquared != 0){
1315 $dx = $newPos->x - $oldPos->x;
1316 $dy = $newPos->y - $oldPos->y;
1317 $dz = $newPos->z - $oldPos->z;
1319 $this->move($dx, $dy, $dz);
1323 $this->revertMovement($oldPos);
1331 $now = microtime(true);
1332 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1333 $exceededRateLimit = $this->moveRateLimit < 0;
1334 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1335 $this->lastMovementProcess = $now;
1337 $from = clone $this->lastLocation;
1338 $to = clone $this->location;
1340 $delta = $to->distanceSquared($from);
1341 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1343 if($delta > 0.0001 || $deltaAngle > 1.0){
1344 if(PlayerMoveEvent::hasHandlers()){
1349 if($ev->isCancelled()){
1350 $this->revertMovement($from);
1354 if($to->distanceSquared($ev->getTo()) > 0.01){
1355 $this->teleport($ev->getTo());
1360 $this->lastLocation = $to;
1361 $this->broadcastMovement();
1363 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1364 if($horizontalDistanceTravelled > 0){
1366 if($this->isSprinting()){
1367 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1369 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1372 if($this->nextChunkOrderRun > 20){
1373 $this->nextChunkOrderRun = 20;
1378 if($exceededRateLimit){
1379 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1380 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1384 protected function revertMovement(Location $from) : void{
1385 $this->setPosition($from);
1386 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1389 protected function calculateFallDamage(
float $fallDistance) : float{
1390 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1398 public function setMotion(
Vector3 $motion) : bool{
1399 if(parent::setMotion($motion)){
1400 $this->broadcastMotion();
1401 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1408 protected function updateMovement(
bool $teleport =
false) : void{
1412 protected function tryChangeMovement() : void{
1416 public function onUpdate(int $currentTick) : bool{
1417 $tickDiff = $currentTick - $this->lastUpdate;
1423 $this->messageCounter = 2;
1425 $this->lastUpdate = $currentTick;
1427 if($this->justCreated){
1428 $this->onFirstUpdate($currentTick);
1431 if(!$this->isAlive() && $this->spawned){
1432 $this->onDeathUpdate($tickDiff);
1436 $this->timings->startTiming();
1439 Timings::$playerMove->startTiming();
1440 $this->processMostRecentMovements();
1441 $this->motion = Vector3::zero();
1442 if($this->onGround){
1443 $this->inAirTicks = 0;
1445 $this->inAirTicks += $tickDiff;
1447 Timings::$playerMove->stopTiming();
1449 Timings::$entityBaseTick->startTiming();
1450 $this->entityBaseTick($tickDiff);
1451 Timings::$entityBaseTick->stopTiming();
1453 if($this->isCreative() && $this->fireTicks > 1){
1454 $this->fireTicks = 1;
1457 if(!$this->isSpectator() && $this->isAlive()){
1458 Timings::$playerCheckNearEntities->startTiming();
1459 $this->checkNearEntities();
1460 Timings::$playerCheckNearEntities->stopTiming();
1463 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1464 $this->blockBreakHandler =
null;
1468 $this->timings->stopTiming();
1474 return $this->isCreative() || parent::canBreathe();
1483 $eyePos = $this->getEyePos();
1484 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1488 $dV = $this->getDirectionVector();
1489 $eyeDot = $dV->dot($eyePos);
1490 $targetDot = $dV->dot($pos);
1491 return ($targetDot - $eyeDot) >= -$maxDiff;
1498 public function chat(
string $message) : bool{
1499 $this->removeCurrentWindow();
1501 if($this->messageCounter <= 0){
1507 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1508 if(strlen($message) > $maxTotalLength){
1512 $message = TextFormat::clean($message,
false);
1513 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1514 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1515 if(str_starts_with($messagePart,
'./')){
1516 $messagePart = substr($messagePart, 1);
1519 if(str_starts_with($messagePart,
"/")){
1520 Timings::$playerCommand->startTiming();
1521 $this->server->dispatchCommand($this, substr($messagePart, 1));
1522 Timings::$playerCommand->stopTiming();
1524 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1526 if(!$ev->isCancelled()){
1527 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1536 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1537 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1540 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1544 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1546 if($ev->isCancelled()){
1550 $this->inventory->setHeldItemIndex($hotbarSlot);
1551 $this->setUsingItem(
false);
1559 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1560 $heldItemChanged = false;
1562 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1565 $newReplica = clone $oldHeldItem;
1566 $newReplica->setCount($newHeldItem->getCount());
1567 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1568 $newReplica->setDamage($newHeldItem->getDamage());
1570 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1572 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1573 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1574 $this->broadcastSound(
new ItemBreakSound());
1576 $this->inventory->setItemInHand($newHeldItem);
1577 $heldItemChanged =
true;
1581 if(!$heldItemChanged){
1582 $newHeldItem = $oldHeldItem;
1585 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1586 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1588 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1590 $ev =
new PlayerDropItemEvent($this, $drop);
1591 if($this->isSpectator()){
1595 if(!$ev->isCancelled()){
1596 $this->dropItem($drop);
1607 $directionVector = $this->getDirectionVector();
1608 $item = $this->inventory->getItemInHand();
1609 $oldItem = clone $item;
1612 if($this->hasItemCooldown($item) || $this->isSpectator()){
1618 if($ev->isCancelled()){
1622 $returnedItems = [];
1623 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1624 if($result === ItemUseResult::FAIL){
1628 $this->resetItemCooldown($oldItem);
1629 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1631 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1642 $slot = $this->inventory->getItemInHand();
1644 $oldItem = clone $slot;
1647 if($this->hasItemCooldown($slot)){
1652 if($ev->isCancelled() || !$this->consumeObject($slot)){
1656 $this->setUsingItem(
false);
1657 $this->resetItemCooldown($oldItem);
1660 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1675 $item = $this->inventory->getItemInHand();
1676 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1680 $oldItem = clone $item;
1682 $returnedItems = [];
1683 $result = $item->onReleaseUsing($this, $returnedItems);
1684 if($result === ItemUseResult::SUCCESS){
1685 $this->resetItemCooldown($oldItem);
1686 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1692 $this->setUsingItem(
false);
1696 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1697 $block = $this->getWorld()->getBlock($pos);
1698 if($block instanceof UnknownBlock){
1702 $item = $block->getPickedItem($addTileNBT);
1704 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1705 $existingSlot = $this->inventory->first($item);
1706 if($existingSlot === -1 && $this->hasFiniteResources()){
1711 if(!$ev->isCancelled()){
1712 if($existingSlot !== -1){
1713 if($existingSlot < $this->inventory->getHotbarSize()){
1714 $this->inventory->setHeldItemIndex($existingSlot);
1716 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1719 $firstEmpty = $this->inventory->firstEmpty();
1720 if($firstEmpty === -1){
1721 $this->inventory->setItemInHand($item);
1722 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1723 $this->inventory->setItem($firstEmpty, $item);
1724 $this->inventory->setHeldItemIndex($firstEmpty);
1726 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1727 $this->inventory->setItemInHand($item);
1741 if($pos->distanceSquared($this->location) > 10000){
1745 $target = $this->getWorld()->getBlock($pos);
1747 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1748 if($this->isSpectator()){
1752 if($ev->isCancelled()){
1755 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1756 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1760 $block = $target->getSide($face);
1761 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1762 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1763 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1767 if(!$this->isCreative() && !$block->getBreakInfo()->breaksInstantly()){
1768 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1774 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1775 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1776 $this->blockBreakHandler->setTargetedFace($face);
1780 public function stopBreakBlock(Vector3 $pos) : void{
1781 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1782 $this->blockBreakHandler =
null;
1792 $this->removeCurrentWindow();
1794 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1795 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1796 $this->stopBreakBlock($pos);
1797 $item = $this->inventory->getItemInHand();
1798 $oldItem = clone $item;
1799 $returnedItems = [];
1800 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1801 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1802 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1806 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1818 $this->setUsingItem(false);
1820 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1821 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1822 $item = $this->inventory->getItemInHand();
1823 $oldItem = clone $item;
1824 $returnedItems = [];
1825 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1826 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1830 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1843 if(!$entity->isAlive()){
1847 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1851 $heldItem = $this->inventory->getItemInHand();
1852 $oldItem = clone $heldItem;
1854 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1855 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1856 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1858 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1862 $meleeEnchantmentDamage = 0;
1864 $meleeEnchantments = [];
1865 foreach($heldItem->getEnchantments() as $enchantment){
1866 $type = $enchantment->getType();
1867 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1868 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1869 $meleeEnchantments[] = $enchantment;
1872 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1874 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1875 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1878 $entity->attack($ev);
1879 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1881 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1882 if($ev->isCancelled()){
1883 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1886 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1888 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1889 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
1892 foreach($meleeEnchantments as $enchantment){
1893 $type = $enchantment->getType();
1894 assert($type instanceof MeleeWeaponEnchantment);
1895 $type->onPostAttack($this, $entity, $enchantment->getLevel());
1898 if($this->isAlive()){
1901 $returnedItems = [];
1902 $heldItem->onAttackEntity($entity, $returnedItems);
1903 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
1905 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
1918 if(!$ev->isCancelled()){
1919 $this->broadcastSound(new EntityAttackNoDamageSound());
1920 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1930 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1931 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
1937 $item = $this->inventory->getItemInHand();
1938 $oldItem = clone $item;
1939 if(!$ev->isCancelled()){
1940 if($item->onInteractEntity($this, $entity, $clickPos)){
1941 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
1942 if($item instanceof Durable && $item->isBroken()){
1943 $this->broadcastSound(new ItemBreakSound());
1945 $this->inventory->setItemInHand($item);
1948 return $entity->
onInteract($this, $clickPos);
1953 public function toggleSprint(
bool $sprint) : bool{
1954 if($sprint === $this->sprinting){
1957 $ev =
new PlayerToggleSprintEvent($this, $sprint);
1959 if($ev->isCancelled()){
1962 $this->setSprinting($sprint);
1966 public function toggleSneak(
bool $sneak) : bool{
1967 if($sneak === $this->sneaking){
1970 $ev =
new PlayerToggleSneakEvent($this, $sneak);
1972 if($ev->isCancelled()){
1975 $this->setSneaking($sneak);
1979 public function toggleFlight(
bool $fly) : bool{
1980 if($fly === $this->flying){
1983 $ev =
new PlayerToggleFlightEvent($this, $fly);
1984 if(!$this->allowFlight){
1988 if($ev->isCancelled()){
1991 $this->setFlying($fly);
1995 public function toggleGlide(
bool $glide) : bool{
1996 if($glide === $this->gliding){
1999 $ev =
new PlayerToggleGlideEvent($this, $glide);
2001 if($ev->isCancelled()){
2004 $this->setGliding($glide);
2008 public function toggleSwim(
bool $swim) : bool{
2009 if($swim === $this->swimming){
2012 $ev =
new PlayerToggleSwimEvent($this, $swim);
2014 if($ev->isCancelled()){
2017 $this->setSwimming($swim);
2021 public function emote(
string $emoteId) : void{
2022 $currentTick = $this->
server->getTick();
2023 if($currentTick - $this->lastEmoteTick > 5){
2024 $this->lastEmoteTick = $currentTick;
2025 $event =
new PlayerEmoteEvent($this, $emoteId);
2027 if(!$event->isCancelled()){
2028 $emoteId = $event->getEmoteId();
2029 parent::emote($emoteId);
2039 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2049 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2050 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2051 if($subtitle !==
""){
2052 $this->sendSubTitle($subtitle);
2054 $this->getNetworkSession()->onTitle($title);
2061 $this->getNetworkSession()->onSubTitle($subtitle);
2068 $this->getNetworkSession()->onActionBar($message);
2075 $this->getNetworkSession()->onClearTitle();
2082 $this->getNetworkSession()->onResetTitleOptions();
2093 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2094 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2102 $this->getNetworkSession()->onChatMessage($message);
2105 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2106 $this->getNetworkSession()->onJukeboxPopup($message);
2115 $this->getNetworkSession()->onPopup($message);
2118 public function sendTip(
string $message) : void{
2119 $this->getNetworkSession()->onTip($message);
2126 $this->getNetworkSession()->onToastNotification($title, $body);
2135 $id = $this->formIdCounter++;
2136 if($this->getNetworkSession()->onFormSent($id, $form)){
2137 $this->forms[$id] = $form;
2141 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2142 if(!isset($this->forms[$formId])){
2143 $this->logger->debug(
"Got unexpected response for form $formId");
2148 $this->forms[$formId]->handleResponse($this, $responseData);
2149 }
catch(FormValidationException $e){
2150 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2151 $this->logger->logException($e);
2153 unset($this->forms[$formId]);
2163 $this->getNetworkSession()->onCloseAllForms();
2178 if(!$ev->isCancelled()){
2179 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2194 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2196 if(!$ev->isCancelled()){
2197 $reason = $ev->getDisconnectReason();
2199 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2201 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2202 if($disconnectScreenMessage ===
""){
2203 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2205 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2227 if(!$this->isConnected()){
2231 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2232 $this->onPostDisconnect($reason, $quitMessage);
2243 if($this->isConnected()){
2244 throw new \LogicException(
"Player is still connected");
2248 $this->server->unsubscribeFromAllBroadcastChannels($this);
2250 $this->removeCurrentWindow();
2252 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2254 if(($quitMessage = $ev->getQuitMessage()) !=
""){
2255 $this->server->broadcastMessage($quitMessage);
2259 $this->spawned =
false;
2262 $this->blockBreakHandler =
null;
2263 $this->despawnFromAll();
2265 $this->
server->removeOnlinePlayer($this);
2267 foreach($this->
server->getOnlinePlayers() as $player){
2268 if(!$player->canSee($this)){
2269 $player->showPlayer($this);
2272 $this->hiddenPlayers = [];
2274 if($this->location->isValid()){
2275 foreach($this->usedChunks as $index => $status){
2276 World::getXZ($index, $chunkX, $chunkZ);
2277 $this->unloadChunk($chunkX, $chunkZ);
2280 if(count($this->usedChunks) !== 0){
2281 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2283 $this->loadQueue = [];
2285 $this->removeCurrentWindow();
2286 $this->removePermanentInventories();
2288 $this->perm->getPermissionRecalculationCallbacks()->clear();
2290 $this->flagForDespawn();
2294 $this->disconnect(
"Player destroyed");
2295 $this->cursorInventory->removeAllViewers();
2296 $this->craftingGrid->removeAllViewers();
2297 parent::onDispose();
2301 $this->networkSession = null;
2302 unset($this->cursorInventory);
2303 unset($this->craftingGrid);
2304 $this->spawnPosition =
null;
2305 $this->blockBreakHandler =
null;
2306 parent::destroyCycles();
2316 public function __destruct(){
2317 parent::__destruct();
2318 $this->logger->debug(
"Destroyed by garbage collector");
2326 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2330 $nbt = $this->saveNBT();
2332 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2334 if($this->location->isValid()){
2335 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2338 if($this->hasValidCustomSpawn()){
2339 $spawn = $this->getSpawn();
2340 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2341 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2342 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2343 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2346 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2347 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2348 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2357 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2363 $this->removeCurrentWindow();
2365 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2368 if(!$ev->getKeepInventory()){
2369 foreach($ev->getDrops() as $item){
2370 $this->getWorld()->dropItem($this->location, $item);
2373 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2374 $this->inventory->setHeldItemIndex(0);
2375 $clearInventory($this->inventory);
2376 $clearInventory($this->armorInventory);
2377 $clearInventory($this->offHandInventory);
2380 if(!$ev->getKeepXp()){
2381 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2382 $this->xpManager->setXpAndProgress(0, 0.0);
2385 if($ev->getDeathMessage() !=
""){
2386 $this->server->broadcastMessage($ev->getDeathMessage());
2389 $this->startDeathAnimation();
2391 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2395 parent::onDeathUpdate($tickDiff);
2399 public function respawn() : void{
2400 if($this->
server->isHardcore()){
2401 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2402 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2407 $this->actuallyRespawn();
2410 protected function actuallyRespawn() : void{
2411 if($this->respawnLocked){
2414 $this->respawnLocked =
true;
2416 $this->logger->debug(
"Waiting for safe respawn position to be located");
2417 $spawn = $this->getSpawn();
2418 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2419 function(Position $safeSpawn) :
void{
2420 if(!$this->isConnected()){
2423 $this->logger->debug(
"Respawn position located, completing respawn");
2424 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2427 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2428 $this->teleport($realSpawn);
2430 $this->setSprinting(
false);
2431 $this->setSneaking(
false);
2432 $this->setFlying(
false);
2434 $this->extinguish();
2435 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2436 $this->deadTicks = 0;
2437 $this->noDamageTicks = 60;
2439 $this->effectManager->clear();
2440 $this->setHealth($this->getMaxHealth());
2442 foreach($this->attributeMap->getAll() as $attr){
2443 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2446 $attr->resetToDefault();
2449 $this->spawnToAll();
2450 $this->scheduleUpdate();
2452 $this->getNetworkSession()->onServerRespawn();
2453 $this->respawnLocked =
false;
2456 if($this->isConnected()){
2457 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2464 parent::applyPostDamageEffects($source);
2466 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2470 if(!$this->isAlive()){
2474 if($this->isCreative()
2475 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2478 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2482 parent::attack($source);
2485 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2486 parent::syncNetworkData($properties);
2488 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2489 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2491 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2492 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2495 public function sendData(?array $targets, ?array $data =
null) : void{
2496 if($targets === null){
2497 $targets = $this->getViewers();
2500 parent::sendData($targets, $data);
2504 if($this->spawned && $targets === null){
2505 $targets = $this->getViewers();
2508 parent::broadcastAnimation($animation, $targets);
2512 if($this->spawned && $targets === null){
2513 $targets = $this->getViewers();
2516 parent::broadcastSound($sound, $targets);
2522 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2523 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2529 if(parent::teleport($pos, $yaw, $pitch)){
2531 $this->removeCurrentWindow();
2534 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2535 $this->broadcastMovement(
true);
2537 $this->spawnToAll();
2539 $this->resetFallDistance();
2540 $this->nextChunkOrderRun = 0;
2541 if($this->spawnChunkLoadCount !== -1){
2542 $this->spawnChunkLoadCount = 0;
2544 $this->blockBreakHandler =
null;
2548 $this->resetLastMovements();
2556 protected function addDefaultWindows() : void{
2557 $this->cursorInventory = new PlayerCursorInventory($this);
2558 $this->craftingGrid =
new PlayerCraftingInventory($this);
2560 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2565 public function getCursorInventory() : PlayerCursorInventory{
2566 return $this->cursorInventory;
2569 public function getCraftingGrid() : CraftingGrid{
2570 return $this->craftingGrid;
2578 return $this->creativeInventory;
2585 $this->creativeInventory = $inventory;
2586 if($this->spawned && $this->isConnected()){
2587 $this->getNetworkSession()->getInvManager()?->syncCreative();
2595 private function doCloseInventory() : void{
2596 $inventories = [$this->craftingGrid, $this->cursorInventory];
2597 if($this->currentWindow instanceof TemporaryInventory){
2598 $inventories[] = $this->currentWindow;
2601 $builder =
new TransactionBuilder();
2602 foreach($inventories as $inventory){
2603 $contents = $inventory->getContents();
2605 if(count($contents) > 0){
2606 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2607 foreach($drops as $drop){
2608 $builder->addAction(
new DropItemAction($drop));
2611 $builder->getInventory($inventory)->clearAll();
2615 $actions = $builder->generateActions();
2616 if(count($actions) !== 0){
2617 $transaction =
new InventoryTransaction($this, $actions);
2619 $transaction->execute();
2620 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2621 }
catch(TransactionCancelledException){
2622 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2623 foreach($inventories as $inventory){
2624 $inventory->clearAll();
2626 }
catch(TransactionValidationException $e){
2627 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2636 return $this->currentWindow;
2643 if($inventory === $this->currentWindow){
2648 if($ev->isCancelled()){
2652 $this->removeCurrentWindow();
2654 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2655 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2657 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2658 $inventoryManager->onCurrentWindowChange($inventory);
2659 $inventory->onOpen($this);
2660 $this->currentWindow = $inventory;
2664 public function removeCurrentWindow() : void{
2665 $this->doCloseInventory();
2666 if($this->currentWindow !==
null){
2667 $currentWindow = $this->currentWindow;
2668 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2669 $this->currentWindow->onClose($this);
2670 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2671 $inventoryManager->onCurrentWindowRemove();
2673 $this->currentWindow =
null;
2674 (
new InventoryCloseEvent($currentWindow, $this))->call();
2678 protected function addPermanentInventories(Inventory ...$inventories) : void{
2679 foreach($inventories as $inventory){
2680 $inventory->onOpen($this);
2681 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2685 protected function removePermanentInventories() : void{
2686 foreach($this->permanentWindows as $inventory){
2687 $inventory->onClose($this);
2689 $this->permanentWindows = [];
2697 $block = $this->getWorld()->getBlock($position);
2699 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2700 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2702 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2706 use ChunkListenerNoOpTrait {
2707 onChunkChanged as
private;
2708 onChunkUnloaded as
private;
2712 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2713 if($status === UsedChunkStatus::SENT){
2714 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2715 $this->nextChunkOrderRun = 0;
2720 if($this->isUsingChunk($chunkX, $chunkZ)){
2721 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2722 $this->unloadChunk($chunkX, $chunkZ);