178 use PermissibleDelegateTrait;
180 private const MOVES_PER_TICK = 2;
181 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
184 private const MAX_CHAT_CHAR_LENGTH = 512;
190 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
191 private const MAX_REACH_DISTANCE_CREATIVE = 13;
192 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
193 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
195 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
197 public const TAG_FIRST_PLAYED =
"firstPlayed";
198 public const TAG_LAST_PLAYED =
"lastPlayed";
199 private const TAG_GAME_MODE =
"playerGameType";
200 private const TAG_SPAWN_WORLD =
"SpawnLevel";
201 private const TAG_SPAWN_X =
"SpawnX";
202 private const TAG_SPAWN_Y =
"SpawnY";
203 private const TAG_SPAWN_Z =
"SpawnZ";
204 private const TAG_DEATH_WORLD =
"DeathLevel";
205 private const TAG_DEATH_X =
"DeathPositionX";
206 private const TAG_DEATH_Y =
"DeathPositionY";
207 private const TAG_DEATH_Z =
"DeathPositionZ";
208 public const TAG_LEVEL =
"Level";
209 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
219 $lname = strtolower($name);
220 $len = strlen($name);
221 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
226 public bool $spawned =
false;
228 protected string $username;
229 protected string $displayName;
230 protected string $xuid =
"";
231 protected bool $authenticated;
234 protected ?InventoryWindow $currentWindow =
null;
236 protected array $permanentWindows = [];
237 protected Inventory $cursorInventory;
238 protected CraftingGrid $craftingGrid;
239 protected CreativeInventory $creativeInventory;
241 protected int $messageCounter = 2;
243 protected DateTimeImmutable $firstPlayed;
244 protected DateTimeImmutable $lastPlayed;
245 protected GameMode $gamemode;
251 protected array $usedChunks = [];
256 private array $activeChunkGenerationRequests = [];
261 protected array $loadQueue = [];
262 protected int $nextChunkOrderRun = 5;
265 private array $tickingChunks = [];
267 protected int $viewDistance = -1;
268 protected int $spawnThreshold;
269 protected int $spawnChunkLoadCount = 0;
270 protected int $chunksPerTick;
271 protected ChunkSelector $chunkSelector;
272 protected ChunkLoader $chunkLoader;
273 protected ChunkTicker $chunkTicker;
276 protected array $hiddenPlayers = [];
278 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
279 protected ?
float $lastMovementProcess =
null;
281 protected int $inAirTicks = 0;
283 protected float $stepHeight = 0.6;
285 protected ?Vector3 $sleeping =
null;
286 private ?
Position $spawnPosition =
null;
288 private bool $respawnLocked =
false;
290 private ?
Position $deathPosition =
null;
293 protected bool $autoJump =
true;
294 protected bool $allowFlight =
false;
295 protected bool $blockCollision =
true;
296 protected bool $flying =
false;
297 protected bool $sneakPressed =
false;
299 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
302 protected ?
int $lineHeight =
null;
305 protected string $locale =
"en_US";
307 protected int $startAction = -1;
313 protected array $usedItemsCooldown = [];
315 private int $lastEmoteTick = 0;
317 protected int $formIdCounter = 0;
319 protected array $forms = [];
321 protected \Logger $logger;
326 $username = TextFormat::clean($playerInfo->getUsername());
327 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
330 $this->networkSession = $session;
331 $this->playerInfo = $playerInfo;
332 $this->authenticated = $authenticated;
334 $this->username = $username;
335 $this->displayName = $this->username;
336 $this->locale = $this->playerInfo->getLocale();
338 $this->uuid = $this->playerInfo->getUuid();
339 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
341 $this->creativeInventory = CreativeInventory::getInstance();
343 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
344 if($this->
server->isOp($this->username)){
345 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
350 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
351 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
356 $world = $spawnLocation->
getWorld();
358 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
359 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
360 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
361 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
362 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
364 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
368 $this->setNameTag($this->username);
371 private function callDummyItemHeldEvent() : void{
372 $slot = $this->hotbar->getSelectedIndex();
381 protected function initEntity(
CompoundTag $nbt) : void{
382 parent::initEntity($nbt);
383 $this->addDefaultWindows();
385 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
386 function(Inventory $unused,
int $slot) :
void{
387 if($slot === $this->hotbar->getSelectedIndex()){
388 $this->setUsingItem(
false);
390 $this->callDummyItemHeldEvent();
394 $this->setUsingItem(
false);
395 $this->callDummyItemHeldEvent();
399 $now = (int) (microtime(
true) * 1000);
400 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
401 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
403 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
404 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
406 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
407 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
409 $this->internalSetGameMode($this->
server->getGamemode());
412 $this->keepMovement =
true;
414 $this->setNameTagVisible();
415 $this->setNameTagAlwaysVisible();
416 $this->setCanClimb();
418 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
419 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
421 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
422 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
426 public function getLeaveMessage() : Translatable|string{
428 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
434 public function isAuthenticated() : bool{
435 return $this->authenticated;
460 return parent::getUniqueId();
467 return $this->firstPlayed;
474 return $this->lastPlayed;
477 public function hasPlayedBefore() : bool{
478 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
491 if($this->allowFlight !== $value){
492 $this->allowFlight = $value;
493 $this->getNetworkSession()->syncAbilities($this);
504 return $this->allowFlight;
516 if($this->blockCollision !== $value){
517 $this->blockCollision = $value;
518 $this->getNetworkSession()->syncAbilities($this);
527 return $this->blockCollision;
530 public function setFlying(
bool $value) : void{
531 if($this->flying !== $value){
532 $this->flying = $value;
533 $this->resetFallDistance();
534 $this->getNetworkSession()->syncAbilities($this);
538 public function isFlying() : bool{
539 return $this->flying;
556 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
557 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
558 $this->getNetworkSession()->syncAbilities($this);
574 return $this->flightSpeedMultiplier;
577 public function setAutoJump(
bool $value) : void{
578 if($this->autoJump !== $value){
579 $this->autoJump = $value;
580 $this->getNetworkSession()->syncAdventureSettings();
584 public function hasAutoJump() : bool{
585 return $this->autoJump;
588 public function spawnTo(Player $player) : void{
589 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
590 parent::spawnTo($player);
594 public function getServer() : Server{
599 return $this->lineHeight ?? 7;
603 if($height !== null && $height < 1){
604 throw new \InvalidArgumentException(
"Line height must be at least 1");
606 $this->lineHeight = $height;
611 public function canSee(
Player $player) : bool{
612 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
615 public function hidePlayer(
Player $player) : void{
616 if($player === $this){
619 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
620 $player->despawnFrom($this);
623 public function showPlayer(Player $player) : void{
624 if($player === $this){
627 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
628 if($player->isOnline()){
629 $player->spawnTo($this);
633 public function canCollideWith(Entity $entity) : bool{
637 public function canBeCollidedWith() : bool{
638 return !$this->isSpectator() && parent::canBeCollidedWith();
641 public function resetFallDistance() : void{
642 parent::resetFallDistance();
643 $this->inAirTicks = 0;
646 public function getViewDistance() : int{
647 return $this->viewDistance;
650 public function setViewDistance(
int $distance) : void{
651 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
653 if($newViewDistance !== $this->viewDistance){
654 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
658 $this->viewDistance = $newViewDistance;
660 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
662 $this->nextChunkOrderRun = 0;
664 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
666 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
669 public function isOnline() : bool{
670 return $this->isConnected();
673 public function isConnected() : bool{
674 return $this->networkSession !== null && $this->networkSession->isConnected();
677 public function getNetworkSession() : NetworkSession{
678 if($this->networkSession === null){
679 throw new \LogicException(
"Player is not connected");
681 return $this->networkSession;
688 return $this->username;
695 return $this->displayName;
698 public function setDisplayName(
string $name) : void{
702 $this->displayName = $ev->getNewName();
713 return $this->locale;
716 public function getLanguage() :
Language{
717 return $this->
server->getLanguage();
724 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
728 if($ev->isCancelled()){
729 $this->sendSkin([$this]);
733 $this->setSkin($ev->getNewSkin());
734 $this->sendSkin($this->server->getOnlinePlayers());
743 public function sendSkin(?array $targets =
null) : void{
744 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
751 return $this->startAction > -1;
754 public function setUsingItem(
bool $value) : void{
755 $this->startAction = $value ? $this->
server->getTick() : -1;
756 $this->networkPropertiesDirty =
true;
764 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
771 $this->checkItemCooldowns();
772 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
779 $this->checkItemCooldowns();
780 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
787 $ticks = $ticks ?? $item->getCooldownTicks();
789 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
790 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
794 protected function checkItemCooldowns() : void{
795 $serverTick = $this->
server->getTick();
796 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
797 if($cooldownUntil <= $serverTick){
798 unset($this->usedItemsCooldown[$itemId]);
803 protected function setPosition(Vector3 $pos) : bool{
804 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
805 if(parent::setPosition($pos)){
806 $newWorld = $this->getWorld();
807 if($oldWorld !== $newWorld){
808 if($oldWorld !==
null){
809 foreach($this->usedChunks as $index => $status){
810 World::getXZ($index, $X, $Z);
811 $this->unloadChunk($X, $Z, $oldWorld);
815 $this->usedChunks = [];
816 $this->loadQueue = [];
817 $this->getNetworkSession()->onEnterWorld();
826 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
827 $world = $world ?? $this->getWorld();
828 $index = World::chunkHash($x, $z);
829 if(isset($this->usedChunks[$index])){
830 foreach($world->getChunkEntities($x, $z) as $entity){
831 if($entity !== $this){
832 $entity->despawnFrom($this);
835 $this->getNetworkSession()->stopUsingChunk($x, $z);
836 unset($this->usedChunks[$index]);
837 unset($this->activeChunkGenerationRequests[$index]);
839 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
840 $world->unregisterChunkListener($this, $x, $z);
841 unset($this->loadQueue[$index]);
842 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
843 unset($this->tickingChunks[$index]);
846 protected function spawnEntitiesOnAllChunks() : void{
847 foreach($this->usedChunks as $chunkHash => $status){
848 if($status === UsedChunkStatus::SENT){
849 World::getXZ($chunkHash, $chunkX, $chunkZ);
850 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
855 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
856 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
857 if($entity !== $this && !$entity->isFlaggedForDespawn()){
858 $entity->spawnTo($this);
868 if(!$this->isConnected()){
872 Timings::$playerChunkSend->startTiming();
875 $world = $this->getWorld();
877 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
878 foreach($this->loadQueue as $index => $distance){
879 if($count >= $limit){
885 World::getXZ($index, $X, $Z);
889 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
890 $this->activeChunkGenerationRequests[$index] =
true;
891 unset($this->loadQueue[$index]);
892 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
893 $world->registerChunkListener($this, $X, $Z);
894 if(isset($this->tickingChunks[$index])){
895 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
898 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
899 function() use ($X, $Z, $index, $world) :
void{
900 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
903 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
909 unset($this->activeChunkGenerationRequests[$index]);
910 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
912 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
913 $this->usedChunks[$index] = UsedChunkStatus::SENT;
914 if($this->spawnChunkLoadCount === -1){
915 $this->spawnEntitiesOnChunk($X, $Z);
916 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
917 $this->spawnChunkLoadCount = -1;
919 $this->spawnEntitiesOnAllChunks();
921 $this->getNetworkSession()->notifyTerrainReady();
923 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
926 static function() :
void{
932 Timings::$playerChunkSend->stopTiming();
935 private function recheckBroadcastPermissions() : void{
937 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
938 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
939 ] as $permission => $channel){
940 if($this->hasPermission($permission)){
941 $this->
server->subscribeToBroadcastChannel($channel, $this);
943 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
956 $this->spawned =
true;
957 $this->recheckBroadcastPermissions();
958 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
959 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
960 $this->recheckBroadcastPermissions();
964 $ev =
new PlayerJoinEvent($this,
965 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
968 if($ev->getJoinMessage() !==
""){
969 $this->server->broadcastMessage($ev->getJoinMessage());
972 $this->noDamageTicks = 60;
976 if($this->getHealth() <= 0){
977 $this->logger->debug(
"Quit while dead, forcing respawn");
978 $this->actuallyRespawn();
989 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
990 $world = $this->getWorld();
991 foreach($oldTickingChunks as $hash => $_){
992 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
994 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
995 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
998 foreach($newTickingChunks as $hash => $_){
999 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
1001 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1002 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1012 if(!$this->isConnected() || $this->viewDistance === -1){
1016 Timings::$playerChunkOrder->startTiming();
1019 $tickingChunks = [];
1020 $unloadChunks = $this->usedChunks;
1022 $world = $this->getWorld();
1023 $tickingChunkRadius = $world->getChunkTickRadius();
1025 foreach($this->chunkSelector->selectChunks(
1026 $this->server->getAllowedViewDistance($this->viewDistance),
1027 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1028 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1029 ) as $radius => $hash){
1030 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1031 $newOrder[$hash] =
true;
1033 if($radius < $tickingChunkRadius){
1034 $tickingChunks[$hash] =
true;
1036 unset($unloadChunks[$hash]);
1039 foreach($unloadChunks as $index => $status){
1040 World::getXZ($index, $X, $Z);
1041 $this->unloadChunk($X, $Z);
1044 $this->loadQueue = $newOrder;
1046 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1047 $this->tickingChunks = $tickingChunks;
1049 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1050 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1053 Timings::$playerChunkOrder->stopTiming();
1061 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1069 return $this->usedChunks;
1076 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1083 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1084 return $status === UsedChunkStatus::SENT;
1091 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1092 $this->nextChunkOrderRun = PHP_INT_MAX;
1093 $this->orderChunks();
1096 if(count($this->loadQueue) > 0){
1097 $this->requestChunks();
1101 public function getDeathPosition() : ?Position{
1102 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1103 $this->deathPosition =
null;
1105 return $this->deathPosition;
1113 if($pos instanceof
Position && $pos->world !==
null){
1114 $world = $pos->world;
1116 $world = $this->getWorld();
1118 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1120 $this->deathPosition =
null;
1122 $this->networkPropertiesDirty =
true;
1129 if($this->hasValidCustomSpawn()){
1130 return $this->spawnPosition;
1132 $world = $this->
server->getWorldManager()->getDefaultWorld();
1134 return $world->getSpawnLocation();
1138 public function hasValidCustomSpawn() : bool{
1139 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1151 $world = $this->getWorld();
1153 $world = $pos->getWorld();
1155 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1157 $this->spawnPosition =
null;
1159 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1162 public function isSleeping() : bool{
1163 return $this->sleeping !== null;
1166 public function sleepOn(Vector3 $pos) : bool{
1167 $pos = $pos->floor();
1168 $b = $this->getWorld()->getBlock($pos);
1170 $ev =
new PlayerBedEnterEvent($this, $b);
1172 if($ev->isCancelled()){
1176 if($b instanceof Bed){
1178 $this->getWorld()->setBlock($pos, $b);
1181 $this->sleeping = $pos;
1182 $this->networkPropertiesDirty =
true;
1184 $this->setSpawn($pos);
1186 $this->getWorld()->setSleepTicks(60);
1191 public function stopSleep() : void{
1192 if($this->sleeping instanceof Vector3){
1193 $b = $this->getWorld()->getBlock($this->sleeping);
1194 if($b instanceof Bed){
1195 $b->setOccupied(
false);
1196 $this->getWorld()->setBlock($this->sleeping, $b);
1198 (
new PlayerBedLeaveEvent($this, $b))->call();
1200 $this->sleeping =
null;
1201 $this->networkPropertiesDirty =
true;
1203 $this->getWorld()->setSleepTicks(0);
1205 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1209 public function getGamemode() : GameMode{
1210 return $this->gamemode;
1213 protected function internalSetGameMode(GameMode $gameMode) : void{
1214 $this->gamemode = $gameMode;
1216 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1217 $this->hungerManager->setEnabled($this->isSurvival());
1219 if($this->isSpectator()){
1220 $this->setFlying(
true);
1221 $this->setHasBlockCollision(
false);
1223 $this->onGround =
false;
1227 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1229 if($this->isSurvival()){
1230 $this->setFlying(
false);
1232 $this->setHasBlockCollision(
true);
1233 $this->setSilent(
false);
1234 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1242 if($this->gamemode === $gm){
1248 if($ev->isCancelled()){
1252 $this->internalSetGameMode($gm);
1254 if($this->isSpectator()){
1255 $this->despawnFromAll();
1257 $this->spawnToAll();
1260 $this->getNetworkSession()->syncGameMode($this->gamemode);
1271 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1281 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1291 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1294 public function isSpectator() : bool{
1295 return $this->gamemode === GameMode::SPECTATOR;
1298 public function setSneakPressed(
bool $sneakPressed) : void{
1299 $this->sneakPressed = $sneakPressed;
1307 return $this->sneakPressed;
1314 return $this->gamemode !== GameMode::CREATIVE;
1318 if($this->hasFiniteResources()){
1319 return parent::getDrops();
1326 if($this->hasFiniteResources()){
1327 return parent::getXpDropAmount();
1333 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1334 if(!$this->blockCollision){
1335 $this->onGround =
false;
1338 $bb =
new AxisAlignedBB(
1339 $this->boundingBox->minX,
1340 $this->location->y - 0.2,
1341 $this->boundingBox->minZ,
1342 $this->boundingBox->maxX,
1343 $this->location->y + 0.2,
1344 $this->boundingBox->maxZ
1349 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1351 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1359 protected function checkNearEntities() : void{
1360 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1361 $entity->scheduleUpdate();
1363 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1367 $entity->onCollideWithPlayer($this);
1371 public function getInAirTicks() : int{
1372 return $this->inAirTicks;
1384 Timings::$playerMove->startTiming();
1386 $this->actuallyHandleMovement($newPos);
1388 Timings::$playerMove->stopTiming();
1392 private function actuallyHandleMovement(Vector3 $newPos) : void{
1393 $this->moveRateLimit--;
1394 if($this->moveRateLimit < 0){
1398 $oldPos = $this->location;
1399 $distanceSquared = $newPos->distanceSquared($oldPos);
1403 if($distanceSquared > 225){
1415 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1416 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1418 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1420 $this->nextChunkOrderRun = 0;
1423 if(!$revert && $distanceSquared !== 0.0){
1424 $dx = $newPos->x - $oldPos->x;
1425 $dy = $newPos->y - $oldPos->y;
1426 $dz = $newPos->z - $oldPos->z;
1428 $this->move($dx, $dy, $dz);
1432 $this->revertMovement($oldPos);
1440 $now = microtime(true);
1441 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1442 $exceededRateLimit = $this->moveRateLimit < 0;
1443 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1444 $this->lastMovementProcess = $now;
1446 $from = clone $this->lastLocation;
1447 $to = clone $this->location;
1449 $delta = $to->distanceSquared($from);
1450 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1452 if($delta > 0.0001 || $deltaAngle > 1.0){
1453 if(PlayerMoveEvent::hasHandlers()){
1458 if($ev->isCancelled()){
1459 $this->revertMovement($from);
1463 if($to->distanceSquared($ev->getTo()) > 0.01){
1464 $this->teleport($ev->getTo());
1469 $this->lastLocation = $to;
1470 $this->broadcastMovement();
1472 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1473 if($horizontalDistanceTravelled > 0){
1475 if($this->isSprinting()){
1476 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1478 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1481 if($this->nextChunkOrderRun > 20){
1482 $this->nextChunkOrderRun = 20;
1487 if($exceededRateLimit){
1488 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1489 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1493 protected function revertMovement(Location $from) : void{
1494 $this->setPosition($from);
1495 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1498 protected function calculateFallDamage(
float $fallDistance) : float{
1499 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1507 public function setMotion(
Vector3 $motion) : bool{
1508 if(parent::setMotion($motion)){
1509 $this->broadcastMotion();
1510 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1517 protected function updateMovement(
bool $teleport =
false) : void{
1521 protected function tryChangeMovement() : void{
1525 public function onUpdate(int $currentTick) : bool{
1526 $tickDiff = $currentTick - $this->lastUpdate;
1532 $this->messageCounter = 2;
1534 $this->lastUpdate = $currentTick;
1536 if($this->justCreated){
1537 $this->onFirstUpdate($currentTick);
1540 if(!$this->isAlive() && $this->spawned){
1541 $this->onDeathUpdate($tickDiff);
1545 $this->timings->startTiming();
1548 Timings::$playerMove->startTiming();
1549 $this->processMostRecentMovements();
1550 $this->motion = Vector3::zero();
1551 if($this->onGround){
1552 $this->inAirTicks = 0;
1554 $this->inAirTicks += $tickDiff;
1556 Timings::$playerMove->stopTiming();
1558 Timings::$entityBaseTick->startTiming();
1559 $this->entityBaseTick($tickDiff);
1560 Timings::$entityBaseTick->stopTiming();
1562 if($this->isCreative() && $this->fireTicks > 1){
1563 $this->fireTicks = 1;
1566 if(!$this->isSpectator() && $this->isAlive()){
1567 Timings::$playerCheckNearEntities->startTiming();
1568 $this->checkNearEntities();
1569 Timings::$playerCheckNearEntities->stopTiming();
1572 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1573 $this->blockBreakHandler =
null;
1576 if($this->isUsingItem() && $this->getItemUseDuration() % 4 === 0 && ($item = $this->getMainHandItem()) instanceof ConsumableItem){
1577 $this->broadcastAnimation(
new ConsumingItemAnimation($this, $item));
1581 $this->timings->stopTiming();
1587 return $this->isCreative() || parent::canEat();
1591 return $this->isCreative() || parent::canBreathe();
1600 $eyePos = $this->getEyePos();
1601 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1605 $dV = $this->getDirectionVector();
1606 $eyeDot = $dV->dot($eyePos);
1607 $targetDot = $dV->dot($pos);
1608 return ($targetDot - $eyeDot) >= -$maxDiff;
1615 public function chat(
string $message) : bool{
1616 $this->removeCurrentWindow();
1618 if($this->messageCounter <= 0){
1624 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1625 if(strlen($message) > $maxTotalLength){
1629 $message = TextFormat::clean($message,
false);
1630 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1631 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1632 if(str_starts_with($messagePart,
'./')){
1633 $messagePart = substr($messagePart, 1);
1636 if(str_starts_with($messagePart,
"/")){
1637 Timings::$playerCommand->startTiming();
1638 $this->server->dispatchCommand($this, substr($messagePart, 1));
1639 Timings::$playerCommand->stopTiming();
1641 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1643 if(!$ev->isCancelled()){
1644 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1653 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1654 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1657 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1661 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1663 if($ev->isCancelled()){
1667 $this->hotbar->setSelectedIndex($hotbarSlot);
1668 $this->setUsingItem(
false);
1676 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1677 $heldItemChanged = false;
1679 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1682 $newReplica = clone $oldHeldItem;
1683 $newReplica->setCount($newHeldItem->getCount());
1684 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1685 $newDamage = $newHeldItem->getDamage();
1686 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1687 $newReplica->setDamage($newDamage);
1690 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1692 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1693 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1694 $this->broadcastSound(
new ItemBreakSound());
1696 $this->setMainHandItem($newHeldItem);
1697 $heldItemChanged =
true;
1701 if(!$heldItemChanged){
1702 $newHeldItem = $oldHeldItem;
1705 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1706 $this->setMainHandItem(array_shift($extraReturnedItems));
1708 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1710 $ev =
new PlayerDropItemEvent($this, $drop);
1711 if($this->isSpectator()){
1715 if(!$ev->isCancelled()){
1716 $this->dropItem($drop);
1727 $directionVector = $this->getDirectionVector();
1728 $item = $this->getMainHandItem();
1729 $oldItem = clone $item;
1732 if($this->hasItemCooldown($item) || $this->isSpectator()){
1738 if($ev->isCancelled()){
1742 $returnedItems = [];
1743 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1744 if($result === ItemUseResult::FAIL){
1748 $this->resetItemCooldown($oldItem);
1749 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1751 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1762 $slot = $this->getMainHandItem();
1764 $oldItem = clone $slot;
1766 $residue = $slot->getResidue();
1768 if($this->hasItemCooldown($slot)){
1773 if($ev->isCancelled() || !$this->consumeObject($slot)){
1777 $this->setUsingItem(
false);
1778 $this->resetItemCooldown($oldItem);
1781 $this->returnItemsFromAction($oldItem, $slot, $ev->getResidue());
1796 $item = $this->getMainHandItem();
1797 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1801 $oldItem = clone $item;
1803 $returnedItems = [];
1804 $result = $item->onReleaseUsing($this, $returnedItems);
1805 if($result === ItemUseResult::SUCCESS){
1806 $this->resetItemCooldown($oldItem);
1807 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1813 $this->setUsingItem(
false);
1817 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1818 $block = $this->getWorld()->getBlock($pos);
1819 if($block instanceof UnknownBlock){
1823 $item = $block->getPickedItem($addTileNBT);
1825 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1826 $existingSlot = $this->inventory->first($item);
1827 if($existingSlot === -1 && $this->hasFiniteResources()){
1832 if(!$ev->isCancelled()){
1833 $this->equipOrAddPickedItem($existingSlot, $item);
1839 public function pickEntity(
int $entityId) : bool{
1840 $entity = $this->getWorld()->getEntity($entityId);
1843 if($entity ===
null || $entity->isFlaggedForDespawn()){
1847 $item = $entity->getPickedItem();
1852 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1853 $existingSlot = $this->inventory->first($item);
1854 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1859 if(!$ev->isCancelled()){
1860 $this->equipOrAddPickedItem($existingSlot, $item);
1866 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1867 if($existingSlot !== -1){
1868 if($existingSlot < $this->hotbar->getSize()){
1869 $this->hotbar->setSelectedIndex($existingSlot);
1871 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1874 $firstEmpty = $this->inventory->firstEmpty();
1875 if($firstEmpty === -1){
1876 $this->setMainHandItem($item);
1877 }elseif($firstEmpty < $this->hotbar->getSize()){
1878 $this->inventory->setItem($firstEmpty, $item);
1879 $this->hotbar->setSelectedIndex($firstEmpty);
1881 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1882 $this->setMainHandItem($item);
1893 if($pos->distanceSquared($this->location) > 10000){
1897 $target = $this->getWorld()->getBlock($pos);
1899 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1900 if($this->isSpectator()){
1904 if($ev->isCancelled()){
1907 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1908 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1912 $block = $target->getSide($face);
1913 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1914 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1915 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1919 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1920 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1926 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1927 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1928 $this->blockBreakHandler->setTargetedFace($face);
1932 public function stopBreakBlock(Vector3 $pos) : void{
1933 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1934 $this->blockBreakHandler =
null;
1944 $this->removeCurrentWindow();
1946 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1947 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1948 $this->stopBreakBlock($pos);
1949 $item = $this->getMainHandItem();
1950 $oldItem = clone $item;
1951 $returnedItems = [];
1952 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1953 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1954 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1958 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1970 $this->setUsingItem(false);
1972 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1973 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1974 $item = $this->getMainHandItem();
1975 $oldItem = clone $item;
1976 $returnedItems = [];
1977 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1978 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1982 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1995 if(!$entity->isAlive()){
1999 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
2003 $heldItem = $this->getMainHandItem();
2004 $oldItem = clone $heldItem;
2006 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
2007 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2008 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
2010 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
2014 $meleeEnchantmentDamage = 0;
2016 $meleeEnchantments = [];
2017 foreach($heldItem->getEnchantments() as $enchantment){
2018 $type = $enchantment->getType();
2019 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2020 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2021 $meleeEnchantments[] = $enchantment;
2024 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2026 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2027 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2030 $entity->attack($ev);
2031 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2033 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2034 if($ev->isCancelled()){
2035 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2038 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2040 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2041 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2043 if($ev->getModifier(EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS) > 0 && $entity instanceof Living){
2044 $entity->broadcastAnimation(
new MagicHitAnimation($entity));
2047 foreach($meleeEnchantments as $enchantment){
2048 $type = $enchantment->getType();
2049 assert($type instanceof MeleeWeaponEnchantment);
2050 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2053 if($this->isAlive()){
2056 $returnedItems = [];
2057 $heldItem->onAttackEntity($entity, $returnedItems);
2058 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2060 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2073 if(!$ev->isCancelled()){
2074 $this->broadcastSound(new EntityAttackNoDamageSound());
2075 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2085 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2086 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2092 $item = $this->getMainHandItem();
2093 $oldItem = clone $item;
2094 if(!$ev->isCancelled()){
2095 if($item->onInteractEntity($this, $entity, $clickPos)){
2096 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2097 if($item instanceof Durable && $item->isBroken()){
2098 $this->broadcastSound(new ItemBreakSound());
2100 $this->setMainHandItem($item);
2103 return $entity->
onInteract($this, $clickPos);
2108 public function toggleSprint(
bool $sprint) : bool{
2109 if($sprint === $this->sprinting){
2112 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2114 if($ev->isCancelled()){
2117 $this->setSprinting($sprint);
2121 public function toggleSneak(
bool $sneak,
bool $sneakPressed =
true) : bool{
2122 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2125 $this->setSneakPressed($sneakPressed);
2127 $ev =
new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2128 if($sneak === $this->sneaking){
2133 if($ev->isCancelled()){
2136 $this->setSneaking($sneak);
2140 public function toggleFlight(
bool $fly) : bool{
2141 if($fly === $this->flying){
2144 $ev =
new PlayerToggleFlightEvent($this, $fly);
2145 if(!$this->allowFlight){
2149 if($ev->isCancelled()){
2152 $this->setFlying($fly);
2156 public function toggleGlide(
bool $glide) : bool{
2157 if($glide === $this->gliding){
2160 $ev =
new PlayerToggleGlideEvent($this, $glide);
2162 if($ev->isCancelled()){
2165 $this->setGliding($glide);
2169 public function toggleSwim(
bool $swim) : bool{
2170 if($swim === $this->swimming){
2173 $ev =
new PlayerToggleSwimEvent($this, $swim);
2175 if($ev->isCancelled()){
2178 $this->setSwimming($swim);
2182 public function emote(
string $emoteId) : void{
2183 $currentTick = $this->
server->getTick();
2184 if($currentTick - $this->lastEmoteTick > 5){
2185 $this->lastEmoteTick = $currentTick;
2186 $event =
new PlayerEmoteEvent($this, $emoteId);
2188 if(!$event->isCancelled()){
2189 $emoteId = $event->getEmoteId();
2190 parent::emote($emoteId);
2200 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2210 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2211 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2212 if($subtitle !==
""){
2213 $this->sendSubTitle($subtitle);
2215 $this->getNetworkSession()->onTitle($title);
2222 $this->getNetworkSession()->onSubTitle($subtitle);
2229 $this->getNetworkSession()->onActionBar($message);
2236 $this->getNetworkSession()->onClearTitle();
2243 $this->getNetworkSession()->onResetTitleOptions();
2254 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2255 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2263 $this->getNetworkSession()->onChatMessage($message);
2266 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2267 $this->getNetworkSession()->onJukeboxPopup($message);
2276 $this->getNetworkSession()->onPopup($message);
2279 public function sendTip(
string $message) : void{
2280 $this->getNetworkSession()->onTip($message);
2287 $this->getNetworkSession()->onToastNotification($title, $body);
2296 $id = $this->formIdCounter++;
2297 if($this->getNetworkSession()->onFormSent($id, $form)){
2298 $this->forms[$id] = $form;
2302 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2303 if(!isset($this->forms[$formId])){
2304 $this->logger->debug(
"Got unexpected response for form $formId");
2309 $this->forms[$formId]->handleResponse($this, $responseData);
2310 }
catch(FormValidationException $e){
2311 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2312 $this->logger->logException($e);
2314 unset($this->forms[$formId]);
2324 public function hasPendingForm(
int $formId) : bool{
2325 return isset($this->forms[$formId]);
2332 $this->getNetworkSession()->onCloseAllForms();
2347 if(!$ev->isCancelled()){
2348 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2363 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2365 if(!$ev->isCancelled()){
2366 $reason = $ev->getDisconnectReason();
2368 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2370 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2371 if($disconnectScreenMessage ===
""){
2372 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2374 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2396 if(!$this->isConnected()){
2400 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2401 $this->onPostDisconnect($reason, $quitMessage);
2412 if($this->isConnected()){
2413 throw new \LogicException(
"Player is still connected");
2417 $this->server->unsubscribeFromAllBroadcastChannels($this);
2419 $this->removeCurrentWindow();
2421 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2423 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2424 $this->server->broadcastMessage($quitMessage);
2428 $this->spawned =
false;
2431 $this->blockBreakHandler =
null;
2432 $this->despawnFromAll();
2434 $this->
server->removeOnlinePlayer($this);
2436 foreach($this->
server->getOnlinePlayers() as $player){
2437 if(!$player->canSee($this)){
2438 $player->showPlayer($this);
2441 $this->hiddenPlayers = [];
2443 if($this->location->isValid()){
2444 foreach($this->usedChunks as $index => $status){
2445 World::getXZ($index, $chunkX, $chunkZ);
2446 $this->unloadChunk($chunkX, $chunkZ);
2449 if(count($this->usedChunks) !== 0){
2450 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2452 $this->loadQueue = [];
2454 $this->removeCurrentWindow();
2455 $this->removePermanentWindows();
2457 $this->perm->getPermissionRecalculationCallbacks()->clear();
2459 $this->flagForDespawn();
2463 $this->disconnect(
"Player destroyed");
2464 $this->cursorInventory->removeAllWindows();
2465 $this->craftingGrid->removeAllWindows();
2466 parent::onDispose();
2470 $this->networkSession = null;
2471 $this->spawnPosition =
null;
2472 $this->deathPosition =
null;
2473 $this->blockBreakHandler =
null;
2474 parent::destroyCycles();
2484 public function __destruct(){
2485 parent::__destruct();
2486 $this->logger->debug(
"Destroyed by garbage collector");
2494 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2498 $nbt = $this->saveNBT();
2500 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2502 if($this->location->isValid()){
2503 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2506 if($this->hasValidCustomSpawn()){
2507 $spawn = $this->getSpawn();
2508 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2509 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2510 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2511 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2514 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2515 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2516 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2517 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2518 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2521 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2522 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2523 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2532 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2538 $this->removeCurrentWindow();
2540 $this->setDeathPosition($this->getPosition());
2542 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2545 if(!$ev->getKeepInventory()){
2546 foreach($ev->getDrops() as $item){
2547 $this->getWorld()->dropItem($this->location, $item);
2550 $this->hotbar->setSelectedIndex(0);
2551 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2552 $clearInventory($this->inventory);
2553 $clearInventory($this->armorInventory);
2554 $clearInventory($this->offHandInventory);
2557 if(!$ev->getKeepXp()){
2558 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2559 $this->xpManager->setXpAndProgress(0, 0.0);
2562 if($ev->getDeathMessage() !==
""){
2563 $this->server->broadcastMessage($ev->getDeathMessage());
2566 $this->startDeathAnimation();
2568 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2572 parent::onDeathUpdate($tickDiff);
2576 public function respawn() : void{
2577 if($this->
server->isHardcore()){
2578 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2579 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2584 $this->actuallyRespawn();
2587 protected function actuallyRespawn() : void{
2588 if($this->respawnLocked){
2591 $this->respawnLocked =
true;
2593 $this->logger->debug(
"Waiting for safe respawn position to be located");
2594 $spawn = $this->getSpawn();
2595 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2596 function(Position $safeSpawn) :
void{
2597 if(!$this->isConnected()){
2600 $this->logger->debug(
"Respawn position located, completing respawn");
2601 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2602 $spawnPosition = $ev->getRespawnPosition();
2603 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2604 if($spawnBlock instanceof RespawnAnchor){
2605 if($spawnBlock->getCharges() > 0){
2606 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2607 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2609 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2610 if($defaultSpawn !==
null){
2611 $this->setSpawn($defaultSpawn);
2612 $ev->setRespawnPosition($defaultSpawn);
2613 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2619 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2620 $this->teleport($realSpawn);
2622 $this->setSprinting(
false);
2623 $this->setSneaking(
false);
2624 $this->setFlying(
false);
2626 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2627 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2628 $this->deadTicks = 0;
2629 $this->noDamageTicks = 60;
2631 $this->effectManager->clear();
2632 $this->setHealth($this->getMaxHealth());
2634 foreach($this->attributeMap->getAll() as $attr){
2635 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2638 $attr->resetToDefault();
2641 $this->spawnToAll();
2642 $this->scheduleUpdate();
2644 $this->getNetworkSession()->onServerRespawn();
2645 $this->respawnLocked =
false;
2648 if($this->isConnected()){
2649 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2656 parent::applyPostDamageEffects($source);
2658 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2662 if(!$this->isAlive()){
2666 if($this->isCreative()
2667 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2670 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2674 parent::attack($source);
2677 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2678 parent::syncNetworkData($properties);
2680 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2681 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2683 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2684 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2686 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2687 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2689 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2690 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2692 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2693 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2694 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2698 public function sendData(?array $targets, ?array $data =
null) : void{
2699 if($targets === null){
2700 $targets = $this->getViewers();
2703 parent::sendData($targets, $data);
2707 if($this->spawned && $targets === null){
2708 $targets = $this->getViewers();
2711 parent::broadcastAnimation($animation, $targets);
2715 if($this->spawned && $targets === null){
2716 $targets = $this->getViewers();
2719 parent::broadcastSound($sound, $targets);
2725 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2726 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2732 if(parent::teleport($pos, $yaw, $pitch)){
2734 $this->removeCurrentWindow();
2737 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2738 $this->broadcastMovement(
true);
2740 $this->spawnToAll();
2742 $this->resetFallDistance();
2743 $this->nextChunkOrderRun = 0;
2744 if($this->spawnChunkLoadCount !== -1){
2745 $this->spawnChunkLoadCount = 0;
2747 $this->blockBreakHandler =
null;
2751 $this->resetLastMovements();
2759 protected function addDefaultWindows() : void{
2760 $this->cursorInventory = new SimpleInventory(1);
2761 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2763 $this->addPermanentWindows([
2764 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2765 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2766 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2767 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2768 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2772 public function getCursorInventory() : Inventory{
2773 return $this->cursorInventory;
2776 public function getCraftingGrid() : CraftingGrid{
2777 return $this->craftingGrid;
2785 return $this->creativeInventory;
2792 $this->creativeInventory = $inventory;
2793 if($this->spawned && $this->isConnected()){
2794 $this->getNetworkSession()->getInvManager()?->syncCreative();
2802 private function doCloseInventory() : void{
2803 $windowsToClear = [];
2804 $mainInventoryWindow =
null;
2805 foreach($this->permanentWindows as $window){
2806 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2807 $windowsToClear[] = $window;
2808 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2809 $mainInventoryWindow = $window;
2812 if($mainInventoryWindow ===
null){
2816 throw new AssumptionFailedError(
"This should never be null");
2819 if($this->currentWindow instanceof TemporaryInventoryWindow){
2820 $windowsToClear[] = $this->currentWindow;
2823 $builder =
new TransactionBuilder();
2824 foreach($windowsToClear as $window){
2825 $contents = $window->getInventory()->getContents();
2827 if(count($contents) > 0){
2828 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2829 foreach($drops as $drop){
2830 $builder->addAction(
new DropItemAction($drop));
2833 $builder->getActionBuilder($window)->clearAll();
2837 $actions = $builder->generateActions();
2838 if(count($actions) !== 0){
2839 $transaction =
new InventoryTransaction($this, $actions);
2841 $transaction->execute();
2842 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2843 }
catch(TransactionCancelledException){
2844 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2845 foreach($windowsToClear as $window){
2846 $window->getInventory()->clearAll();
2848 }
catch(TransactionValidationException $e){
2849 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2858 return $this->currentWindow;
2865 if($window === $this->currentWindow){
2868 if($window->getViewer() !== $this){
2869 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2873 if($ev->isCancelled()){
2877 $this->removeCurrentWindow();
2879 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2880 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2882 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2883 $inventoryManager->onCurrentWindowChange($window);
2885 $this->currentWindow = $window;
2889 public function removeCurrentWindow() : void{
2890 $this->doCloseInventory();
2891 if($this->currentWindow !==
null){
2892 $currentWindow = $this->currentWindow;
2893 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2894 $this->currentWindow->onClose();
2895 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2896 $inventoryManager->onCurrentWindowRemove();
2898 $this->currentWindow =
null;
2899 (
new InventoryCloseEvent($currentWindow, $this))->call();
2907 foreach($windows as $window){
2909 $this->permanentWindows[spl_object_id($window)] = $window;
2913 protected function removePermanentWindows() : void{
2914 foreach($this->permanentWindows as $window){
2917 $this->permanentWindows = [];
2925 return $this->permanentWindows;
2932 $block = $this->getWorld()->getBlock($position);
2934 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2935 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2937 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2941 use ChunkListenerNoOpTrait {
2942 onChunkChanged as
private;
2943 onChunkUnloaded as
private;
2947 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2948 if($status === UsedChunkStatus::SENT){
2949 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2950 $this->nextChunkOrderRun = 0;
2955 if($this->isUsingChunk($chunkX, $chunkZ)){
2956 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2957 $this->unloadChunk($chunkX, $chunkZ);