177 use PermissibleDelegateTrait;
179 private const MOVES_PER_TICK = 2;
180 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
183 private const MAX_CHAT_CHAR_LENGTH = 512;
189 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
190 private const MAX_REACH_DISTANCE_CREATIVE = 13;
191 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
192 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
194 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
196 public const TAG_FIRST_PLAYED =
"firstPlayed";
197 public const TAG_LAST_PLAYED =
"lastPlayed";
198 private const TAG_GAME_MODE =
"playerGameType";
199 private const TAG_SPAWN_WORLD =
"SpawnLevel";
200 private const TAG_SPAWN_X =
"SpawnX";
201 private const TAG_SPAWN_Y =
"SpawnY";
202 private const TAG_SPAWN_Z =
"SpawnZ";
203 private const TAG_DEATH_WORLD =
"DeathLevel";
204 private const TAG_DEATH_X =
"DeathPositionX";
205 private const TAG_DEATH_Y =
"DeathPositionY";
206 private const TAG_DEATH_Z =
"DeathPositionZ";
207 public const TAG_LEVEL =
"Level";
208 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
218 $lname = strtolower($name);
219 $len = strlen($name);
220 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
225 public bool $spawned =
false;
227 protected string $username;
228 protected string $displayName;
229 protected string $xuid =
"";
230 protected bool $authenticated;
233 protected ?InventoryWindow $currentWindow =
null;
235 protected array $permanentWindows = [];
236 protected Inventory $cursorInventory;
237 protected CraftingGrid $craftingGrid;
238 protected CreativeInventory $creativeInventory;
240 protected int $messageCounter = 2;
242 protected DateTimeImmutable $firstPlayed;
243 protected DateTimeImmutable $lastPlayed;
244 protected GameMode $gamemode;
250 protected array $usedChunks = [];
255 private array $activeChunkGenerationRequests = [];
260 protected array $loadQueue = [];
261 protected int $nextChunkOrderRun = 5;
264 private array $tickingChunks = [];
266 protected int $viewDistance = -1;
267 protected int $spawnThreshold;
268 protected int $spawnChunkLoadCount = 0;
269 protected int $chunksPerTick;
270 protected ChunkSelector $chunkSelector;
271 protected ChunkLoader $chunkLoader;
272 protected ChunkTicker $chunkTicker;
275 protected array $hiddenPlayers = [];
277 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
278 protected ?
float $lastMovementProcess =
null;
280 protected int $inAirTicks = 0;
282 protected float $stepHeight = 0.6;
284 protected ?Vector3 $sleeping =
null;
285 private ?
Position $spawnPosition =
null;
287 private bool $respawnLocked =
false;
289 private ?
Position $deathPosition =
null;
292 protected bool $autoJump =
true;
293 protected bool $allowFlight =
false;
294 protected bool $blockCollision =
true;
295 protected bool $flying =
false;
296 protected bool $sneakPressed =
false;
298 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
301 protected ?
int $lineHeight =
null;
304 protected string $locale =
"en_US";
306 protected int $startAction = -1;
312 protected array $usedItemsCooldown = [];
314 private int $lastEmoteTick = 0;
316 protected int $formIdCounter = 0;
318 protected array $forms = [];
320 protected \Logger $logger;
325 $username = TextFormat::clean($playerInfo->getUsername());
326 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
329 $this->networkSession = $session;
330 $this->playerInfo = $playerInfo;
331 $this->authenticated = $authenticated;
333 $this->username = $username;
334 $this->displayName = $this->username;
335 $this->locale = $this->playerInfo->getLocale();
337 $this->uuid = $this->playerInfo->getUuid();
338 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
340 $this->creativeInventory = CreativeInventory::getInstance();
342 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
343 if($this->
server->isOp($this->username)){
344 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
349 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
350 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
355 $world = $spawnLocation->
getWorld();
357 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
358 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
359 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
360 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
361 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
363 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
367 $this->setNameTag($this->username);
370 private function callDummyItemHeldEvent() : void{
371 $slot = $this->hotbar->getSelectedIndex();
380 protected function initEntity(
CompoundTag $nbt) : void{
381 parent::initEntity($nbt);
382 $this->addDefaultWindows();
384 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
385 function(Inventory $unused,
int $slot) :
void{
386 if($slot === $this->hotbar->getSelectedIndex()){
387 $this->setUsingItem(
false);
389 $this->callDummyItemHeldEvent();
393 $this->setUsingItem(
false);
394 $this->callDummyItemHeldEvent();
398 $now = (int) (microtime(
true) * 1000);
399 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
400 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
402 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
403 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
405 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
406 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
408 $this->internalSetGameMode($this->
server->getGamemode());
411 $this->keepMovement =
true;
413 $this->setNameTagVisible();
414 $this->setNameTagAlwaysVisible();
415 $this->setCanClimb();
417 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
418 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
420 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
421 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
425 public function getLeaveMessage() : Translatable|string{
427 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
433 public function isAuthenticated() : bool{
434 return $this->authenticated;
459 return parent::getUniqueId();
466 return $this->firstPlayed;
473 return $this->lastPlayed;
476 public function hasPlayedBefore() : bool{
477 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
490 if($this->allowFlight !== $value){
491 $this->allowFlight = $value;
492 $this->getNetworkSession()->syncAbilities($this);
503 return $this->allowFlight;
515 if($this->blockCollision !== $value){
516 $this->blockCollision = $value;
517 $this->getNetworkSession()->syncAbilities($this);
526 return $this->blockCollision;
529 public function setFlying(
bool $value) : void{
530 if($this->flying !== $value){
531 $this->flying = $value;
532 $this->resetFallDistance();
533 $this->getNetworkSession()->syncAbilities($this);
537 public function isFlying() : bool{
538 return $this->flying;
555 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
556 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
557 $this->getNetworkSession()->syncAbilities($this);
573 return $this->flightSpeedMultiplier;
576 public function setAutoJump(
bool $value) : void{
577 if($this->autoJump !== $value){
578 $this->autoJump = $value;
579 $this->getNetworkSession()->syncAdventureSettings();
583 public function hasAutoJump() : bool{
584 return $this->autoJump;
587 public function spawnTo(Player $player) : void{
588 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
589 parent::spawnTo($player);
593 public function getServer() : Server{
598 return $this->lineHeight ?? 7;
602 if($height !== null && $height < 1){
603 throw new \InvalidArgumentException(
"Line height must be at least 1");
605 $this->lineHeight = $height;
610 public function canSee(
Player $player) : bool{
611 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
614 public function hidePlayer(
Player $player) : void{
615 if($player === $this){
618 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
619 $player->despawnFrom($this);
622 public function showPlayer(Player $player) : void{
623 if($player === $this){
626 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
627 if($player->isOnline()){
628 $player->spawnTo($this);
632 public function canCollideWith(Entity $entity) : bool{
636 public function canBeCollidedWith() : bool{
637 return !$this->isSpectator() && parent::canBeCollidedWith();
640 public function resetFallDistance() : void{
641 parent::resetFallDistance();
642 $this->inAirTicks = 0;
645 public function getViewDistance() : int{
646 return $this->viewDistance;
649 public function setViewDistance(
int $distance) : void{
650 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
652 if($newViewDistance !== $this->viewDistance){
653 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
657 $this->viewDistance = $newViewDistance;
659 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
661 $this->nextChunkOrderRun = 0;
663 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
665 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
668 public function isOnline() : bool{
669 return $this->isConnected();
672 public function isConnected() : bool{
673 return $this->networkSession !== null && $this->networkSession->isConnected();
676 public function getNetworkSession() : NetworkSession{
677 if($this->networkSession === null){
678 throw new \LogicException(
"Player is not connected");
680 return $this->networkSession;
687 return $this->username;
694 return $this->displayName;
697 public function setDisplayName(
string $name) : void{
701 $this->displayName = $ev->getNewName();
712 return $this->locale;
715 public function getLanguage() :
Language{
716 return $this->
server->getLanguage();
723 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
727 if($ev->isCancelled()){
728 $this->sendSkin([$this]);
732 $this->setSkin($ev->getNewSkin());
733 $this->sendSkin($this->server->getOnlinePlayers());
742 public function sendSkin(?array $targets =
null) : void{
743 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
750 return $this->startAction > -1;
753 public function setUsingItem(
bool $value) : void{
754 $this->startAction = $value ? $this->
server->getTick() : -1;
755 $this->networkPropertiesDirty =
true;
763 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
770 $this->checkItemCooldowns();
771 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
778 $this->checkItemCooldowns();
779 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
786 $ticks = $ticks ?? $item->getCooldownTicks();
788 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
789 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
793 protected function checkItemCooldowns() : void{
794 $serverTick = $this->
server->getTick();
795 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
796 if($cooldownUntil <= $serverTick){
797 unset($this->usedItemsCooldown[$itemId]);
802 protected function setPosition(Vector3 $pos) : bool{
803 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
804 if(parent::setPosition($pos)){
805 $newWorld = $this->getWorld();
806 if($oldWorld !== $newWorld){
807 if($oldWorld !==
null){
808 foreach($this->usedChunks as $index => $status){
809 World::getXZ($index, $X, $Z);
810 $this->unloadChunk($X, $Z, $oldWorld);
814 $this->usedChunks = [];
815 $this->loadQueue = [];
816 $this->getNetworkSession()->onEnterWorld();
825 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
826 $world = $world ?? $this->getWorld();
827 $index = World::chunkHash($x, $z);
828 if(isset($this->usedChunks[$index])){
829 foreach($world->getChunkEntities($x, $z) as $entity){
830 if($entity !== $this){
831 $entity->despawnFrom($this);
834 $this->getNetworkSession()->stopUsingChunk($x, $z);
835 unset($this->usedChunks[$index]);
836 unset($this->activeChunkGenerationRequests[$index]);
838 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
839 $world->unregisterChunkListener($this, $x, $z);
840 unset($this->loadQueue[$index]);
841 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
842 unset($this->tickingChunks[$index]);
845 protected function spawnEntitiesOnAllChunks() : void{
846 foreach($this->usedChunks as $chunkHash => $status){
847 if($status === UsedChunkStatus::SENT){
848 World::getXZ($chunkHash, $chunkX, $chunkZ);
849 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
854 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
855 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
856 if($entity !== $this && !$entity->isFlaggedForDespawn()){
857 $entity->spawnTo($this);
867 if(!$this->isConnected()){
871 Timings::$playerChunkSend->startTiming();
874 $world = $this->getWorld();
876 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
877 foreach($this->loadQueue as $index => $distance){
878 if($count >= $limit){
884 World::getXZ($index, $X, $Z);
888 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
889 $this->activeChunkGenerationRequests[$index] =
true;
890 unset($this->loadQueue[$index]);
891 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
892 $world->registerChunkListener($this, $X, $Z);
893 if(isset($this->tickingChunks[$index])){
894 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
897 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
898 function() use ($X, $Z, $index, $world) :
void{
899 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
902 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
908 unset($this->activeChunkGenerationRequests[$index]);
909 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
911 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
912 $this->usedChunks[$index] = UsedChunkStatus::SENT;
913 if($this->spawnChunkLoadCount === -1){
914 $this->spawnEntitiesOnChunk($X, $Z);
915 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
916 $this->spawnChunkLoadCount = -1;
918 $this->spawnEntitiesOnAllChunks();
920 $this->getNetworkSession()->notifyTerrainReady();
922 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
925 static function() :
void{
931 Timings::$playerChunkSend->stopTiming();
934 private function recheckBroadcastPermissions() : void{
936 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
937 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
938 ] as $permission => $channel){
939 if($this->hasPermission($permission)){
940 $this->
server->subscribeToBroadcastChannel($channel, $this);
942 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
955 $this->spawned =
true;
956 $this->recheckBroadcastPermissions();
957 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
958 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
959 $this->recheckBroadcastPermissions();
963 $ev =
new PlayerJoinEvent($this,
964 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
967 if($ev->getJoinMessage() !==
""){
968 $this->server->broadcastMessage($ev->getJoinMessage());
971 $this->noDamageTicks = 60;
975 if($this->getHealth() <= 0){
976 $this->logger->debug(
"Quit while dead, forcing respawn");
977 $this->actuallyRespawn();
988 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
989 $world = $this->getWorld();
990 foreach($oldTickingChunks as $hash => $_){
991 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
993 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
994 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
997 foreach($newTickingChunks as $hash => $_){
998 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
1000 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1001 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1011 if(!$this->isConnected() || $this->viewDistance === -1){
1015 Timings::$playerChunkOrder->startTiming();
1018 $tickingChunks = [];
1019 $unloadChunks = $this->usedChunks;
1021 $world = $this->getWorld();
1022 $tickingChunkRadius = $world->getChunkTickRadius();
1024 foreach($this->chunkSelector->selectChunks(
1025 $this->server->getAllowedViewDistance($this->viewDistance),
1026 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1027 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1028 ) as $radius => $hash){
1029 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1030 $newOrder[$hash] =
true;
1032 if($radius < $tickingChunkRadius){
1033 $tickingChunks[$hash] =
true;
1035 unset($unloadChunks[$hash]);
1038 foreach($unloadChunks as $index => $status){
1039 World::getXZ($index, $X, $Z);
1040 $this->unloadChunk($X, $Z);
1043 $this->loadQueue = $newOrder;
1045 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1046 $this->tickingChunks = $tickingChunks;
1048 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1049 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1052 Timings::$playerChunkOrder->stopTiming();
1060 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1068 return $this->usedChunks;
1075 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1082 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1083 return $status === UsedChunkStatus::SENT;
1090 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1091 $this->nextChunkOrderRun = PHP_INT_MAX;
1092 $this->orderChunks();
1095 if(count($this->loadQueue) > 0){
1096 $this->requestChunks();
1100 public function getDeathPosition() : ?Position{
1101 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1102 $this->deathPosition =
null;
1104 return $this->deathPosition;
1112 if($pos instanceof
Position && $pos->world !==
null){
1113 $world = $pos->world;
1115 $world = $this->getWorld();
1117 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1119 $this->deathPosition =
null;
1121 $this->networkPropertiesDirty =
true;
1128 if($this->hasValidCustomSpawn()){
1129 return $this->spawnPosition;
1131 $world = $this->
server->getWorldManager()->getDefaultWorld();
1133 return $world->getSpawnLocation();
1137 public function hasValidCustomSpawn() : bool{
1138 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1150 $world = $this->getWorld();
1152 $world = $pos->getWorld();
1154 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1156 $this->spawnPosition =
null;
1158 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1161 public function isSleeping() : bool{
1162 return $this->sleeping !== null;
1165 public function sleepOn(Vector3 $pos) : bool{
1166 $pos = $pos->floor();
1167 $b = $this->getWorld()->getBlock($pos);
1169 $ev =
new PlayerBedEnterEvent($this, $b);
1171 if($ev->isCancelled()){
1175 if($b instanceof Bed){
1177 $this->getWorld()->setBlock($pos, $b);
1180 $this->sleeping = $pos;
1181 $this->networkPropertiesDirty =
true;
1183 $this->setSpawn($pos);
1185 $this->getWorld()->setSleepTicks(60);
1190 public function stopSleep() : void{
1191 if($this->sleeping instanceof Vector3){
1192 $b = $this->getWorld()->getBlock($this->sleeping);
1193 if($b instanceof Bed){
1194 $b->setOccupied(
false);
1195 $this->getWorld()->setBlock($this->sleeping, $b);
1197 (
new PlayerBedLeaveEvent($this, $b))->call();
1199 $this->sleeping =
null;
1200 $this->networkPropertiesDirty =
true;
1202 $this->getWorld()->setSleepTicks(0);
1204 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1208 public function getGamemode() : GameMode{
1209 return $this->gamemode;
1212 protected function internalSetGameMode(GameMode $gameMode) : void{
1213 $this->gamemode = $gameMode;
1215 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1216 $this->hungerManager->setEnabled($this->isSurvival());
1218 if($this->isSpectator()){
1219 $this->setFlying(
true);
1220 $this->setHasBlockCollision(
false);
1222 $this->onGround =
false;
1226 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1228 if($this->isSurvival()){
1229 $this->setFlying(
false);
1231 $this->setHasBlockCollision(
true);
1232 $this->setSilent(
false);
1233 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1241 if($this->gamemode === $gm){
1247 if($ev->isCancelled()){
1251 $this->internalSetGameMode($gm);
1253 if($this->isSpectator()){
1254 $this->despawnFromAll();
1256 $this->spawnToAll();
1259 $this->getNetworkSession()->syncGameMode($this->gamemode);
1270 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1280 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1290 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1293 public function isSpectator() : bool{
1294 return $this->gamemode === GameMode::SPECTATOR;
1297 public function setSneakPressed(
bool $sneakPressed) : void{
1298 $this->sneakPressed = $sneakPressed;
1306 return $this->sneakPressed;
1313 return $this->gamemode !== GameMode::CREATIVE;
1317 if($this->hasFiniteResources()){
1318 return parent::getDrops();
1325 if($this->hasFiniteResources()){
1326 return parent::getXpDropAmount();
1332 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1333 if(!$this->blockCollision){
1334 $this->onGround =
false;
1337 $bb =
new AxisAlignedBB(
1338 $this->boundingBox->minX,
1339 $this->location->y - 0.2,
1340 $this->boundingBox->minZ,
1341 $this->boundingBox->maxX,
1342 $this->location->y + 0.2,
1343 $this->boundingBox->maxZ
1348 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1350 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1358 protected function checkNearEntities() : void{
1359 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1360 $entity->scheduleUpdate();
1362 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1366 $entity->onCollideWithPlayer($this);
1370 public function getInAirTicks() : int{
1371 return $this->inAirTicks;
1383 Timings::$playerMove->startTiming();
1385 $this->actuallyHandleMovement($newPos);
1387 Timings::$playerMove->stopTiming();
1391 private function actuallyHandleMovement(Vector3 $newPos) : void{
1392 $this->moveRateLimit--;
1393 if($this->moveRateLimit < 0){
1397 $oldPos = $this->location;
1398 $distanceSquared = $newPos->distanceSquared($oldPos);
1402 if($distanceSquared > 225){
1414 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1415 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1417 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1419 $this->nextChunkOrderRun = 0;
1422 if(!$revert && $distanceSquared !== 0.0){
1423 $dx = $newPos->x - $oldPos->x;
1424 $dy = $newPos->y - $oldPos->y;
1425 $dz = $newPos->z - $oldPos->z;
1427 $this->move($dx, $dy, $dz);
1431 $this->revertMovement($oldPos);
1439 $now = microtime(true);
1440 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1441 $exceededRateLimit = $this->moveRateLimit < 0;
1442 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1443 $this->lastMovementProcess = $now;
1445 $from = clone $this->lastLocation;
1446 $to = clone $this->location;
1448 $delta = $to->distanceSquared($from);
1449 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1451 if($delta > 0.0001 || $deltaAngle > 1.0){
1452 if(PlayerMoveEvent::hasHandlers()){
1457 if($ev->isCancelled()){
1458 $this->revertMovement($from);
1462 if($to->distanceSquared($ev->getTo()) > 0.01){
1463 $this->teleport($ev->getTo());
1468 $this->lastLocation = $to;
1469 $this->broadcastMovement();
1471 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1472 if($horizontalDistanceTravelled > 0){
1474 if($this->isSprinting()){
1475 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1477 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1480 if($this->nextChunkOrderRun > 20){
1481 $this->nextChunkOrderRun = 20;
1486 if($exceededRateLimit){
1487 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1488 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1492 protected function revertMovement(Location $from) : void{
1493 $this->setPosition($from);
1494 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1497 protected function calculateFallDamage(
float $fallDistance) : float{
1498 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1506 public function setMotion(
Vector3 $motion) : bool{
1507 if(parent::setMotion($motion)){
1508 $this->broadcastMotion();
1509 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1516 protected function updateMovement(
bool $teleport =
false) : void{
1520 protected function tryChangeMovement() : void{
1524 public function onUpdate(int $currentTick) : bool{
1525 $tickDiff = $currentTick - $this->lastUpdate;
1531 $this->messageCounter = 2;
1533 $this->lastUpdate = $currentTick;
1535 if($this->justCreated){
1536 $this->onFirstUpdate($currentTick);
1539 if(!$this->isAlive() && $this->spawned){
1540 $this->onDeathUpdate($tickDiff);
1544 $this->timings->startTiming();
1547 Timings::$playerMove->startTiming();
1548 $this->processMostRecentMovements();
1549 $this->motion = Vector3::zero();
1550 if($this->onGround){
1551 $this->inAirTicks = 0;
1553 $this->inAirTicks += $tickDiff;
1555 Timings::$playerMove->stopTiming();
1557 Timings::$entityBaseTick->startTiming();
1558 $this->entityBaseTick($tickDiff);
1559 Timings::$entityBaseTick->stopTiming();
1561 if($this->isCreative() && $this->fireTicks > 1){
1562 $this->fireTicks = 1;
1565 if(!$this->isSpectator() && $this->isAlive()){
1566 Timings::$playerCheckNearEntities->startTiming();
1567 $this->checkNearEntities();
1568 Timings::$playerCheckNearEntities->stopTiming();
1571 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1572 $this->blockBreakHandler =
null;
1576 $this->timings->stopTiming();
1582 return $this->isCreative() || parent::canEat();
1586 return $this->isCreative() || parent::canBreathe();
1595 $eyePos = $this->getEyePos();
1596 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1600 $dV = $this->getDirectionVector();
1601 $eyeDot = $dV->dot($eyePos);
1602 $targetDot = $dV->dot($pos);
1603 return ($targetDot - $eyeDot) >= -$maxDiff;
1610 public function chat(
string $message) : bool{
1611 $this->removeCurrentWindow();
1613 if($this->messageCounter <= 0){
1619 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1620 if(strlen($message) > $maxTotalLength){
1624 $message = TextFormat::clean($message,
false);
1625 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1626 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1627 if(str_starts_with($messagePart,
'./')){
1628 $messagePart = substr($messagePart, 1);
1631 if(str_starts_with($messagePart,
"/")){
1632 Timings::$playerCommand->startTiming();
1633 $this->server->dispatchCommand($this, substr($messagePart, 1));
1634 Timings::$playerCommand->stopTiming();
1636 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1638 if(!$ev->isCancelled()){
1639 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1648 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1649 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1652 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1656 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1658 if($ev->isCancelled()){
1662 $this->hotbar->setSelectedIndex($hotbarSlot);
1663 $this->setUsingItem(
false);
1671 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1672 $heldItemChanged = false;
1674 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1677 $newReplica = clone $oldHeldItem;
1678 $newReplica->setCount($newHeldItem->getCount());
1679 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1680 $newDamage = $newHeldItem->getDamage();
1681 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1682 $newReplica->setDamage($newDamage);
1685 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1687 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1688 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1689 $this->broadcastSound(
new ItemBreakSound());
1691 $this->setMainHandItem($newHeldItem);
1692 $heldItemChanged =
true;
1696 if(!$heldItemChanged){
1697 $newHeldItem = $oldHeldItem;
1700 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1701 $this->setMainHandItem(array_shift($extraReturnedItems));
1703 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1705 $ev =
new PlayerDropItemEvent($this, $drop);
1706 if($this->isSpectator()){
1710 if(!$ev->isCancelled()){
1711 $this->dropItem($drop);
1722 $directionVector = $this->getDirectionVector();
1723 $item = $this->getMainHandItem();
1724 $oldItem = clone $item;
1727 if($this->hasItemCooldown($item) || $this->isSpectator()){
1733 if($ev->isCancelled()){
1737 $returnedItems = [];
1738 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1739 if($result === ItemUseResult::FAIL){
1743 $this->resetItemCooldown($oldItem);
1744 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1746 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1757 $slot = $this->getMainHandItem();
1759 $oldItem = clone $slot;
1762 if($this->hasItemCooldown($slot)){
1767 if($ev->isCancelled() || !$this->consumeObject($slot)){
1771 $this->setUsingItem(
false);
1772 $this->resetItemCooldown($oldItem);
1775 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1790 $item = $this->getMainHandItem();
1791 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1795 $oldItem = clone $item;
1797 $returnedItems = [];
1798 $result = $item->onReleaseUsing($this, $returnedItems);
1799 if($result === ItemUseResult::SUCCESS){
1800 $this->resetItemCooldown($oldItem);
1801 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1807 $this->setUsingItem(
false);
1811 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1812 $block = $this->getWorld()->getBlock($pos);
1813 if($block instanceof UnknownBlock){
1817 $item = $block->getPickedItem($addTileNBT);
1819 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1820 $existingSlot = $this->inventory->first($item);
1821 if($existingSlot === -1 && $this->hasFiniteResources()){
1826 if(!$ev->isCancelled()){
1827 $this->equipOrAddPickedItem($existingSlot, $item);
1833 public function pickEntity(
int $entityId) : bool{
1834 $entity = $this->getWorld()->getEntity($entityId);
1835 if($entity ===
null){
1839 $item = $entity->getPickedItem();
1844 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1845 $existingSlot = $this->inventory->first($item);
1846 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1851 if(!$ev->isCancelled()){
1852 $this->equipOrAddPickedItem($existingSlot, $item);
1858 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1859 if($existingSlot !== -1){
1860 if($existingSlot < $this->hotbar->getSize()){
1861 $this->hotbar->setSelectedIndex($existingSlot);
1863 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1866 $firstEmpty = $this->inventory->firstEmpty();
1867 if($firstEmpty === -1){
1868 $this->setMainHandItem($item);
1869 }elseif($firstEmpty < $this->hotbar->getSize()){
1870 $this->inventory->setItem($firstEmpty, $item);
1871 $this->hotbar->setSelectedIndex($firstEmpty);
1873 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1874 $this->setMainHandItem($item);
1885 if($pos->distanceSquared($this->location) > 10000){
1889 $target = $this->getWorld()->getBlock($pos);
1891 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1892 if($this->isSpectator()){
1896 if($ev->isCancelled()){
1899 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1900 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1904 $block = $target->getSide($face);
1905 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1906 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1907 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1911 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1912 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1918 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1919 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1920 $this->blockBreakHandler->setTargetedFace($face);
1924 public function stopBreakBlock(Vector3 $pos) : void{
1925 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1926 $this->blockBreakHandler =
null;
1936 $this->removeCurrentWindow();
1938 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1939 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1940 $this->stopBreakBlock($pos);
1941 $item = $this->getMainHandItem();
1942 $oldItem = clone $item;
1943 $returnedItems = [];
1944 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1945 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1946 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1950 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1962 $this->setUsingItem(false);
1964 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1965 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1966 $item = $this->getMainHandItem();
1967 $oldItem = clone $item;
1968 $returnedItems = [];
1969 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1970 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1974 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1987 if(!$entity->isAlive()){
1991 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1995 $heldItem = $this->getMainHandItem();
1996 $oldItem = clone $heldItem;
1998 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1999 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2000 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
2002 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
2006 $meleeEnchantmentDamage = 0;
2008 $meleeEnchantments = [];
2009 foreach($heldItem->getEnchantments() as $enchantment){
2010 $type = $enchantment->getType();
2011 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2012 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2013 $meleeEnchantments[] = $enchantment;
2016 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2018 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2019 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2022 $entity->attack($ev);
2023 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2025 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2026 if($ev->isCancelled()){
2027 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2030 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2032 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2033 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2035 if($ev->getModifier(EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS) > 0 && $entity instanceof Living){
2036 $entity->broadcastAnimation(
new MagicHitAnimation($entity));
2039 foreach($meleeEnchantments as $enchantment){
2040 $type = $enchantment->getType();
2041 assert($type instanceof MeleeWeaponEnchantment);
2042 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2045 if($this->isAlive()){
2048 $returnedItems = [];
2049 $heldItem->onAttackEntity($entity, $returnedItems);
2050 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2052 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2065 if(!$ev->isCancelled()){
2066 $this->broadcastSound(new EntityAttackNoDamageSound());
2067 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2077 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2078 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2084 $item = $this->getMainHandItem();
2085 $oldItem = clone $item;
2086 if(!$ev->isCancelled()){
2087 if($item->onInteractEntity($this, $entity, $clickPos)){
2088 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2089 if($item instanceof Durable && $item->isBroken()){
2090 $this->broadcastSound(new ItemBreakSound());
2092 $this->setMainHandItem($item);
2095 return $entity->
onInteract($this, $clickPos);
2100 public function toggleSprint(
bool $sprint) : bool{
2101 if($sprint === $this->sprinting){
2104 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2106 if($ev->isCancelled()){
2109 $this->setSprinting($sprint);
2113 public function toggleSneak(
bool $sneak,
bool $sneakPressed =
true) : bool{
2114 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2117 $this->setSneakPressed($sneakPressed);
2119 $ev =
new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2120 if($sneak === $this->sneaking){
2125 if($ev->isCancelled()){
2128 $this->setSneaking($sneak);
2132 public function toggleFlight(
bool $fly) : bool{
2133 if($fly === $this->flying){
2136 $ev =
new PlayerToggleFlightEvent($this, $fly);
2137 if(!$this->allowFlight){
2141 if($ev->isCancelled()){
2144 $this->setFlying($fly);
2148 public function toggleGlide(
bool $glide) : bool{
2149 if($glide === $this->gliding){
2152 $ev =
new PlayerToggleGlideEvent($this, $glide);
2154 if($ev->isCancelled()){
2157 $this->setGliding($glide);
2161 public function toggleSwim(
bool $swim) : bool{
2162 if($swim === $this->swimming){
2165 $ev =
new PlayerToggleSwimEvent($this, $swim);
2167 if($ev->isCancelled()){
2170 $this->setSwimming($swim);
2174 public function emote(
string $emoteId) : void{
2175 $currentTick = $this->
server->getTick();
2176 if($currentTick - $this->lastEmoteTick > 5){
2177 $this->lastEmoteTick = $currentTick;
2178 $event =
new PlayerEmoteEvent($this, $emoteId);
2180 if(!$event->isCancelled()){
2181 $emoteId = $event->getEmoteId();
2182 parent::emote($emoteId);
2192 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2202 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2203 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2204 if($subtitle !==
""){
2205 $this->sendSubTitle($subtitle);
2207 $this->getNetworkSession()->onTitle($title);
2214 $this->getNetworkSession()->onSubTitle($subtitle);
2221 $this->getNetworkSession()->onActionBar($message);
2228 $this->getNetworkSession()->onClearTitle();
2235 $this->getNetworkSession()->onResetTitleOptions();
2246 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2247 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2255 $this->getNetworkSession()->onChatMessage($message);
2258 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2259 $this->getNetworkSession()->onJukeboxPopup($message);
2268 $this->getNetworkSession()->onPopup($message);
2271 public function sendTip(
string $message) : void{
2272 $this->getNetworkSession()->onTip($message);
2279 $this->getNetworkSession()->onToastNotification($title, $body);
2288 $id = $this->formIdCounter++;
2289 if($this->getNetworkSession()->onFormSent($id, $form)){
2290 $this->forms[$id] = $form;
2294 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2295 if(!isset($this->forms[$formId])){
2296 $this->logger->debug(
"Got unexpected response for form $formId");
2301 $this->forms[$formId]->handleResponse($this, $responseData);
2302 }
catch(FormValidationException $e){
2303 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2304 $this->logger->logException($e);
2306 unset($this->forms[$formId]);
2316 $this->getNetworkSession()->onCloseAllForms();
2331 if(!$ev->isCancelled()){
2332 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2347 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2349 if(!$ev->isCancelled()){
2350 $reason = $ev->getDisconnectReason();
2352 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2354 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2355 if($disconnectScreenMessage ===
""){
2356 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2358 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2380 if(!$this->isConnected()){
2384 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2385 $this->onPostDisconnect($reason, $quitMessage);
2396 if($this->isConnected()){
2397 throw new \LogicException(
"Player is still connected");
2401 $this->server->unsubscribeFromAllBroadcastChannels($this);
2403 $this->removeCurrentWindow();
2405 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2407 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2408 $this->server->broadcastMessage($quitMessage);
2412 $this->spawned =
false;
2415 $this->blockBreakHandler =
null;
2416 $this->despawnFromAll();
2418 $this->
server->removeOnlinePlayer($this);
2420 foreach($this->
server->getOnlinePlayers() as $player){
2421 if(!$player->canSee($this)){
2422 $player->showPlayer($this);
2425 $this->hiddenPlayers = [];
2427 if($this->location->isValid()){
2428 foreach($this->usedChunks as $index => $status){
2429 World::getXZ($index, $chunkX, $chunkZ);
2430 $this->unloadChunk($chunkX, $chunkZ);
2433 if(count($this->usedChunks) !== 0){
2434 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2436 $this->loadQueue = [];
2438 $this->removeCurrentWindow();
2439 $this->removePermanentWindows();
2441 $this->perm->getPermissionRecalculationCallbacks()->clear();
2443 $this->flagForDespawn();
2447 $this->disconnect(
"Player destroyed");
2448 $this->cursorInventory->removeAllWindows();
2449 $this->craftingGrid->removeAllWindows();
2450 parent::onDispose();
2454 $this->networkSession = null;
2455 $this->spawnPosition =
null;
2456 $this->deathPosition =
null;
2457 $this->blockBreakHandler =
null;
2458 parent::destroyCycles();
2468 public function __destruct(){
2469 parent::__destruct();
2470 $this->logger->debug(
"Destroyed by garbage collector");
2478 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2482 $nbt = $this->saveNBT();
2484 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2486 if($this->location->isValid()){
2487 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2490 if($this->hasValidCustomSpawn()){
2491 $spawn = $this->getSpawn();
2492 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2493 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2494 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2495 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2498 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2499 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2500 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2501 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2502 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2505 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2506 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2507 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2516 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2522 $this->removeCurrentWindow();
2524 $this->setDeathPosition($this->getPosition());
2526 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2529 if(!$ev->getKeepInventory()){
2530 foreach($ev->getDrops() as $item){
2531 $this->getWorld()->dropItem($this->location, $item);
2534 $this->hotbar->setSelectedIndex(0);
2535 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2536 $clearInventory($this->inventory);
2537 $clearInventory($this->armorInventory);
2538 $clearInventory($this->offHandInventory);
2541 if(!$ev->getKeepXp()){
2542 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2543 $this->xpManager->setXpAndProgress(0, 0.0);
2546 if($ev->getDeathMessage() !==
""){
2547 $this->server->broadcastMessage($ev->getDeathMessage());
2550 $this->startDeathAnimation();
2552 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2556 parent::onDeathUpdate($tickDiff);
2560 public function respawn() : void{
2561 if($this->
server->isHardcore()){
2562 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2563 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2568 $this->actuallyRespawn();
2571 protected function actuallyRespawn() : void{
2572 if($this->respawnLocked){
2575 $this->respawnLocked =
true;
2577 $this->logger->debug(
"Waiting for safe respawn position to be located");
2578 $spawn = $this->getSpawn();
2579 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2580 function(Position $safeSpawn) :
void{
2581 if(!$this->isConnected()){
2584 $this->logger->debug(
"Respawn position located, completing respawn");
2585 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2586 $spawnPosition = $ev->getRespawnPosition();
2587 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2588 if($spawnBlock instanceof RespawnAnchor){
2589 if($spawnBlock->getCharges() > 0){
2590 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2591 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2593 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2594 if($defaultSpawn !==
null){
2595 $this->setSpawn($defaultSpawn);
2596 $ev->setRespawnPosition($defaultSpawn);
2597 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2603 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2604 $this->teleport($realSpawn);
2606 $this->setSprinting(
false);
2607 $this->setSneaking(
false);
2608 $this->setFlying(
false);
2610 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2611 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2612 $this->deadTicks = 0;
2613 $this->noDamageTicks = 60;
2615 $this->effectManager->clear();
2616 $this->setHealth($this->getMaxHealth());
2618 foreach($this->attributeMap->getAll() as $attr){
2619 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2622 $attr->resetToDefault();
2625 $this->spawnToAll();
2626 $this->scheduleUpdate();
2628 $this->getNetworkSession()->onServerRespawn();
2629 $this->respawnLocked =
false;
2632 if($this->isConnected()){
2633 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2640 parent::applyPostDamageEffects($source);
2642 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2646 if(!$this->isAlive()){
2650 if($this->isCreative()
2651 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2654 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2658 parent::attack($source);
2661 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2662 parent::syncNetworkData($properties);
2664 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2665 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2667 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2668 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2670 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2671 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2673 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2674 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2676 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2677 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2678 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2682 public function sendData(?array $targets, ?array $data =
null) : void{
2683 if($targets === null){
2684 $targets = $this->getViewers();
2687 parent::sendData($targets, $data);
2691 if($this->spawned && $targets === null){
2692 $targets = $this->getViewers();
2695 parent::broadcastAnimation($animation, $targets);
2699 if($this->spawned && $targets === null){
2700 $targets = $this->getViewers();
2703 parent::broadcastSound($sound, $targets);
2709 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2710 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2716 if(parent::teleport($pos, $yaw, $pitch)){
2718 $this->removeCurrentWindow();
2721 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2722 $this->broadcastMovement(
true);
2724 $this->spawnToAll();
2726 $this->resetFallDistance();
2727 $this->nextChunkOrderRun = 0;
2728 if($this->spawnChunkLoadCount !== -1){
2729 $this->spawnChunkLoadCount = 0;
2731 $this->blockBreakHandler =
null;
2735 $this->resetLastMovements();
2743 protected function addDefaultWindows() : void{
2744 $this->cursorInventory = new SimpleInventory(1);
2745 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2747 $this->addPermanentWindows([
2748 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2749 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2750 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2751 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2752 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2756 public function getCursorInventory() : Inventory{
2757 return $this->cursorInventory;
2760 public function getCraftingGrid() : CraftingGrid{
2761 return $this->craftingGrid;
2769 return $this->creativeInventory;
2776 $this->creativeInventory = $inventory;
2777 if($this->spawned && $this->isConnected()){
2778 $this->getNetworkSession()->getInvManager()?->syncCreative();
2786 private function doCloseInventory() : void{
2787 $windowsToClear = [];
2788 $mainInventoryWindow =
null;
2789 foreach($this->permanentWindows as $window){
2790 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2791 $windowsToClear[] = $window;
2792 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2793 $mainInventoryWindow = $window;
2796 if($mainInventoryWindow ===
null){
2800 throw new AssumptionFailedError(
"This should never be null");
2803 if($this->currentWindow instanceof TemporaryInventoryWindow){
2804 $windowsToClear[] = $this->currentWindow;
2807 $builder =
new TransactionBuilder();
2808 foreach($windowsToClear as $window){
2809 $contents = $window->getInventory()->getContents();
2811 if(count($contents) > 0){
2812 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2813 foreach($drops as $drop){
2814 $builder->addAction(
new DropItemAction($drop));
2817 $builder->getActionBuilder($window)->clearAll();
2821 $actions = $builder->generateActions();
2822 if(count($actions) !== 0){
2823 $transaction =
new InventoryTransaction($this, $actions);
2825 $transaction->execute();
2826 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2827 }
catch(TransactionCancelledException){
2828 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2829 foreach($windowsToClear as $window){
2830 $window->getInventory()->clearAll();
2832 }
catch(TransactionValidationException $e){
2833 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2842 return $this->currentWindow;
2849 if($window === $this->currentWindow){
2852 if($window->getViewer() !== $this){
2853 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2857 if($ev->isCancelled()){
2861 $this->removeCurrentWindow();
2863 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2864 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2866 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2867 $inventoryManager->onCurrentWindowChange($window);
2869 $this->currentWindow = $window;
2873 public function removeCurrentWindow() : void{
2874 $this->doCloseInventory();
2875 if($this->currentWindow !==
null){
2876 $currentWindow = $this->currentWindow;
2877 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2878 $this->currentWindow->onClose();
2879 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2880 $inventoryManager->onCurrentWindowRemove();
2882 $this->currentWindow =
null;
2883 (
new InventoryCloseEvent($currentWindow, $this))->call();
2891 foreach($windows as $window){
2893 $this->permanentWindows[spl_object_id($window)] = $window;
2897 protected function removePermanentWindows() : void{
2898 foreach($this->permanentWindows as $window){
2901 $this->permanentWindows = [];
2909 return $this->permanentWindows;
2916 $block = $this->getWorld()->getBlock($position);
2918 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2919 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2921 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2925 use ChunkListenerNoOpTrait {
2926 onChunkChanged as
private;
2927 onChunkUnloaded as
private;
2931 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2932 if($status === UsedChunkStatus::SENT){
2933 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2934 $this->nextChunkOrderRun = 0;
2939 if($this->isUsingChunk($chunkX, $chunkZ)){
2940 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2941 $this->unloadChunk($chunkX, $chunkZ);