171 use PermissibleDelegateTrait;
173 private const MOVES_PER_TICK = 2;
174 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
177 private const MAX_CHAT_CHAR_LENGTH = 512;
183 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
184 private const MAX_REACH_DISTANCE_CREATIVE = 13;
185 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
186 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
188 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
190 public const TAG_FIRST_PLAYED =
"firstPlayed";
191 public const TAG_LAST_PLAYED =
"lastPlayed";
192 private const TAG_GAME_MODE =
"playerGameType";
193 private const TAG_SPAWN_WORLD =
"SpawnLevel";
194 private const TAG_SPAWN_X =
"SpawnX";
195 private const TAG_SPAWN_Y =
"SpawnY";
196 private const TAG_SPAWN_Z =
"SpawnZ";
197 private const TAG_DEATH_WORLD =
"DeathLevel";
198 private const TAG_DEATH_X =
"DeathPositionX";
199 private const TAG_DEATH_Y =
"DeathPositionY";
200 private const TAG_DEATH_Z =
"DeathPositionZ";
201 public const TAG_LEVEL =
"Level";
202 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
212 $lname = strtolower($name);
213 $len = strlen($name);
214 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
219 public bool $spawned =
false;
221 protected string $username;
222 protected string $displayName;
223 protected string $xuid =
"";
224 protected bool $authenticated;
227 protected ?Inventory $currentWindow =
null;
229 protected array $permanentWindows = [];
230 protected PlayerCursorInventory $cursorInventory;
231 protected PlayerCraftingInventory $craftingGrid;
232 protected CreativeInventory $creativeInventory;
234 protected int $messageCounter = 2;
236 protected DateTimeImmutable $firstPlayed;
237 protected DateTimeImmutable $lastPlayed;
238 protected GameMode $gamemode;
244 protected array $usedChunks = [];
249 private array $activeChunkGenerationRequests = [];
254 protected array $loadQueue = [];
255 protected int $nextChunkOrderRun = 5;
258 private array $tickingChunks = [];
260 protected int $viewDistance = -1;
261 protected int $spawnThreshold;
262 protected int $spawnChunkLoadCount = 0;
263 protected int $chunksPerTick;
264 protected ChunkSelector $chunkSelector;
265 protected ChunkLoader $chunkLoader;
266 protected ChunkTicker $chunkTicker;
269 protected array $hiddenPlayers = [];
271 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
272 protected ?
float $lastMovementProcess =
null;
274 protected int $inAirTicks = 0;
276 protected float $stepHeight = 0.6;
278 protected ?Vector3 $sleeping =
null;
279 private ?
Position $spawnPosition =
null;
281 private bool $respawnLocked =
false;
283 private ?
Position $deathPosition =
null;
286 protected bool $autoJump =
true;
287 protected bool $allowFlight =
false;
288 protected bool $blockCollision =
true;
289 protected bool $flying =
false;
291 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
294 protected ?
int $lineHeight =
null;
295 protected string $locale =
"en_US";
297 protected int $startAction = -1;
303 protected array $usedItemsCooldown = [];
305 private int $lastEmoteTick = 0;
307 protected int $formIdCounter = 0;
309 protected array $forms = [];
311 protected \Logger $logger;
316 $username = TextFormat::clean($playerInfo->getUsername());
317 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
320 $this->networkSession = $session;
321 $this->playerInfo = $playerInfo;
322 $this->authenticated = $authenticated;
324 $this->username = $username;
325 $this->displayName = $this->username;
326 $this->locale = $this->playerInfo->getLocale();
328 $this->uuid = $this->playerInfo->getUuid();
329 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
331 $this->creativeInventory = CreativeInventory::getInstance();
333 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
334 if($this->
server->isOp($this->username)){
335 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
338 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
339 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
342 $this->chunkLoader =
new class implements
ChunkLoader{};
344 $world = $spawnLocation->
getWorld();
346 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
347 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
348 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
349 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
350 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
352 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
356 $this->setNameTag($this->username);
359 private function callDummyItemHeldEvent() : void{
360 $slot = $this->inventory->getHeldItemIndex();
369 protected function initEntity(
CompoundTag $nbt) : void{
370 parent::initEntity($nbt);
371 $this->addDefaultWindows();
373 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
374 function(Inventory $unused,
int $slot) :
void{
375 if($slot === $this->inventory->getHeldItemIndex()){
376 $this->setUsingItem(
false);
378 $this->callDummyItemHeldEvent();
382 $this->setUsingItem(
false);
383 $this->callDummyItemHeldEvent();
387 $now = (int) (microtime(
true) * 1000);
388 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
389 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
391 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
392 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
394 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
395 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
397 $this->internalSetGameMode($this->
server->getGamemode());
400 $this->keepMovement =
true;
402 $this->setNameTagVisible();
403 $this->setNameTagAlwaysVisible();
404 $this->setCanClimb();
406 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
407 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
409 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
410 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
414 public function getLeaveMessage() : Translatable|string{
416 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
422 public function isAuthenticated() : bool{
423 return $this->authenticated;
448 return parent::getUniqueId();
455 return $this->firstPlayed;
462 return $this->lastPlayed;
465 public function hasPlayedBefore() : bool{
466 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
479 if($this->allowFlight !== $value){
480 $this->allowFlight = $value;
481 $this->getNetworkSession()->syncAbilities($this);
492 return $this->allowFlight;
504 if($this->blockCollision !== $value){
505 $this->blockCollision = $value;
506 $this->getNetworkSession()->syncAbilities($this);
515 return $this->blockCollision;
518 public function setFlying(
bool $value) : void{
519 if($this->flying !== $value){
520 $this->flying = $value;
521 $this->resetFallDistance();
522 $this->getNetworkSession()->syncAbilities($this);
526 public function isFlying() : bool{
527 return $this->flying;
544 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
545 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
546 $this->getNetworkSession()->syncAbilities($this);
562 return $this->flightSpeedMultiplier;
565 public function setAutoJump(
bool $value) : void{
566 if($this->autoJump !== $value){
567 $this->autoJump = $value;
568 $this->getNetworkSession()->syncAdventureSettings();
572 public function hasAutoJump() : bool{
573 return $this->autoJump;
576 public function spawnTo(Player $player) : void{
577 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
578 parent::spawnTo($player);
582 public function getServer() : Server{
587 return $this->lineHeight ?? 7;
591 if($height !== null && $height < 1){
592 throw new \InvalidArgumentException(
"Line height must be at least 1");
594 $this->lineHeight = $height;
597 public function canSee(
Player $player) : bool{
598 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
601 public function hidePlayer(Player $player) : void{
602 if($player === $this){
605 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
606 $player->despawnFrom($this);
609 public function showPlayer(Player $player) : void{
610 if($player === $this){
613 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
614 if($player->isOnline()){
615 $player->spawnTo($this);
619 public function canCollideWith(Entity $entity) : bool{
623 public function canBeCollidedWith() : bool{
624 return !$this->isSpectator() && parent::canBeCollidedWith();
627 public function resetFallDistance() : void{
628 parent::resetFallDistance();
629 $this->inAirTicks = 0;
632 public function getViewDistance() : int{
633 return $this->viewDistance;
636 public function setViewDistance(
int $distance) : void{
637 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
639 if($newViewDistance !== $this->viewDistance){
640 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
644 $this->viewDistance = $newViewDistance;
646 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
648 $this->nextChunkOrderRun = 0;
650 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
652 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
655 public function isOnline() : bool{
656 return $this->isConnected();
659 public function isConnected() : bool{
660 return $this->networkSession !== null && $this->networkSession->isConnected();
663 public function getNetworkSession() : NetworkSession{
664 if($this->networkSession === null){
665 throw new \LogicException(
"Player is not connected");
667 return $this->networkSession;
674 return $this->username;
681 return $this->displayName;
684 public function setDisplayName(
string $name) : void{
688 $this->displayName = $ev->getNewName();
699 return $this->locale;
702 public function getLanguage() :
Language{
703 return $this->
server->getLanguage();
710 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
714 if($ev->isCancelled()){
715 $this->sendSkin([$this]);
719 $this->setSkin($ev->getNewSkin());
720 $this->sendSkin($this->server->getOnlinePlayers());
729 public function sendSkin(?array $targets =
null) : void{
730 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
737 return $this->startAction > -1;
740 public function setUsingItem(
bool $value) : void{
741 $this->startAction = $value ? $this->
server->getTick() : -1;
742 $this->networkPropertiesDirty =
true;
750 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
757 $this->checkItemCooldowns();
758 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
765 $this->checkItemCooldowns();
766 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
773 $ticks = $ticks ?? $item->getCooldownTicks();
775 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
776 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
780 protected function checkItemCooldowns() : void{
781 $serverTick = $this->
server->getTick();
782 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
783 if($cooldownUntil <= $serverTick){
784 unset($this->usedItemsCooldown[$itemId]);
789 protected function setPosition(Vector3 $pos) : bool{
790 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
791 if(parent::setPosition($pos)){
792 $newWorld = $this->getWorld();
793 if($oldWorld !== $newWorld){
794 if($oldWorld !==
null){
795 foreach($this->usedChunks as $index => $status){
796 World::getXZ($index, $X, $Z);
797 $this->unloadChunk($X, $Z, $oldWorld);
801 $this->usedChunks = [];
802 $this->loadQueue = [];
803 $this->getNetworkSession()->onEnterWorld();
812 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
813 $world = $world ?? $this->getWorld();
814 $index = World::chunkHash($x, $z);
815 if(isset($this->usedChunks[$index])){
816 foreach($world->getChunkEntities($x, $z) as $entity){
817 if($entity !== $this){
818 $entity->despawnFrom($this);
821 $this->getNetworkSession()->stopUsingChunk($x, $z);
822 unset($this->usedChunks[$index]);
823 unset($this->activeChunkGenerationRequests[$index]);
825 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
826 $world->unregisterChunkListener($this, $x, $z);
827 unset($this->loadQueue[$index]);
828 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
829 unset($this->tickingChunks[$index]);
832 protected function spawnEntitiesOnAllChunks() : void{
833 foreach($this->usedChunks as $chunkHash => $status){
834 if($status === UsedChunkStatus::SENT){
835 World::getXZ($chunkHash, $chunkX, $chunkZ);
836 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
841 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
842 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
843 if($entity !== $this && !$entity->isFlaggedForDespawn()){
844 $entity->spawnTo($this);
854 if(!$this->isConnected()){
858 Timings::$playerChunkSend->startTiming();
861 $world = $this->getWorld();
863 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
864 foreach($this->loadQueue as $index => $distance){
865 if($count >= $limit){
871 World::getXZ($index, $X, $Z);
875 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
876 $this->activeChunkGenerationRequests[$index] =
true;
877 unset($this->loadQueue[$index]);
878 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
879 $world->registerChunkListener($this, $X, $Z);
880 if(isset($this->tickingChunks[$index])){
881 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
884 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
885 function() use ($X, $Z, $index, $world) :
void{
886 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
889 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
895 unset($this->activeChunkGenerationRequests[$index]);
896 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
898 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
899 $this->usedChunks[$index] = UsedChunkStatus::SENT;
900 if($this->spawnChunkLoadCount === -1){
901 $this->spawnEntitiesOnChunk($X, $Z);
902 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
903 $this->spawnChunkLoadCount = -1;
905 $this->spawnEntitiesOnAllChunks();
907 $this->getNetworkSession()->notifyTerrainReady();
909 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
912 static function() :
void{
918 Timings::$playerChunkSend->stopTiming();
921 private function recheckBroadcastPermissions() : void{
923 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
924 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
925 ] as $permission => $channel){
926 if($this->hasPermission($permission)){
927 $this->
server->subscribeToBroadcastChannel($channel, $this);
929 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
942 $this->spawned =
true;
943 $this->recheckBroadcastPermissions();
944 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
945 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
946 $this->recheckBroadcastPermissions();
950 $ev =
new PlayerJoinEvent($this,
951 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
954 if($ev->getJoinMessage() !==
""){
955 $this->server->broadcastMessage($ev->getJoinMessage());
958 $this->noDamageTicks = 60;
962 if($this->getHealth() <= 0){
963 $this->logger->debug(
"Quit while dead, forcing respawn");
964 $this->actuallyRespawn();
975 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
976 $world = $this->getWorld();
977 foreach($oldTickingChunks as $hash => $_){
978 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
980 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
981 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
984 foreach($newTickingChunks as $hash => $_){
985 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
987 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
988 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
998 if(!$this->isConnected() || $this->viewDistance === -1){
1002 Timings::$playerChunkOrder->startTiming();
1005 $tickingChunks = [];
1006 $unloadChunks = $this->usedChunks;
1008 $world = $this->getWorld();
1009 $tickingChunkRadius = $world->getChunkTickRadius();
1011 foreach($this->chunkSelector->selectChunks(
1012 $this->server->getAllowedViewDistance($this->viewDistance),
1013 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1014 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1015 ) as $radius => $hash){
1016 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1017 $newOrder[$hash] =
true;
1019 if($radius < $tickingChunkRadius){
1020 $tickingChunks[$hash] =
true;
1022 unset($unloadChunks[$hash]);
1025 foreach($unloadChunks as $index => $status){
1026 World::getXZ($index, $X, $Z);
1027 $this->unloadChunk($X, $Z);
1030 $this->loadQueue = $newOrder;
1032 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1033 $this->tickingChunks = $tickingChunks;
1035 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1036 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1039 Timings::$playerChunkOrder->stopTiming();
1047 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1055 return $this->usedChunks;
1062 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1069 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1070 return $status === UsedChunkStatus::SENT;
1077 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1078 $this->nextChunkOrderRun = PHP_INT_MAX;
1079 $this->orderChunks();
1082 if(count($this->loadQueue) > 0){
1083 $this->requestChunks();
1087 public function getDeathPosition() : ?Position{
1088 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1089 $this->deathPosition =
null;
1091 return $this->deathPosition;
1099 if($pos instanceof
Position && $pos->world !==
null){
1100 $world = $pos->world;
1102 $world = $this->getWorld();
1104 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1106 $this->deathPosition =
null;
1108 $this->networkPropertiesDirty =
true;
1115 if($this->hasValidCustomSpawn()){
1116 return $this->spawnPosition;
1118 $world = $this->
server->getWorldManager()->getDefaultWorld();
1120 return $world->getSpawnLocation();
1124 public function hasValidCustomSpawn() : bool{
1125 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1137 $world = $this->getWorld();
1139 $world = $pos->getWorld();
1141 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1143 $this->spawnPosition =
null;
1145 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1148 public function isSleeping() : bool{
1149 return $this->sleeping !== null;
1152 public function sleepOn(Vector3 $pos) : bool{
1153 $pos = $pos->floor();
1154 $b = $this->getWorld()->getBlock($pos);
1156 $ev =
new PlayerBedEnterEvent($this, $b);
1158 if($ev->isCancelled()){
1162 if($b instanceof Bed){
1164 $this->getWorld()->setBlock($pos, $b);
1167 $this->sleeping = $pos;
1168 $this->networkPropertiesDirty =
true;
1170 $this->setSpawn($pos);
1172 $this->getWorld()->setSleepTicks(60);
1177 public function stopSleep() : void{
1178 if($this->sleeping instanceof Vector3){
1179 $b = $this->getWorld()->getBlock($this->sleeping);
1180 if($b instanceof Bed){
1181 $b->setOccupied(
false);
1182 $this->getWorld()->setBlock($this->sleeping, $b);
1184 (
new PlayerBedLeaveEvent($this, $b))->call();
1186 $this->sleeping =
null;
1187 $this->networkPropertiesDirty =
true;
1189 $this->getWorld()->setSleepTicks(0);
1191 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1195 public function getGamemode() : GameMode{
1196 return $this->gamemode;
1199 protected function internalSetGameMode(GameMode $gameMode) : void{
1200 $this->gamemode = $gameMode;
1202 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1203 $this->hungerManager->setEnabled($this->isSurvival());
1205 if($this->isSpectator()){
1206 $this->setFlying(
true);
1207 $this->setHasBlockCollision(
false);
1209 $this->onGround =
false;
1213 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1215 if($this->isSurvival()){
1216 $this->setFlying(
false);
1218 $this->setHasBlockCollision(
true);
1219 $this->setSilent(
false);
1220 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1228 if($this->gamemode === $gm){
1234 if($ev->isCancelled()){
1238 $this->internalSetGameMode($gm);
1240 if($this->isSpectator()){
1241 $this->despawnFromAll();
1243 $this->spawnToAll();
1246 $this->getNetworkSession()->syncGameMode($this->gamemode);
1257 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1267 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1277 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1280 public function isSpectator() : bool{
1281 return $this->gamemode === GameMode::SPECTATOR;
1288 return $this->gamemode !== GameMode::CREATIVE;
1292 if($this->hasFiniteResources()){
1293 return parent::getDrops();
1300 if($this->hasFiniteResources()){
1301 return parent::getXpDropAmount();
1307 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1308 if($this->gamemode === GameMode::SPECTATOR){
1309 $this->onGround =
false;
1311 $bb = clone $this->boundingBox;
1312 $bb->minY = $this->location->y - 0.2;
1313 $bb->maxY = $this->location->y + 0.2;
1317 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1319 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1327 protected function checkNearEntities() : void{
1328 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1329 $entity->scheduleUpdate();
1331 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1335 $entity->onCollideWithPlayer($this);
1339 public function getInAirTicks() : int{
1340 return $this->inAirTicks;
1352 Timings::$playerMove->startTiming();
1354 $this->actuallyHandleMovement($newPos);
1356 Timings::$playerMove->stopTiming();
1360 private function actuallyHandleMovement(Vector3 $newPos) : void{
1361 $this->moveRateLimit--;
1362 if($this->moveRateLimit < 0){
1366 $oldPos = $this->location;
1367 $distanceSquared = $newPos->distanceSquared($oldPos);
1371 if($distanceSquared > 225){
1383 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1384 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1386 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1388 $this->nextChunkOrderRun = 0;
1391 if(!$revert && $distanceSquared !== 0.0){
1392 $dx = $newPos->x - $oldPos->x;
1393 $dy = $newPos->y - $oldPos->y;
1394 $dz = $newPos->z - $oldPos->z;
1396 $this->move($dx, $dy, $dz);
1400 $this->revertMovement($oldPos);
1408 $now = microtime(true);
1409 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1410 $exceededRateLimit = $this->moveRateLimit < 0;
1411 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1412 $this->lastMovementProcess = $now;
1414 $from = clone $this->lastLocation;
1415 $to = clone $this->location;
1417 $delta = $to->distanceSquared($from);
1418 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1420 if($delta > 0.0001 || $deltaAngle > 1.0){
1421 if(PlayerMoveEvent::hasHandlers()){
1426 if($ev->isCancelled()){
1427 $this->revertMovement($from);
1431 if($to->distanceSquared($ev->getTo()) > 0.01){
1432 $this->teleport($ev->getTo());
1437 $this->lastLocation = $to;
1438 $this->broadcastMovement();
1440 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1441 if($horizontalDistanceTravelled > 0){
1443 if($this->isSprinting()){
1444 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1446 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1449 if($this->nextChunkOrderRun > 20){
1450 $this->nextChunkOrderRun = 20;
1455 if($exceededRateLimit){
1456 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1457 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1461 protected function revertMovement(Location $from) : void{
1462 $this->setPosition($from);
1463 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1466 protected function calculateFallDamage(
float $fallDistance) : float{
1467 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1475 public function setMotion(
Vector3 $motion) : bool{
1476 if(parent::setMotion($motion)){
1477 $this->broadcastMotion();
1478 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1485 protected function updateMovement(
bool $teleport =
false) : void{
1489 protected function tryChangeMovement() : void{
1493 public function onUpdate(int $currentTick) : bool{
1494 $tickDiff = $currentTick - $this->lastUpdate;
1500 $this->messageCounter = 2;
1502 $this->lastUpdate = $currentTick;
1504 if($this->justCreated){
1505 $this->onFirstUpdate($currentTick);
1508 if(!$this->isAlive() && $this->spawned){
1509 $this->onDeathUpdate($tickDiff);
1513 $this->timings->startTiming();
1516 Timings::$playerMove->startTiming();
1517 $this->processMostRecentMovements();
1518 $this->motion = Vector3::zero();
1519 if($this->onGround){
1520 $this->inAirTicks = 0;
1522 $this->inAirTicks += $tickDiff;
1524 Timings::$playerMove->stopTiming();
1526 Timings::$entityBaseTick->startTiming();
1527 $this->entityBaseTick($tickDiff);
1528 Timings::$entityBaseTick->stopTiming();
1530 if($this->isCreative() && $this->fireTicks > 1){
1531 $this->fireTicks = 1;
1534 if(!$this->isSpectator() && $this->isAlive()){
1535 Timings::$playerCheckNearEntities->startTiming();
1536 $this->checkNearEntities();
1537 Timings::$playerCheckNearEntities->stopTiming();
1540 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1541 $this->blockBreakHandler =
null;
1545 $this->timings->stopTiming();
1551 return $this->isCreative() || parent::canEat();
1555 return $this->isCreative() || parent::canBreathe();
1564 $eyePos = $this->getEyePos();
1565 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1569 $dV = $this->getDirectionVector();
1570 $eyeDot = $dV->dot($eyePos);
1571 $targetDot = $dV->dot($pos);
1572 return ($targetDot - $eyeDot) >= -$maxDiff;
1579 public function chat(
string $message) : bool{
1580 $this->removeCurrentWindow();
1582 if($this->messageCounter <= 0){
1588 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1589 if(strlen($message) > $maxTotalLength){
1593 $message = TextFormat::clean($message,
false);
1594 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1595 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1596 if(str_starts_with($messagePart,
'./')){
1597 $messagePart = substr($messagePart, 1);
1600 if(str_starts_with($messagePart,
"/")){
1601 Timings::$playerCommand->startTiming();
1602 $this->server->dispatchCommand($this, substr($messagePart, 1));
1603 Timings::$playerCommand->stopTiming();
1605 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1607 if(!$ev->isCancelled()){
1608 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1617 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1618 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1621 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1625 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1627 if($ev->isCancelled()){
1631 $this->inventory->setHeldItemIndex($hotbarSlot);
1632 $this->setUsingItem(
false);
1640 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1641 $heldItemChanged = false;
1643 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1646 $newReplica = clone $oldHeldItem;
1647 $newReplica->setCount($newHeldItem->getCount());
1648 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1649 $newReplica->setDamage($newHeldItem->getDamage());
1651 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1653 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1654 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1655 $this->broadcastSound(
new ItemBreakSound());
1657 $this->inventory->setItemInHand($newHeldItem);
1658 $heldItemChanged =
true;
1662 if(!$heldItemChanged){
1663 $newHeldItem = $oldHeldItem;
1666 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1667 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1669 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1671 $ev =
new PlayerDropItemEvent($this, $drop);
1672 if($this->isSpectator()){
1676 if(!$ev->isCancelled()){
1677 $this->dropItem($drop);
1688 $directionVector = $this->getDirectionVector();
1689 $item = $this->inventory->getItemInHand();
1690 $oldItem = clone $item;
1693 if($this->hasItemCooldown($item) || $this->isSpectator()){
1699 if($ev->isCancelled()){
1703 $returnedItems = [];
1704 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1705 if($result === ItemUseResult::FAIL){
1709 $this->resetItemCooldown($oldItem);
1710 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1712 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1723 $slot = $this->inventory->getItemInHand();
1725 $oldItem = clone $slot;
1728 if($this->hasItemCooldown($slot)){
1733 if($ev->isCancelled() || !$this->consumeObject($slot)){
1737 $this->setUsingItem(
false);
1738 $this->resetItemCooldown($oldItem);
1741 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1756 $item = $this->inventory->getItemInHand();
1757 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1761 $oldItem = clone $item;
1763 $returnedItems = [];
1764 $result = $item->onReleaseUsing($this, $returnedItems);
1765 if($result === ItemUseResult::SUCCESS){
1766 $this->resetItemCooldown($oldItem);
1767 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1773 $this->setUsingItem(
false);
1777 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1778 $block = $this->getWorld()->getBlock($pos);
1779 if($block instanceof UnknownBlock){
1783 $item = $block->getPickedItem($addTileNBT);
1785 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1786 $existingSlot = $this->inventory->first($item);
1787 if($existingSlot === -1 && $this->hasFiniteResources()){
1792 if(!$ev->isCancelled()){
1793 $this->equipOrAddPickedItem($existingSlot, $item);
1799 public function pickEntity(
int $entityId) : bool{
1800 $entity = $this->getWorld()->getEntity($entityId);
1801 if($entity ===
null){
1805 $item = $entity->getPickedItem();
1810 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1811 $existingSlot = $this->inventory->first($item);
1812 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1817 if(!$ev->isCancelled()){
1818 $this->equipOrAddPickedItem($existingSlot, $item);
1824 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1825 if($existingSlot !== -1){
1826 if($existingSlot < $this->inventory->getHotbarSize()){
1827 $this->inventory->setHeldItemIndex($existingSlot);
1829 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1832 $firstEmpty = $this->inventory->firstEmpty();
1833 if($firstEmpty === -1){
1834 $this->inventory->setItemInHand($item);
1835 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1836 $this->inventory->setItem($firstEmpty, $item);
1837 $this->inventory->setHeldItemIndex($firstEmpty);
1839 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1840 $this->inventory->setItemInHand($item);
1851 if($pos->distanceSquared($this->location) > 10000){
1855 $target = $this->getWorld()->getBlock($pos);
1857 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1858 if($this->isSpectator()){
1862 if($ev->isCancelled()){
1865 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1866 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1870 $block = $target->getSide($face);
1871 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1872 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1873 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1877 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1878 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1884 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1885 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1886 $this->blockBreakHandler->setTargetedFace($face);
1890 public function stopBreakBlock(Vector3 $pos) : void{
1891 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1892 $this->blockBreakHandler =
null;
1902 $this->removeCurrentWindow();
1904 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1905 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1906 $this->stopBreakBlock($pos);
1907 $item = $this->inventory->getItemInHand();
1908 $oldItem = clone $item;
1909 $returnedItems = [];
1910 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1911 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1912 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1916 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1928 $this->setUsingItem(false);
1930 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1931 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1932 $item = $this->inventory->getItemInHand();
1933 $oldItem = clone $item;
1934 $returnedItems = [];
1935 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1936 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1940 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1953 if(!$entity->isAlive()){
1957 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1961 $heldItem = $this->inventory->getItemInHand();
1962 $oldItem = clone $heldItem;
1964 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1965 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1966 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1968 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1972 $meleeEnchantmentDamage = 0;
1974 $meleeEnchantments = [];
1975 foreach($heldItem->getEnchantments() as $enchantment){
1976 $type = $enchantment->getType();
1977 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1978 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1979 $meleeEnchantments[] = $enchantment;
1982 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1984 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1985 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1988 $entity->attack($ev);
1989 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1991 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1992 if($ev->isCancelled()){
1993 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1996 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1998 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1999 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2002 foreach($meleeEnchantments as $enchantment){
2003 $type = $enchantment->getType();
2004 assert($type instanceof MeleeWeaponEnchantment);
2005 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2008 if($this->isAlive()){
2011 $returnedItems = [];
2012 $heldItem->onAttackEntity($entity, $returnedItems);
2013 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2015 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2028 if(!$ev->isCancelled()){
2029 $this->broadcastSound(new EntityAttackNoDamageSound());
2030 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2040 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2041 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2047 $item = $this->inventory->getItemInHand();
2048 $oldItem = clone $item;
2049 if(!$ev->isCancelled()){
2050 if($item->onInteractEntity($this, $entity, $clickPos)){
2051 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2052 if($item instanceof Durable && $item->isBroken()){
2053 $this->broadcastSound(new ItemBreakSound());
2055 $this->inventory->setItemInHand($item);
2058 return $entity->
onInteract($this, $clickPos);
2063 public function toggleSprint(
bool $sprint) : bool{
2064 if($sprint === $this->sprinting){
2067 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2069 if($ev->isCancelled()){
2072 $this->setSprinting($sprint);
2076 public function toggleSneak(
bool $sneak) : bool{
2077 if($sneak === $this->sneaking){
2080 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2082 if($ev->isCancelled()){
2085 $this->setSneaking($sneak);
2089 public function toggleFlight(
bool $fly) : bool{
2090 if($fly === $this->flying){
2093 $ev =
new PlayerToggleFlightEvent($this, $fly);
2094 if(!$this->allowFlight){
2098 if($ev->isCancelled()){
2101 $this->setFlying($fly);
2105 public function toggleGlide(
bool $glide) : bool{
2106 if($glide === $this->gliding){
2109 $ev =
new PlayerToggleGlideEvent($this, $glide);
2111 if($ev->isCancelled()){
2114 $this->setGliding($glide);
2118 public function toggleSwim(
bool $swim) : bool{
2119 if($swim === $this->swimming){
2122 $ev =
new PlayerToggleSwimEvent($this, $swim);
2124 if($ev->isCancelled()){
2127 $this->setSwimming($swim);
2131 public function emote(
string $emoteId) : void{
2132 $currentTick = $this->
server->getTick();
2133 if($currentTick - $this->lastEmoteTick > 5){
2134 $this->lastEmoteTick = $currentTick;
2135 $event =
new PlayerEmoteEvent($this, $emoteId);
2137 if(!$event->isCancelled()){
2138 $emoteId = $event->getEmoteId();
2139 parent::emote($emoteId);
2149 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2159 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2160 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2161 if($subtitle !==
""){
2162 $this->sendSubTitle($subtitle);
2164 $this->getNetworkSession()->onTitle($title);
2171 $this->getNetworkSession()->onSubTitle($subtitle);
2178 $this->getNetworkSession()->onActionBar($message);
2185 $this->getNetworkSession()->onClearTitle();
2192 $this->getNetworkSession()->onResetTitleOptions();
2203 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2204 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2212 $this->getNetworkSession()->onChatMessage($message);
2215 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2216 $this->getNetworkSession()->onJukeboxPopup($message);
2225 $this->getNetworkSession()->onPopup($message);
2228 public function sendTip(
string $message) : void{
2229 $this->getNetworkSession()->onTip($message);
2236 $this->getNetworkSession()->onToastNotification($title, $body);
2245 $id = $this->formIdCounter++;
2246 if($this->getNetworkSession()->onFormSent($id, $form)){
2247 $this->forms[$id] = $form;
2251 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2252 if(!isset($this->forms[$formId])){
2253 $this->logger->debug(
"Got unexpected response for form $formId");
2258 $this->forms[$formId]->handleResponse($this, $responseData);
2259 }
catch(FormValidationException $e){
2260 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2261 $this->logger->logException($e);
2263 unset($this->forms[$formId]);
2273 $this->getNetworkSession()->onCloseAllForms();
2288 if(!$ev->isCancelled()){
2289 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2304 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2306 if(!$ev->isCancelled()){
2307 $reason = $ev->getDisconnectReason();
2309 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2311 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2312 if($disconnectScreenMessage ===
""){
2313 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2315 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2337 if(!$this->isConnected()){
2341 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2342 $this->onPostDisconnect($reason, $quitMessage);
2353 if($this->isConnected()){
2354 throw new \LogicException(
"Player is still connected");
2358 $this->server->unsubscribeFromAllBroadcastChannels($this);
2360 $this->removeCurrentWindow();
2362 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2364 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2365 $this->server->broadcastMessage($quitMessage);
2369 $this->spawned =
false;
2372 $this->blockBreakHandler =
null;
2373 $this->despawnFromAll();
2375 $this->
server->removeOnlinePlayer($this);
2377 foreach($this->
server->getOnlinePlayers() as $player){
2378 if(!$player->canSee($this)){
2379 $player->showPlayer($this);
2382 $this->hiddenPlayers = [];
2384 if($this->location->isValid()){
2385 foreach($this->usedChunks as $index => $status){
2386 World::getXZ($index, $chunkX, $chunkZ);
2387 $this->unloadChunk($chunkX, $chunkZ);
2390 if(count($this->usedChunks) !== 0){
2391 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2393 $this->loadQueue = [];
2395 $this->removeCurrentWindow();
2396 $this->removePermanentInventories();
2398 $this->perm->getPermissionRecalculationCallbacks()->clear();
2400 $this->flagForDespawn();
2404 $this->disconnect(
"Player destroyed");
2405 $this->cursorInventory->removeAllViewers();
2406 $this->craftingGrid->removeAllViewers();
2407 parent::onDispose();
2411 $this->networkSession = null;
2412 unset($this->cursorInventory);
2413 unset($this->craftingGrid);
2414 $this->spawnPosition =
null;
2415 $this->deathPosition =
null;
2416 $this->blockBreakHandler =
null;
2417 parent::destroyCycles();
2427 public function __destruct(){
2428 parent::__destruct();
2429 $this->logger->debug(
"Destroyed by garbage collector");
2437 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2441 $nbt = $this->saveNBT();
2443 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2445 if($this->location->isValid()){
2446 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2449 if($this->hasValidCustomSpawn()){
2450 $spawn = $this->getSpawn();
2451 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2452 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2453 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2454 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2457 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2458 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2459 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2460 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2461 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2464 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2465 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2466 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2475 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2481 $this->removeCurrentWindow();
2483 $this->setDeathPosition($this->getPosition());
2485 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2488 if(!$ev->getKeepInventory()){
2489 foreach($ev->getDrops() as $item){
2490 $this->getWorld()->dropItem($this->location, $item);
2493 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2494 $this->inventory->setHeldItemIndex(0);
2495 $clearInventory($this->inventory);
2496 $clearInventory($this->armorInventory);
2497 $clearInventory($this->offHandInventory);
2500 if(!$ev->getKeepXp()){
2501 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2502 $this->xpManager->setXpAndProgress(0, 0.0);
2505 if($ev->getDeathMessage() !==
""){
2506 $this->server->broadcastMessage($ev->getDeathMessage());
2509 $this->startDeathAnimation();
2511 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2515 parent::onDeathUpdate($tickDiff);
2519 public function respawn() : void{
2520 if($this->
server->isHardcore()){
2521 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2522 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2527 $this->actuallyRespawn();
2530 protected function actuallyRespawn() : void{
2531 if($this->respawnLocked){
2534 $this->respawnLocked =
true;
2536 $this->logger->debug(
"Waiting for safe respawn position to be located");
2537 $spawn = $this->getSpawn();
2538 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2539 function(Position $safeSpawn) :
void{
2540 if(!$this->isConnected()){
2543 $this->logger->debug(
"Respawn position located, completing respawn");
2544 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2547 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2548 $this->teleport($realSpawn);
2550 $this->setSprinting(
false);
2551 $this->setSneaking(
false);
2552 $this->setFlying(
false);
2554 $this->extinguish();
2555 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2556 $this->deadTicks = 0;
2557 $this->noDamageTicks = 60;
2559 $this->effectManager->clear();
2560 $this->setHealth($this->getMaxHealth());
2562 foreach($this->attributeMap->getAll() as $attr){
2563 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2566 $attr->resetToDefault();
2569 $this->spawnToAll();
2570 $this->scheduleUpdate();
2572 $this->getNetworkSession()->onServerRespawn();
2573 $this->respawnLocked =
false;
2576 if($this->isConnected()){
2577 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2584 parent::applyPostDamageEffects($source);
2586 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2590 if(!$this->isAlive()){
2594 if($this->isCreative()
2595 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2598 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2602 parent::attack($source);
2605 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2606 parent::syncNetworkData($properties);
2608 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2609 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2611 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2612 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2614 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2615 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2617 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2618 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2620 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2621 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2622 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2626 public function sendData(?array $targets, ?array $data =
null) : void{
2627 if($targets === null){
2628 $targets = $this->getViewers();
2631 parent::sendData($targets, $data);
2635 if($this->spawned && $targets === null){
2636 $targets = $this->getViewers();
2639 parent::broadcastAnimation($animation, $targets);
2643 if($this->spawned && $targets === null){
2644 $targets = $this->getViewers();
2647 parent::broadcastSound($sound, $targets);
2653 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2654 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2660 if(parent::teleport($pos, $yaw, $pitch)){
2662 $this->removeCurrentWindow();
2665 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2666 $this->broadcastMovement(
true);
2668 $this->spawnToAll();
2670 $this->resetFallDistance();
2671 $this->nextChunkOrderRun = 0;
2672 if($this->spawnChunkLoadCount !== -1){
2673 $this->spawnChunkLoadCount = 0;
2675 $this->blockBreakHandler =
null;
2679 $this->resetLastMovements();
2687 protected function addDefaultWindows() : void{
2688 $this->cursorInventory = new PlayerCursorInventory($this);
2689 $this->craftingGrid =
new PlayerCraftingInventory($this);
2691 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2696 public function getCursorInventory() : PlayerCursorInventory{
2697 return $this->cursorInventory;
2700 public function getCraftingGrid() : CraftingGrid{
2701 return $this->craftingGrid;
2709 return $this->creativeInventory;
2716 $this->creativeInventory = $inventory;
2717 if($this->spawned && $this->isConnected()){
2718 $this->getNetworkSession()->getInvManager()?->syncCreative();
2726 private function doCloseInventory() : void{
2727 $inventories = [$this->craftingGrid, $this->cursorInventory];
2728 if($this->currentWindow instanceof TemporaryInventory){
2729 $inventories[] = $this->currentWindow;
2732 $builder =
new TransactionBuilder();
2733 foreach($inventories as $inventory){
2734 $contents = $inventory->getContents();
2736 if(count($contents) > 0){
2737 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2738 foreach($drops as $drop){
2739 $builder->addAction(
new DropItemAction($drop));
2742 $builder->getInventory($inventory)->clearAll();
2746 $actions = $builder->generateActions();
2747 if(count($actions) !== 0){
2748 $transaction =
new InventoryTransaction($this, $actions);
2750 $transaction->execute();
2751 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2752 }
catch(TransactionCancelledException){
2753 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2754 foreach($inventories as $inventory){
2755 $inventory->clearAll();
2757 }
catch(TransactionValidationException $e){
2758 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2767 return $this->currentWindow;
2774 if($inventory === $this->currentWindow){
2779 if($ev->isCancelled()){
2783 $this->removeCurrentWindow();
2785 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2786 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2788 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2789 $inventoryManager->onCurrentWindowChange($inventory);
2790 $inventory->onOpen($this);
2791 $this->currentWindow = $inventory;
2795 public function removeCurrentWindow() : void{
2796 $this->doCloseInventory();
2797 if($this->currentWindow !==
null){
2798 $currentWindow = $this->currentWindow;
2799 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2800 $this->currentWindow->onClose($this);
2801 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2802 $inventoryManager->onCurrentWindowRemove();
2804 $this->currentWindow =
null;
2805 (
new InventoryCloseEvent($currentWindow, $this))->call();
2809 protected function addPermanentInventories(Inventory ...$inventories) : void{
2810 foreach($inventories as $inventory){
2811 $inventory->onOpen($this);
2812 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2816 protected function removePermanentInventories() : void{
2817 foreach($this->permanentWindows as $inventory){
2818 $inventory->onClose($this);
2820 $this->permanentWindows = [];
2828 $block = $this->getWorld()->getBlock($position);
2830 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2831 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2833 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2837 use ChunkListenerNoOpTrait {
2838 onChunkChanged as
private;
2839 onChunkUnloaded as
private;
2843 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2844 if($status === UsedChunkStatus::SENT){
2845 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2846 $this->nextChunkOrderRun = 0;
2851 if($this->isUsingChunk($chunkX, $chunkZ)){
2852 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2853 $this->unloadChunk($chunkX, $chunkZ);