176 use PermissibleDelegateTrait;
178 private const MOVES_PER_TICK = 2;
179 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
182 private const MAX_CHAT_CHAR_LENGTH = 512;
188 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
189 private const MAX_REACH_DISTANCE_CREATIVE = 13;
190 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
191 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
193 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
195 public const TAG_FIRST_PLAYED =
"firstPlayed";
196 public const TAG_LAST_PLAYED =
"lastPlayed";
197 private const TAG_GAME_MODE =
"playerGameType";
198 private const TAG_SPAWN_WORLD =
"SpawnLevel";
199 private const TAG_SPAWN_X =
"SpawnX";
200 private const TAG_SPAWN_Y =
"SpawnY";
201 private const TAG_SPAWN_Z =
"SpawnZ";
202 private const TAG_DEATH_WORLD =
"DeathLevel";
203 private const TAG_DEATH_X =
"DeathPositionX";
204 private const TAG_DEATH_Y =
"DeathPositionY";
205 private const TAG_DEATH_Z =
"DeathPositionZ";
206 public const TAG_LEVEL =
"Level";
207 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
217 $lname = strtolower($name);
218 $len = strlen($name);
219 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
224 public bool $spawned =
false;
226 protected string $username;
227 protected string $displayName;
228 protected string $xuid =
"";
229 protected bool $authenticated;
232 protected ?Inventory $currentWindow =
null;
234 protected array $permanentWindows = [];
235 protected PlayerCursorInventory $cursorInventory;
236 protected PlayerCraftingInventory $craftingGrid;
237 protected CreativeInventory $creativeInventory;
239 protected int $messageCounter = 2;
241 protected int $firstPlayed;
242 protected int $lastPlayed;
243 protected GameMode $gamemode;
249 protected array $usedChunks = [];
254 private array $activeChunkGenerationRequests = [];
259 protected array $loadQueue = [];
260 protected int $nextChunkOrderRun = 5;
263 private array $tickingChunks = [];
265 protected int $viewDistance = -1;
266 protected int $spawnThreshold;
267 protected int $spawnChunkLoadCount = 0;
268 protected int $chunksPerTick;
269 protected ChunkSelector $chunkSelector;
270 protected ChunkLoader $chunkLoader;
271 protected ChunkTicker $chunkTicker;
274 protected array $hiddenPlayers = [];
276 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
277 protected ?
float $lastMovementProcess =
null;
279 protected int $inAirTicks = 0;
281 protected float $stepHeight = 0.6;
283 protected ?Vector3 $sleeping =
null;
284 private ?
Position $spawnPosition =
null;
286 private bool $respawnLocked =
false;
288 private ?
Position $deathPosition =
null;
291 protected bool $autoJump =
true;
292 protected bool $allowFlight =
false;
293 protected bool $blockCollision =
true;
294 protected bool $flying =
false;
295 protected bool $sneakPressed =
false;
297 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
300 protected ?
int $lineHeight =
null;
301 protected string $locale =
"en_US";
303 protected int $startAction = -1;
309 protected array $usedItemsCooldown = [];
311 private int $lastEmoteTick = 0;
313 protected int $formIdCounter = 0;
315 protected array $forms = [];
317 protected \Logger $logger;
322 $username = TextFormat::clean($playerInfo->getUsername());
323 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
326 $this->networkSession = $session;
327 $this->playerInfo = $playerInfo;
328 $this->authenticated = $authenticated;
330 $this->username = $username;
331 $this->displayName = $this->username;
332 $this->locale = $this->playerInfo->getLocale();
334 $this->uuid = $this->playerInfo->getUuid();
335 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
337 $this->creativeInventory = CreativeInventory::getInstance();
339 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
340 if($this->
server->isOp($this->username)){
341 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
344 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
345 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
348 $this->chunkLoader =
new class implements
ChunkLoader{};
350 $world = $spawnLocation->
getWorld();
352 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
353 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
354 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
355 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
356 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
358 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
362 $this->setNameTag($this->username);
365 private function callDummyItemHeldEvent() : void{
366 $slot = $this->inventory->getHeldItemIndex();
375 protected function initEntity(
CompoundTag $nbt) : void{
376 parent::initEntity($nbt);
377 $this->addDefaultWindows();
379 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
380 function(Inventory $unused,
int $slot) :
void{
381 if($slot === $this->inventory->getHeldItemIndex()){
382 $this->setUsingItem(
false);
384 $this->callDummyItemHeldEvent();
388 $this->setUsingItem(
false);
389 $this->callDummyItemHeldEvent();
393 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
394 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
396 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
397 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
399 $this->internalSetGameMode($this->
server->getGamemode());
402 $this->keepMovement =
true;
404 $this->setNameTagVisible();
405 $this->setNameTagAlwaysVisible();
406 $this->setCanClimb();
408 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
409 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
411 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
412 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
416 public function getLeaveMessage() : Translatable|string{
418 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
424 public function isAuthenticated() : bool{
425 return $this->authenticated;
450 return parent::getUniqueId();
457 return $this->firstPlayed;
464 return $this->lastPlayed;
467 public function hasPlayedBefore() : bool{
468 return $this->lastPlayed - $this->firstPlayed > 1;
481 if($this->allowFlight !== $value){
482 $this->allowFlight = $value;
483 $this->getNetworkSession()->syncAbilities($this);
494 return $this->allowFlight;
506 if($this->blockCollision !== $value){
507 $this->blockCollision = $value;
508 $this->getNetworkSession()->syncAbilities($this);
517 return $this->blockCollision;
520 public function setFlying(
bool $value) : void{
521 if($this->flying !== $value){
522 $this->flying = $value;
523 $this->resetFallDistance();
524 $this->getNetworkSession()->syncAbilities($this);
528 public function isFlying() : bool{
529 return $this->flying;
546 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
547 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
548 $this->getNetworkSession()->syncAbilities($this);
564 return $this->flightSpeedMultiplier;
567 public function setAutoJump(
bool $value) : void{
568 if($this->autoJump !== $value){
569 $this->autoJump = $value;
570 $this->getNetworkSession()->syncAdventureSettings();
574 public function hasAutoJump() : bool{
575 return $this->autoJump;
578 public function spawnTo(Player $player) : void{
579 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
580 parent::spawnTo($player);
584 public function getServer() : Server{
589 return $this->lineHeight ?? 7;
593 if($height !== null && $height < 1){
594 throw new \InvalidArgumentException(
"Line height must be at least 1");
596 $this->lineHeight = $height;
599 public function canSee(
Player $player) : bool{
600 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
603 public function hidePlayer(Player $player) : void{
604 if($player === $this){
607 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
608 $player->despawnFrom($this);
611 public function showPlayer(Player $player) : void{
612 if($player === $this){
615 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
616 if($player->isOnline()){
617 $player->spawnTo($this);
621 public function canCollideWith(Entity $entity) : bool{
625 public function canBeCollidedWith() : bool{
626 return !$this->isSpectator() && parent::canBeCollidedWith();
629 public function resetFallDistance() : void{
630 parent::resetFallDistance();
631 $this->inAirTicks = 0;
634 public function getViewDistance() : int{
635 return $this->viewDistance;
638 public function setViewDistance(
int $distance) : void{
639 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
641 if($newViewDistance !== $this->viewDistance){
642 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
646 $this->viewDistance = $newViewDistance;
648 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
650 $this->nextChunkOrderRun = 0;
652 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
654 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
657 public function isOnline() : bool{
658 return $this->isConnected();
661 public function isConnected() : bool{
662 return $this->networkSession !== null && $this->networkSession->isConnected();
665 public function getNetworkSession() : NetworkSession{
666 if($this->networkSession === null){
667 throw new \LogicException(
"Player is not connected");
669 return $this->networkSession;
676 return $this->username;
683 return $this->displayName;
686 public function setDisplayName(
string $name) : void{
690 $this->displayName = $ev->getNewName();
701 return $this->locale;
704 public function getLanguage() :
Language{
705 return $this->
server->getLanguage();
712 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
716 if($ev->isCancelled()){
717 $this->sendSkin([$this]);
721 $this->setSkin($ev->getNewSkin());
722 $this->sendSkin($this->server->getOnlinePlayers());
731 public function sendSkin(?array $targets =
null) : void{
732 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
739 return $this->startAction > -1;
742 public function setUsingItem(
bool $value) : void{
743 $this->startAction = $value ? $this->
server->getTick() : -1;
744 $this->networkPropertiesDirty =
true;
752 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
759 $this->checkItemCooldowns();
760 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
767 $this->checkItemCooldowns();
768 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
775 $ticks = $ticks ?? $item->getCooldownTicks();
777 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
778 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
782 protected function checkItemCooldowns() : void{
783 $serverTick = $this->
server->getTick();
784 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
785 if($cooldownUntil <= $serverTick){
786 unset($this->usedItemsCooldown[$itemId]);
791 protected function setPosition(Vector3 $pos) : bool{
792 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
793 if(parent::setPosition($pos)){
794 $newWorld = $this->getWorld();
795 if($oldWorld !== $newWorld){
796 if($oldWorld !==
null){
797 foreach($this->usedChunks as $index => $status){
798 World::getXZ($index, $X, $Z);
799 $this->unloadChunk($X, $Z, $oldWorld);
803 $this->usedChunks = [];
804 $this->loadQueue = [];
805 $this->getNetworkSession()->onEnterWorld();
814 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
815 $world = $world ?? $this->getWorld();
816 $index = World::chunkHash($x, $z);
817 if(isset($this->usedChunks[$index])){
818 foreach($world->getChunkEntities($x, $z) as $entity){
819 if($entity !== $this){
820 $entity->despawnFrom($this);
823 $this->getNetworkSession()->stopUsingChunk($x, $z);
824 unset($this->usedChunks[$index]);
825 unset($this->activeChunkGenerationRequests[$index]);
827 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
828 $world->unregisterChunkListener($this, $x, $z);
829 unset($this->loadQueue[$index]);
830 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
831 unset($this->tickingChunks[$index]);
834 protected function spawnEntitiesOnAllChunks() : void{
835 foreach($this->usedChunks as $chunkHash => $status){
836 if($status === UsedChunkStatus::SENT){
837 World::getXZ($chunkHash, $chunkX, $chunkZ);
838 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
843 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
844 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
845 if($entity !== $this && !$entity->isFlaggedForDespawn()){
846 $entity->spawnTo($this);
856 if(!$this->isConnected()){
860 Timings::$playerChunkSend->startTiming();
863 $world = $this->getWorld();
865 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
866 foreach($this->loadQueue as $index => $distance){
867 if($count >= $limit){
873 World::getXZ($index, $X, $Z);
877 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
878 $this->activeChunkGenerationRequests[$index] =
true;
879 unset($this->loadQueue[$index]);
880 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
881 $world->registerChunkListener($this, $X, $Z);
882 if(isset($this->tickingChunks[$index])){
883 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
886 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
887 function() use ($X, $Z, $index, $world) :
void{
888 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
891 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
897 unset($this->activeChunkGenerationRequests[$index]);
898 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
900 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
901 $this->usedChunks[$index] = UsedChunkStatus::SENT;
902 if($this->spawnChunkLoadCount === -1){
903 $this->spawnEntitiesOnChunk($X, $Z);
904 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
905 $this->spawnChunkLoadCount = -1;
907 $this->spawnEntitiesOnAllChunks();
909 $this->getNetworkSession()->notifyTerrainReady();
911 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
914 static function() :
void{
920 Timings::$playerChunkSend->stopTiming();
923 private function recheckBroadcastPermissions() : void{
925 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
926 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
927 ] as $permission => $channel){
928 if($this->hasPermission($permission)){
929 $this->
server->subscribeToBroadcastChannel($channel, $this);
931 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
944 $this->spawned =
true;
945 $this->recheckBroadcastPermissions();
946 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
947 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
948 $this->recheckBroadcastPermissions();
952 $ev =
new PlayerJoinEvent($this,
953 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
956 if($ev->getJoinMessage() !==
""){
957 $this->server->broadcastMessage($ev->getJoinMessage());
960 $this->noDamageTicks = 60;
964 if($this->getHealth() <= 0){
965 $this->logger->debug(
"Quit while dead, forcing respawn");
966 $this->actuallyRespawn();
977 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
978 $world = $this->getWorld();
979 foreach($oldTickingChunks as $hash => $_){
980 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
982 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
983 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
986 foreach($newTickingChunks as $hash => $_){
987 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
989 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
990 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1000 if(!$this->isConnected() || $this->viewDistance === -1){
1004 Timings::$playerChunkOrder->startTiming();
1007 $tickingChunks = [];
1008 $unloadChunks = $this->usedChunks;
1010 $world = $this->getWorld();
1011 $tickingChunkRadius = $world->getChunkTickRadius();
1013 foreach($this->chunkSelector->selectChunks(
1014 $this->server->getAllowedViewDistance($this->viewDistance),
1015 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1016 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1017 ) as $radius => $hash){
1018 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1019 $newOrder[$hash] =
true;
1021 if($radius < $tickingChunkRadius){
1022 $tickingChunks[$hash] =
true;
1024 unset($unloadChunks[$hash]);
1027 foreach($unloadChunks as $index => $status){
1028 World::getXZ($index, $X, $Z);
1029 $this->unloadChunk($X, $Z);
1032 $this->loadQueue = $newOrder;
1034 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1035 $this->tickingChunks = $tickingChunks;
1037 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1038 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1041 Timings::$playerChunkOrder->stopTiming();
1049 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1057 return $this->usedChunks;
1064 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1071 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1072 return $status === UsedChunkStatus::SENT;
1079 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1080 $this->nextChunkOrderRun = PHP_INT_MAX;
1081 $this->orderChunks();
1084 if(count($this->loadQueue) > 0){
1085 $this->requestChunks();
1089 public function getDeathPosition() : ?Position{
1090 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1091 $this->deathPosition =
null;
1093 return $this->deathPosition;
1101 if($pos instanceof
Position && $pos->world !==
null){
1102 $world = $pos->world;
1104 $world = $this->getWorld();
1106 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1108 $this->deathPosition =
null;
1110 $this->networkPropertiesDirty =
true;
1117 if($this->hasValidCustomSpawn()){
1118 return $this->spawnPosition;
1120 $world = $this->
server->getWorldManager()->getDefaultWorld();
1122 return $world->getSpawnLocation();
1126 public function hasValidCustomSpawn() : bool{
1127 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1139 $world = $this->getWorld();
1141 $world = $pos->getWorld();
1143 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1145 $this->spawnPosition =
null;
1147 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1150 public function isSleeping() : bool{
1151 return $this->sleeping !== null;
1154 public function sleepOn(Vector3 $pos) : bool{
1155 $pos = $pos->floor();
1156 $b = $this->getWorld()->getBlock($pos);
1158 $ev =
new PlayerBedEnterEvent($this, $b);
1160 if($ev->isCancelled()){
1164 if($b instanceof Bed){
1166 $this->getWorld()->setBlock($pos, $b);
1169 $this->sleeping = $pos;
1170 $this->networkPropertiesDirty =
true;
1172 $this->setSpawn($pos);
1174 $this->getWorld()->setSleepTicks(60);
1179 public function stopSleep() : void{
1180 if($this->sleeping instanceof Vector3){
1181 $b = $this->getWorld()->getBlock($this->sleeping);
1182 if($b instanceof Bed){
1183 $b->setOccupied(
false);
1184 $this->getWorld()->setBlock($this->sleeping, $b);
1186 (
new PlayerBedLeaveEvent($this, $b))->call();
1188 $this->sleeping =
null;
1189 $this->networkPropertiesDirty =
true;
1191 $this->getWorld()->setSleepTicks(0);
1193 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1197 public function getGamemode() : GameMode{
1198 return $this->gamemode;
1201 protected function internalSetGameMode(GameMode $gameMode) : void{
1202 $this->gamemode = $gameMode;
1204 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1205 $this->hungerManager->setEnabled($this->isSurvival());
1207 if($this->isSpectator()){
1208 $this->setFlying(
true);
1209 $this->setHasBlockCollision(
false);
1211 $this->onGround =
false;
1215 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1217 if($this->isSurvival()){
1218 $this->setFlying(
false);
1220 $this->setHasBlockCollision(
true);
1221 $this->setSilent(
false);
1222 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1230 if($this->gamemode === $gm){
1236 if($ev->isCancelled()){
1240 $this->internalSetGameMode($gm);
1242 if($this->isSpectator()){
1243 $this->despawnFromAll();
1245 $this->spawnToAll();
1248 $this->getNetworkSession()->syncGameMode($this->gamemode);
1259 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1269 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1279 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1282 public function isSpectator() : bool{
1283 return $this->gamemode === GameMode::SPECTATOR;
1286 public function setSneakPressed(
bool $sneakPressed) : void{
1287 $this->sneakPressed = $sneakPressed;
1295 return $this->sneakPressed;
1302 return $this->gamemode !== GameMode::CREATIVE;
1306 if($this->hasFiniteResources()){
1307 return parent::getDrops();
1314 if($this->hasFiniteResources()){
1315 return parent::getXpDropAmount();
1321 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1322 if(!$this->blockCollision){
1323 $this->onGround =
false;
1325 $bb = clone $this->boundingBox;
1326 $bb->minY = $this->location->y - 0.2;
1327 $bb->maxY = $this->location->y + 0.2;
1331 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1333 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1341 protected function checkNearEntities() : void{
1342 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1343 $entity->scheduleUpdate();
1345 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1349 $entity->onCollideWithPlayer($this);
1353 public function getInAirTicks() : int{
1354 return $this->inAirTicks;
1366 Timings::$playerMove->startTiming();
1368 $this->actuallyHandleMovement($newPos);
1370 Timings::$playerMove->stopTiming();
1374 private function actuallyHandleMovement(Vector3 $newPos) : void{
1375 $this->moveRateLimit--;
1376 if($this->moveRateLimit < 0){
1380 $oldPos = $this->location;
1381 $distanceSquared = $newPos->distanceSquared($oldPos);
1385 if($distanceSquared > 225){
1397 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1398 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1400 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1402 $this->nextChunkOrderRun = 0;
1405 if(!$revert && $distanceSquared !== 0.0){
1406 $dx = $newPos->x - $oldPos->x;
1407 $dy = $newPos->y - $oldPos->y;
1408 $dz = $newPos->z - $oldPos->z;
1410 $this->move($dx, $dy, $dz);
1414 $this->revertMovement($oldPos);
1422 $now = microtime(true);
1423 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1424 $exceededRateLimit = $this->moveRateLimit < 0;
1425 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1426 $this->lastMovementProcess = $now;
1428 $from = clone $this->lastLocation;
1429 $to = clone $this->location;
1431 $delta = $to->distanceSquared($from);
1432 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1434 if($delta > 0.0001 || $deltaAngle > 1.0){
1435 if(PlayerMoveEvent::hasHandlers()){
1440 if($ev->isCancelled()){
1441 $this->revertMovement($from);
1445 if($to->distanceSquared($ev->getTo()) > 0.01){
1446 $this->teleport($ev->getTo());
1451 $this->lastLocation = $to;
1452 $this->broadcastMovement();
1454 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1455 if($horizontalDistanceTravelled > 0){
1457 if($this->isSprinting()){
1458 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1460 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1463 if($this->nextChunkOrderRun > 20){
1464 $this->nextChunkOrderRun = 20;
1469 if($exceededRateLimit){
1470 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1471 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1475 protected function revertMovement(Location $from) : void{
1476 $this->setPosition($from);
1477 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1480 protected function calculateFallDamage(
float $fallDistance) : float{
1481 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1489 public function setMotion(
Vector3 $motion) : bool{
1490 if(parent::setMotion($motion)){
1491 $this->broadcastMotion();
1492 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1499 protected function updateMovement(
bool $teleport =
false) : void{
1503 protected function tryChangeMovement() : void{
1507 public function onUpdate(int $currentTick) : bool{
1508 $tickDiff = $currentTick - $this->lastUpdate;
1514 $this->messageCounter = 2;
1516 $this->lastUpdate = $currentTick;
1518 if($this->justCreated){
1519 $this->onFirstUpdate($currentTick);
1522 if(!$this->isAlive() && $this->spawned){
1523 $this->onDeathUpdate($tickDiff);
1527 $this->timings->startTiming();
1530 Timings::$playerMove->startTiming();
1531 $this->processMostRecentMovements();
1532 $this->motion = Vector3::zero();
1533 if($this->onGround){
1534 $this->inAirTicks = 0;
1536 $this->inAirTicks += $tickDiff;
1538 Timings::$playerMove->stopTiming();
1540 Timings::$entityBaseTick->startTiming();
1541 $this->entityBaseTick($tickDiff);
1542 Timings::$entityBaseTick->stopTiming();
1544 if($this->isCreative() && $this->fireTicks > 1){
1545 $this->fireTicks = 1;
1548 if(!$this->isSpectator() && $this->isAlive()){
1549 Timings::$playerCheckNearEntities->startTiming();
1550 $this->checkNearEntities();
1551 Timings::$playerCheckNearEntities->stopTiming();
1554 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1555 $this->blockBreakHandler =
null;
1558 if($this->isUsingItem() && $this->getItemUseDuration() % 4 === 0 && ($item = $this->inventory->getItemInHand()) instanceof ConsumableItem){
1559 $this->broadcastAnimation(
new ConsumingItemAnimation($this, $item));
1563 $this->timings->stopTiming();
1569 return $this->isCreative() || parent::canEat();
1573 return $this->isCreative() || parent::canBreathe();
1582 $eyePos = $this->getEyePos();
1583 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1587 $dV = $this->getDirectionVector();
1588 $eyeDot = $dV->dot($eyePos);
1589 $targetDot = $dV->dot($pos);
1590 return ($targetDot - $eyeDot) >= -$maxDiff;
1597 public function chat(
string $message) : bool{
1598 $this->removeCurrentWindow();
1600 if($this->messageCounter <= 0){
1606 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1607 if(strlen($message) > $maxTotalLength){
1611 $message = TextFormat::clean($message,
false);
1612 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1613 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1614 if(str_starts_with($messagePart,
'./')){
1615 $messagePart = substr($messagePart, 1);
1618 if(str_starts_with($messagePart,
"/")){
1619 Timings::$playerCommand->startTiming();
1620 $this->server->dispatchCommand($this, substr($messagePart, 1));
1621 Timings::$playerCommand->stopTiming();
1623 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1625 if(!$ev->isCancelled()){
1626 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1635 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1636 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1639 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1643 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1645 if($ev->isCancelled()){
1649 $this->inventory->setHeldItemIndex($hotbarSlot);
1650 $this->setUsingItem(
false);
1658 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1659 $heldItemChanged = false;
1661 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1664 $newReplica = clone $oldHeldItem;
1665 $newReplica->setCount($newHeldItem->getCount());
1666 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1667 $newDamage = $newHeldItem->getDamage();
1668 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1669 $newReplica->setDamage($newDamage);
1672 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1674 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1675 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1676 $this->broadcastSound(
new ItemBreakSound());
1678 $this->inventory->setItemInHand($newHeldItem);
1679 $heldItemChanged =
true;
1683 if(!$heldItemChanged){
1684 $newHeldItem = $oldHeldItem;
1687 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1688 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1690 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1692 $ev =
new PlayerDropItemEvent($this, $drop);
1693 if($this->isSpectator()){
1697 if(!$ev->isCancelled()){
1698 $this->dropItem($drop);
1709 $directionVector = $this->getDirectionVector();
1710 $item = $this->inventory->getItemInHand();
1711 $oldItem = clone $item;
1714 if($this->hasItemCooldown($item) || $this->isSpectator()){
1720 if($ev->isCancelled()){
1724 $returnedItems = [];
1725 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1726 if($result === ItemUseResult::FAIL){
1730 $this->resetItemCooldown($oldItem);
1731 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1733 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1744 $slot = $this->inventory->getItemInHand();
1746 $oldItem = clone $slot;
1749 if($this->hasItemCooldown($slot)){
1754 if($ev->isCancelled() || !$this->consumeObject($slot)){
1758 $this->setUsingItem(
false);
1759 $this->resetItemCooldown($oldItem);
1762 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1777 $item = $this->inventory->getItemInHand();
1778 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1782 $oldItem = clone $item;
1784 $returnedItems = [];
1785 $result = $item->onReleaseUsing($this, $returnedItems);
1786 if($result === ItemUseResult::SUCCESS){
1787 $this->resetItemCooldown($oldItem);
1788 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1794 $this->setUsingItem(
false);
1798 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1799 $block = $this->getWorld()->getBlock($pos);
1800 if($block instanceof UnknownBlock){
1804 $item = $block->getPickedItem($addTileNBT);
1806 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1807 $existingSlot = $this->inventory->first($item);
1808 if($existingSlot === -1 && $this->hasFiniteResources()){
1813 if(!$ev->isCancelled()){
1814 $this->equipOrAddPickedItem($existingSlot, $item);
1820 public function pickEntity(
int $entityId) : bool{
1821 $entity = $this->getWorld()->getEntity($entityId);
1824 if($entity ===
null || $entity->isFlaggedForDespawn()){
1828 $item = $entity->getPickedItem();
1833 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1834 $existingSlot = $this->inventory->first($item);
1835 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1840 if(!$ev->isCancelled()){
1841 $this->equipOrAddPickedItem($existingSlot, $item);
1847 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1848 if($existingSlot !== -1){
1849 if($existingSlot < $this->inventory->getHotbarSize()){
1850 $this->inventory->setHeldItemIndex($existingSlot);
1852 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1855 $firstEmpty = $this->inventory->firstEmpty();
1856 if($firstEmpty === -1){
1857 $this->inventory->setItemInHand($item);
1858 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1859 $this->inventory->setItem($firstEmpty, $item);
1860 $this->inventory->setHeldItemIndex($firstEmpty);
1862 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1863 $this->inventory->setItemInHand($item);
1874 if($pos->distanceSquared($this->location) > 10000){
1878 $target = $this->getWorld()->getBlock($pos);
1880 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1881 if($this->isSpectator()){
1885 if($ev->isCancelled()){
1888 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1889 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1893 $block = $target->getSide($face);
1894 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1895 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1896 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1900 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1901 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1907 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1908 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1909 $this->blockBreakHandler->setTargetedFace($face);
1913 public function stopBreakBlock(Vector3 $pos) : void{
1914 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1915 $this->blockBreakHandler =
null;
1925 $this->removeCurrentWindow();
1927 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1928 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1929 $this->stopBreakBlock($pos);
1930 $item = $this->inventory->getItemInHand();
1931 $oldItem = clone $item;
1932 $returnedItems = [];
1933 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1934 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1935 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1939 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1951 $this->setUsingItem(false);
1953 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1954 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1955 $item = $this->inventory->getItemInHand();
1956 $oldItem = clone $item;
1957 $returnedItems = [];
1958 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1959 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1963 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1976 if(!$entity->isAlive()){
1980 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1984 $heldItem = $this->inventory->getItemInHand();
1985 $oldItem = clone $heldItem;
1987 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1988 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1989 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1991 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1995 $meleeEnchantmentDamage = 0;
1997 $meleeEnchantments = [];
1998 foreach($heldItem->getEnchantments() as $enchantment){
1999 $type = $enchantment->getType();
2000 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2001 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2002 $meleeEnchantments[] = $enchantment;
2005 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2007 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2008 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2011 $entity->attack($ev);
2012 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2014 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2015 if($ev->isCancelled()){
2016 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2019 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2021 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2022 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2024 if($ev->getModifier(EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS) > 0 && $entity instanceof Living){
2025 $entity->broadcastAnimation(
new MagicHitAnimation($entity));
2028 foreach($meleeEnchantments as $enchantment){
2029 $type = $enchantment->getType();
2030 assert($type instanceof MeleeWeaponEnchantment);
2031 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2034 if($this->isAlive()){
2037 $returnedItems = [];
2038 $heldItem->onAttackEntity($entity, $returnedItems);
2039 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2041 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2054 if(!$ev->isCancelled()){
2055 $this->broadcastSound(new EntityAttackNoDamageSound());
2056 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2066 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2067 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2073 $item = $this->inventory->getItemInHand();
2074 $oldItem = clone $item;
2075 if(!$ev->isCancelled()){
2076 if($item->onInteractEntity($this, $entity, $clickPos)){
2077 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2078 if($item instanceof Durable && $item->isBroken()){
2079 $this->broadcastSound(new ItemBreakSound());
2081 $this->inventory->setItemInHand($item);
2084 return $entity->
onInteract($this, $clickPos);
2089 public function toggleSprint(
bool $sprint) : bool{
2090 if($sprint === $this->sprinting){
2093 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2095 if($ev->isCancelled()){
2098 $this->setSprinting($sprint);
2102 public function toggleSneak(
bool $sneak,
bool $sneakPressed =
true) : bool{
2103 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2106 $this->setSneakPressed($sneakPressed);
2108 $ev =
new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2109 if($sneak === $this->sneaking){
2114 if($ev->isCancelled()){
2117 $this->setSneaking($sneak);
2121 public function toggleFlight(
bool $fly) : bool{
2122 if($fly === $this->flying){
2125 $ev =
new PlayerToggleFlightEvent($this, $fly);
2126 if(!$this->allowFlight){
2130 if($ev->isCancelled()){
2133 $this->setFlying($fly);
2137 public function toggleGlide(
bool $glide) : bool{
2138 if($glide === $this->gliding){
2141 $ev =
new PlayerToggleGlideEvent($this, $glide);
2143 if($ev->isCancelled()){
2146 $this->setGliding($glide);
2150 public function toggleSwim(
bool $swim) : bool{
2151 if($swim === $this->swimming){
2154 $ev =
new PlayerToggleSwimEvent($this, $swim);
2156 if($ev->isCancelled()){
2159 $this->setSwimming($swim);
2163 public function emote(
string $emoteId) : void{
2164 $currentTick = $this->
server->getTick();
2165 if($currentTick - $this->lastEmoteTick > 5){
2166 $this->lastEmoteTick = $currentTick;
2167 $event =
new PlayerEmoteEvent($this, $emoteId);
2169 if(!$event->isCancelled()){
2170 $emoteId = $event->getEmoteId();
2171 parent::emote($emoteId);
2181 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2191 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2192 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2193 if($subtitle !==
""){
2194 $this->sendSubTitle($subtitle);
2196 $this->getNetworkSession()->onTitle($title);
2203 $this->getNetworkSession()->onSubTitle($subtitle);
2210 $this->getNetworkSession()->onActionBar($message);
2217 $this->getNetworkSession()->onClearTitle();
2224 $this->getNetworkSession()->onResetTitleOptions();
2235 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2236 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2244 $this->getNetworkSession()->onChatMessage($message);
2247 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2248 $this->getNetworkSession()->onJukeboxPopup($message);
2257 $this->getNetworkSession()->onPopup($message);
2260 public function sendTip(
string $message) : void{
2261 $this->getNetworkSession()->onTip($message);
2268 $this->getNetworkSession()->onToastNotification($title, $body);
2277 $id = $this->formIdCounter++;
2278 if($this->getNetworkSession()->onFormSent($id, $form)){
2279 $this->forms[$id] = $form;
2283 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2284 if(!isset($this->forms[$formId])){
2285 $this->logger->debug(
"Got unexpected response for form $formId");
2290 $this->forms[$formId]->handleResponse($this, $responseData);
2291 }
catch(FormValidationException $e){
2292 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2293 $this->logger->logException($e);
2295 unset($this->forms[$formId]);
2305 public function hasPendingForm(
int $formId) : bool{
2306 return isset($this->forms[$formId]);
2313 $this->getNetworkSession()->onCloseAllForms();
2328 if(!$ev->isCancelled()){
2329 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2344 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2346 if(!$ev->isCancelled()){
2347 $reason = $ev->getDisconnectReason();
2349 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2351 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2352 if($disconnectScreenMessage ===
""){
2353 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2355 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2377 if(!$this->isConnected()){
2381 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2382 $this->onPostDisconnect($reason, $quitMessage);
2393 if($this->isConnected()){
2394 throw new \LogicException(
"Player is still connected");
2398 $this->server->unsubscribeFromAllBroadcastChannels($this);
2400 $this->removeCurrentWindow();
2402 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2404 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2405 $this->server->broadcastMessage($quitMessage);
2409 $this->spawned =
false;
2412 $this->blockBreakHandler =
null;
2413 $this->despawnFromAll();
2415 $this->
server->removeOnlinePlayer($this);
2417 foreach($this->
server->getOnlinePlayers() as $player){
2418 if(!$player->canSee($this)){
2419 $player->showPlayer($this);
2422 $this->hiddenPlayers = [];
2424 if($this->location->isValid()){
2425 foreach($this->usedChunks as $index => $status){
2426 World::getXZ($index, $chunkX, $chunkZ);
2427 $this->unloadChunk($chunkX, $chunkZ);
2430 if(count($this->usedChunks) !== 0){
2431 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2433 $this->loadQueue = [];
2435 $this->removeCurrentWindow();
2436 $this->removePermanentInventories();
2438 $this->perm->getPermissionRecalculationCallbacks()->clear();
2440 $this->flagForDespawn();
2444 $this->disconnect(
"Player destroyed");
2445 $this->cursorInventory->removeAllViewers();
2446 $this->craftingGrid->removeAllViewers();
2447 parent::onDispose();
2451 $this->networkSession = null;
2452 unset($this->cursorInventory);
2453 unset($this->craftingGrid);
2454 $this->spawnPosition =
null;
2455 $this->deathPosition =
null;
2456 $this->blockBreakHandler =
null;
2457 parent::destroyCycles();
2467 public function __destruct(){
2468 parent::__destruct();
2469 $this->logger->debug(
"Destroyed by garbage collector");
2477 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2481 $nbt = $this->saveNBT();
2483 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2485 if($this->location->isValid()){
2486 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2489 if($this->hasValidCustomSpawn()){
2490 $spawn = $this->getSpawn();
2491 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2492 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2493 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2494 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2497 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2498 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2499 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2500 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2501 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2504 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2505 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2506 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2515 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2521 $this->removeCurrentWindow();
2523 $this->setDeathPosition($this->getPosition());
2525 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2528 if(!$ev->getKeepInventory()){
2529 foreach($ev->getDrops() as $item){
2530 $this->getWorld()->dropItem($this->location, $item);
2533 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2534 $this->inventory->setHeldItemIndex(0);
2535 $clearInventory($this->inventory);
2536 $clearInventory($this->armorInventory);
2537 $clearInventory($this->offHandInventory);
2540 if(!$ev->getKeepXp()){
2541 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2542 $this->xpManager->setXpAndProgress(0, 0.0);
2545 if($ev->getDeathMessage() !==
""){
2546 $this->server->broadcastMessage($ev->getDeathMessage());
2549 $this->startDeathAnimation();
2551 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2555 parent::onDeathUpdate($tickDiff);
2559 public function respawn() : void{
2560 if($this->
server->isHardcore()){
2561 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2562 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2567 $this->actuallyRespawn();
2570 protected function actuallyRespawn() : void{
2571 if($this->respawnLocked){
2574 $this->respawnLocked =
true;
2576 $this->logger->debug(
"Waiting for safe respawn position to be located");
2577 $spawn = $this->getSpawn();
2578 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2579 function(Position $safeSpawn) :
void{
2580 if(!$this->isConnected()){
2583 $this->logger->debug(
"Respawn position located, completing respawn");
2584 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2585 $spawnPosition = $ev->getRespawnPosition();
2586 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2587 if($spawnBlock instanceof RespawnAnchor){
2588 if($spawnBlock->getCharges() > 0){
2589 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2590 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2592 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2593 if($defaultSpawn !==
null){
2594 $this->setSpawn($defaultSpawn);
2595 $ev->setRespawnPosition($defaultSpawn);
2596 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2602 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2603 $this->teleport($realSpawn);
2605 $this->setSprinting(
false);
2606 $this->setSneaking(
false);
2607 $this->setFlying(
false);
2609 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2610 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2611 $this->deadTicks = 0;
2612 $this->noDamageTicks = 60;
2614 $this->effectManager->clear();
2615 $this->setHealth($this->getMaxHealth());
2617 foreach($this->attributeMap->getAll() as $attr){
2618 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2621 $attr->resetToDefault();
2624 $this->spawnToAll();
2625 $this->scheduleUpdate();
2627 $this->getNetworkSession()->onServerRespawn();
2628 $this->respawnLocked =
false;
2631 if($this->isConnected()){
2632 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2639 parent::applyPostDamageEffects($source);
2641 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2645 if(!$this->isAlive()){
2649 if($this->isCreative()
2650 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2653 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2657 parent::attack($source);
2660 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2661 parent::syncNetworkData($properties);
2663 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2664 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2666 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2667 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2669 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2670 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2672 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2673 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2675 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2676 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2677 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2681 public function sendData(?array $targets, ?array $data =
null) : void{
2682 if($targets === null){
2683 $targets = $this->getViewers();
2686 parent::sendData($targets, $data);
2690 if($this->spawned && $targets === null){
2691 $targets = $this->getViewers();
2694 parent::broadcastAnimation($animation, $targets);
2698 if($this->spawned && $targets === null){
2699 $targets = $this->getViewers();
2702 parent::broadcastSound($sound, $targets);
2708 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2709 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2715 if(parent::teleport($pos, $yaw, $pitch)){
2717 $this->removeCurrentWindow();
2720 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2721 $this->broadcastMovement(
true);
2723 $this->spawnToAll();
2725 $this->resetFallDistance();
2726 $this->nextChunkOrderRun = 0;
2727 if($this->spawnChunkLoadCount !== -1){
2728 $this->spawnChunkLoadCount = 0;
2730 $this->blockBreakHandler =
null;
2734 $this->resetLastMovements();
2742 protected function addDefaultWindows() : void{
2743 $this->cursorInventory = new PlayerCursorInventory($this);
2744 $this->craftingGrid =
new PlayerCraftingInventory($this);
2746 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2751 public function getCursorInventory() : PlayerCursorInventory{
2752 return $this->cursorInventory;
2755 public function getCraftingGrid() : CraftingGrid{
2756 return $this->craftingGrid;
2764 return $this->creativeInventory;
2771 $this->creativeInventory = $inventory;
2772 if($this->spawned && $this->isConnected()){
2773 $this->getNetworkSession()->getInvManager()?->syncCreative();
2781 private function doCloseInventory() : void{
2782 $inventories = [$this->craftingGrid, $this->cursorInventory];
2783 if($this->currentWindow instanceof TemporaryInventory){
2784 $inventories[] = $this->currentWindow;
2787 $builder =
new TransactionBuilder();
2788 foreach($inventories as $inventory){
2789 $contents = $inventory->getContents();
2791 if(count($contents) > 0){
2792 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2793 foreach($drops as $drop){
2794 $builder->addAction(
new DropItemAction($drop));
2797 $builder->getInventory($inventory)->clearAll();
2801 $actions = $builder->generateActions();
2802 if(count($actions) !== 0){
2803 $transaction =
new InventoryTransaction($this, $actions);
2805 $transaction->execute();
2806 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2807 }
catch(TransactionCancelledException){
2808 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2809 foreach($inventories as $inventory){
2810 $inventory->clearAll();
2812 }
catch(TransactionValidationException $e){
2813 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2822 return $this->currentWindow;
2829 if($inventory === $this->currentWindow){
2834 if($ev->isCancelled()){
2838 $this->removeCurrentWindow();
2840 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2841 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2843 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2844 $inventoryManager->onCurrentWindowChange($inventory);
2845 $inventory->onOpen($this);
2846 $this->currentWindow = $inventory;
2850 public function removeCurrentWindow() : void{
2851 $this->doCloseInventory();
2852 if($this->currentWindow !==
null){
2853 $currentWindow = $this->currentWindow;
2854 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2855 $this->currentWindow->onClose($this);
2856 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2857 $inventoryManager->onCurrentWindowRemove();
2859 $this->currentWindow =
null;
2860 (
new InventoryCloseEvent($currentWindow, $this))->call();
2864 protected function addPermanentInventories(Inventory ...$inventories) : void{
2865 foreach($inventories as $inventory){
2866 $inventory->onOpen($this);
2867 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2871 protected function removePermanentInventories() : void{
2872 foreach($this->permanentWindows as $inventory){
2873 $inventory->onClose($this);
2875 $this->permanentWindows = [];
2882 $block = $this->getWorld()->getBlock($position);
2884 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2885 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2887 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2891 use ChunkListenerNoOpTrait {
2892 onChunkChanged as
private;
2893 onChunkUnloaded as
private;
2897 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2898 if($status === UsedChunkStatus::SENT){
2899 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2900 $this->nextChunkOrderRun = 0;
2905 if($this->isUsingChunk($chunkX, $chunkZ)){
2906 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2907 $this->unloadChunk($chunkX, $chunkZ);