175 use PermissibleDelegateTrait;
177 private const MOVES_PER_TICK = 2;
178 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
181 private const MAX_CHAT_CHAR_LENGTH = 512;
187 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
188 private const MAX_REACH_DISTANCE_CREATIVE = 13;
189 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
190 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
192 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
194 public const TAG_FIRST_PLAYED =
"firstPlayed";
195 public const TAG_LAST_PLAYED =
"lastPlayed";
196 private const TAG_GAME_MODE =
"playerGameType";
197 private const TAG_SPAWN_WORLD =
"SpawnLevel";
198 private const TAG_SPAWN_X =
"SpawnX";
199 private const TAG_SPAWN_Y =
"SpawnY";
200 private const TAG_SPAWN_Z =
"SpawnZ";
201 private const TAG_DEATH_WORLD =
"DeathLevel";
202 private const TAG_DEATH_X =
"DeathPositionX";
203 private const TAG_DEATH_Y =
"DeathPositionY";
204 private const TAG_DEATH_Z =
"DeathPositionZ";
205 public const TAG_LEVEL =
"Level";
206 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
216 $lname = strtolower($name);
217 $len = strlen($name);
218 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
223 public bool $spawned =
false;
225 protected string $username;
226 protected string $displayName;
227 protected string $xuid =
"";
228 protected bool $authenticated;
231 protected ?InventoryWindow $currentWindow =
null;
233 protected array $permanentWindows = [];
234 protected Inventory $cursorInventory;
235 protected CraftingGrid $craftingGrid;
236 protected CreativeInventory $creativeInventory;
238 protected int $messageCounter = 2;
240 protected DateTimeImmutable $firstPlayed;
241 protected DateTimeImmutable $lastPlayed;
242 protected GameMode $gamemode;
248 protected array $usedChunks = [];
253 private array $activeChunkGenerationRequests = [];
258 protected array $loadQueue = [];
259 protected int $nextChunkOrderRun = 5;
262 private array $tickingChunks = [];
264 protected int $viewDistance = -1;
265 protected int $spawnThreshold;
266 protected int $spawnChunkLoadCount = 0;
267 protected int $chunksPerTick;
268 protected ChunkSelector $chunkSelector;
269 protected ChunkLoader $chunkLoader;
270 protected ChunkTicker $chunkTicker;
273 protected array $hiddenPlayers = [];
275 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
276 protected ?
float $lastMovementProcess =
null;
278 protected int $inAirTicks = 0;
280 protected float $stepHeight = 0.6;
282 protected ?Vector3 $sleeping =
null;
283 private ?
Position $spawnPosition =
null;
285 private bool $respawnLocked =
false;
287 private ?
Position $deathPosition =
null;
290 protected bool $autoJump =
true;
291 protected bool $allowFlight =
false;
292 protected bool $blockCollision =
true;
293 protected bool $flying =
false;
295 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
298 protected ?
int $lineHeight =
null;
299 protected string $locale =
"en_US";
301 protected int $startAction = -1;
307 protected array $usedItemsCooldown = [];
309 private int $lastEmoteTick = 0;
311 protected int $formIdCounter = 0;
313 protected array $forms = [];
315 protected \Logger $logger;
320 $username = TextFormat::clean($playerInfo->getUsername());
321 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
324 $this->networkSession = $session;
325 $this->playerInfo = $playerInfo;
326 $this->authenticated = $authenticated;
328 $this->username = $username;
329 $this->displayName = $this->username;
330 $this->locale = $this->playerInfo->getLocale();
332 $this->uuid = $this->playerInfo->getUuid();
333 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
335 $this->creativeInventory = CreativeInventory::getInstance();
337 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
338 if($this->
server->isOp($this->username)){
339 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
342 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
343 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
348 $world = $spawnLocation->
getWorld();
350 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
351 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
352 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
353 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
354 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
356 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
360 $this->setNameTag($this->username);
363 private function callDummyItemHeldEvent() : void{
364 $slot = $this->hotbar->getSelectedIndex();
373 protected function initEntity(
CompoundTag $nbt) : void{
374 parent::initEntity($nbt);
375 $this->addDefaultWindows();
377 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
378 function(Inventory $unused,
int $slot) :
void{
379 if($slot === $this->hotbar->getSelectedIndex()){
380 $this->setUsingItem(
false);
382 $this->callDummyItemHeldEvent();
386 $this->setUsingItem(
false);
387 $this->callDummyItemHeldEvent();
391 $now = (int) (microtime(
true) * 1000);
392 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
393 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
395 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
396 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
398 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
399 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
401 $this->internalSetGameMode($this->
server->getGamemode());
404 $this->keepMovement =
true;
406 $this->setNameTagVisible();
407 $this->setNameTagAlwaysVisible();
408 $this->setCanClimb();
410 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
411 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
413 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
414 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
418 public function getLeaveMessage() : Translatable|string{
420 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
426 public function isAuthenticated() : bool{
427 return $this->authenticated;
452 return parent::getUniqueId();
459 return $this->firstPlayed;
466 return $this->lastPlayed;
469 public function hasPlayedBefore() : bool{
470 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
483 if($this->allowFlight !== $value){
484 $this->allowFlight = $value;
485 $this->getNetworkSession()->syncAbilities($this);
496 return $this->allowFlight;
508 if($this->blockCollision !== $value){
509 $this->blockCollision = $value;
510 $this->getNetworkSession()->syncAbilities($this);
519 return $this->blockCollision;
522 public function setFlying(
bool $value) : void{
523 if($this->flying !== $value){
524 $this->flying = $value;
525 $this->resetFallDistance();
526 $this->getNetworkSession()->syncAbilities($this);
530 public function isFlying() : bool{
531 return $this->flying;
548 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
549 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
550 $this->getNetworkSession()->syncAbilities($this);
566 return $this->flightSpeedMultiplier;
569 public function setAutoJump(
bool $value) : void{
570 if($this->autoJump !== $value){
571 $this->autoJump = $value;
572 $this->getNetworkSession()->syncAdventureSettings();
576 public function hasAutoJump() : bool{
577 return $this->autoJump;
580 public function spawnTo(Player $player) : void{
581 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
582 parent::spawnTo($player);
586 public function getServer() : Server{
591 return $this->lineHeight ?? 7;
595 if($height !== null && $height < 1){
596 throw new \InvalidArgumentException(
"Line height must be at least 1");
598 $this->lineHeight = $height;
601 public function canSee(
Player $player) : bool{
602 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
605 public function hidePlayer(Player $player) : void{
606 if($player === $this){
609 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
610 $player->despawnFrom($this);
613 public function showPlayer(Player $player) : void{
614 if($player === $this){
617 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
618 if($player->isOnline()){
619 $player->spawnTo($this);
623 public function canCollideWith(Entity $entity) : bool{
627 public function canBeCollidedWith() : bool{
628 return !$this->isSpectator() && parent::canBeCollidedWith();
631 public function resetFallDistance() : void{
632 parent::resetFallDistance();
633 $this->inAirTicks = 0;
636 public function getViewDistance() : int{
637 return $this->viewDistance;
640 public function setViewDistance(
int $distance) : void{
641 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
643 if($newViewDistance !== $this->viewDistance){
644 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
648 $this->viewDistance = $newViewDistance;
650 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
652 $this->nextChunkOrderRun = 0;
654 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
656 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
659 public function isOnline() : bool{
660 return $this->isConnected();
663 public function isConnected() : bool{
664 return $this->networkSession !== null && $this->networkSession->isConnected();
667 public function getNetworkSession() : NetworkSession{
668 if($this->networkSession === null){
669 throw new \LogicException(
"Player is not connected");
671 return $this->networkSession;
678 return $this->username;
685 return $this->displayName;
688 public function setDisplayName(
string $name) : void{
692 $this->displayName = $ev->getNewName();
703 return $this->locale;
706 public function getLanguage() :
Language{
707 return $this->
server->getLanguage();
714 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
718 if($ev->isCancelled()){
719 $this->sendSkin([$this]);
723 $this->setSkin($ev->getNewSkin());
724 $this->sendSkin($this->server->getOnlinePlayers());
733 public function sendSkin(?array $targets =
null) : void{
734 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
741 return $this->startAction > -1;
744 public function setUsingItem(
bool $value) : void{
745 $this->startAction = $value ? $this->
server->getTick() : -1;
746 $this->networkPropertiesDirty =
true;
754 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
761 $this->checkItemCooldowns();
762 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
769 $this->checkItemCooldowns();
770 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
777 $ticks = $ticks ?? $item->getCooldownTicks();
779 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
780 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
784 protected function checkItemCooldowns() : void{
785 $serverTick = $this->
server->getTick();
786 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
787 if($cooldownUntil <= $serverTick){
788 unset($this->usedItemsCooldown[$itemId]);
793 protected function setPosition(Vector3 $pos) : bool{
794 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
795 if(parent::setPosition($pos)){
796 $newWorld = $this->getWorld();
797 if($oldWorld !== $newWorld){
798 if($oldWorld !==
null){
799 foreach($this->usedChunks as $index => $status){
800 World::getXZ($index, $X, $Z);
801 $this->unloadChunk($X, $Z, $oldWorld);
805 $this->usedChunks = [];
806 $this->loadQueue = [];
807 $this->getNetworkSession()->onEnterWorld();
816 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
817 $world = $world ?? $this->getWorld();
818 $index = World::chunkHash($x, $z);
819 if(isset($this->usedChunks[$index])){
820 foreach($world->getChunkEntities($x, $z) as $entity){
821 if($entity !== $this){
822 $entity->despawnFrom($this);
825 $this->getNetworkSession()->stopUsingChunk($x, $z);
826 unset($this->usedChunks[$index]);
827 unset($this->activeChunkGenerationRequests[$index]);
829 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
830 $world->unregisterChunkListener($this, $x, $z);
831 unset($this->loadQueue[$index]);
832 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
833 unset($this->tickingChunks[$index]);
836 protected function spawnEntitiesOnAllChunks() : void{
837 foreach($this->usedChunks as $chunkHash => $status){
838 if($status === UsedChunkStatus::SENT){
839 World::getXZ($chunkHash, $chunkX, $chunkZ);
840 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
845 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
846 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
847 if($entity !== $this && !$entity->isFlaggedForDespawn()){
848 $entity->spawnTo($this);
858 if(!$this->isConnected()){
862 Timings::$playerChunkSend->startTiming();
865 $world = $this->getWorld();
867 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
868 foreach($this->loadQueue as $index => $distance){
869 if($count >= $limit){
875 World::getXZ($index, $X, $Z);
879 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
880 $this->activeChunkGenerationRequests[$index] =
true;
881 unset($this->loadQueue[$index]);
882 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
883 $world->registerChunkListener($this, $X, $Z);
884 if(isset($this->tickingChunks[$index])){
885 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
888 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
889 function() use ($X, $Z, $index, $world) :
void{
890 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
893 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
899 unset($this->activeChunkGenerationRequests[$index]);
900 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
902 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
903 $this->usedChunks[$index] = UsedChunkStatus::SENT;
904 if($this->spawnChunkLoadCount === -1){
905 $this->spawnEntitiesOnChunk($X, $Z);
906 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
907 $this->spawnChunkLoadCount = -1;
909 $this->spawnEntitiesOnAllChunks();
911 $this->getNetworkSession()->notifyTerrainReady();
913 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
916 static function() :
void{
922 Timings::$playerChunkSend->stopTiming();
925 private function recheckBroadcastPermissions() : void{
927 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
928 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
929 ] as $permission => $channel){
930 if($this->hasPermission($permission)){
931 $this->
server->subscribeToBroadcastChannel($channel, $this);
933 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
946 $this->spawned =
true;
947 $this->recheckBroadcastPermissions();
948 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
949 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
950 $this->recheckBroadcastPermissions();
954 $ev =
new PlayerJoinEvent($this,
955 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
958 if($ev->getJoinMessage() !==
""){
959 $this->server->broadcastMessage($ev->getJoinMessage());
962 $this->noDamageTicks = 60;
966 if($this->getHealth() <= 0){
967 $this->logger->debug(
"Quit while dead, forcing respawn");
968 $this->actuallyRespawn();
979 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
980 $world = $this->getWorld();
981 foreach($oldTickingChunks as $hash => $_){
982 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
984 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
985 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
988 foreach($newTickingChunks as $hash => $_){
989 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
991 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
992 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1002 if(!$this->isConnected() || $this->viewDistance === -1){
1006 Timings::$playerChunkOrder->startTiming();
1009 $tickingChunks = [];
1010 $unloadChunks = $this->usedChunks;
1012 $world = $this->getWorld();
1013 $tickingChunkRadius = $world->getChunkTickRadius();
1015 foreach($this->chunkSelector->selectChunks(
1016 $this->server->getAllowedViewDistance($this->viewDistance),
1017 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1018 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1019 ) as $radius => $hash){
1020 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1021 $newOrder[$hash] =
true;
1023 if($radius < $tickingChunkRadius){
1024 $tickingChunks[$hash] =
true;
1026 unset($unloadChunks[$hash]);
1029 foreach($unloadChunks as $index => $status){
1030 World::getXZ($index, $X, $Z);
1031 $this->unloadChunk($X, $Z);
1034 $this->loadQueue = $newOrder;
1036 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1037 $this->tickingChunks = $tickingChunks;
1039 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1040 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1043 Timings::$playerChunkOrder->stopTiming();
1051 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1059 return $this->usedChunks;
1066 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1073 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1074 return $status === UsedChunkStatus::SENT;
1081 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1082 $this->nextChunkOrderRun = PHP_INT_MAX;
1083 $this->orderChunks();
1086 if(count($this->loadQueue) > 0){
1087 $this->requestChunks();
1091 public function getDeathPosition() : ?Position{
1092 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1093 $this->deathPosition =
null;
1095 return $this->deathPosition;
1103 if($pos instanceof
Position && $pos->world !==
null){
1104 $world = $pos->world;
1106 $world = $this->getWorld();
1108 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1110 $this->deathPosition =
null;
1112 $this->networkPropertiesDirty =
true;
1119 if($this->hasValidCustomSpawn()){
1120 return $this->spawnPosition;
1122 $world = $this->
server->getWorldManager()->getDefaultWorld();
1124 return $world->getSpawnLocation();
1128 public function hasValidCustomSpawn() : bool{
1129 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1141 $world = $this->getWorld();
1143 $world = $pos->getWorld();
1145 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1147 $this->spawnPosition =
null;
1149 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1152 public function isSleeping() : bool{
1153 return $this->sleeping !== null;
1156 public function sleepOn(Vector3 $pos) : bool{
1157 $pos = $pos->floor();
1158 $b = $this->getWorld()->getBlock($pos);
1160 $ev =
new PlayerBedEnterEvent($this, $b);
1162 if($ev->isCancelled()){
1166 if($b instanceof Bed){
1168 $this->getWorld()->setBlock($pos, $b);
1171 $this->sleeping = $pos;
1172 $this->networkPropertiesDirty =
true;
1174 $this->setSpawn($pos);
1176 $this->getWorld()->setSleepTicks(60);
1181 public function stopSleep() : void{
1182 if($this->sleeping instanceof Vector3){
1183 $b = $this->getWorld()->getBlock($this->sleeping);
1184 if($b instanceof Bed){
1185 $b->setOccupied(
false);
1186 $this->getWorld()->setBlock($this->sleeping, $b);
1188 (
new PlayerBedLeaveEvent($this, $b))->call();
1190 $this->sleeping =
null;
1191 $this->networkPropertiesDirty =
true;
1193 $this->getWorld()->setSleepTicks(0);
1195 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1199 public function getGamemode() : GameMode{
1200 return $this->gamemode;
1203 protected function internalSetGameMode(GameMode $gameMode) : void{
1204 $this->gamemode = $gameMode;
1206 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1207 $this->hungerManager->setEnabled($this->isSurvival());
1209 if($this->isSpectator()){
1210 $this->setFlying(
true);
1211 $this->setHasBlockCollision(
false);
1213 $this->onGround =
false;
1217 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1219 if($this->isSurvival()){
1220 $this->setFlying(
false);
1222 $this->setHasBlockCollision(
true);
1223 $this->setSilent(
false);
1224 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1232 if($this->gamemode === $gm){
1238 if($ev->isCancelled()){
1242 $this->internalSetGameMode($gm);
1244 if($this->isSpectator()){
1245 $this->despawnFromAll();
1247 $this->spawnToAll();
1250 $this->getNetworkSession()->syncGameMode($this->gamemode);
1261 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1271 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1281 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1284 public function isSpectator() : bool{
1285 return $this->gamemode === GameMode::SPECTATOR;
1292 return $this->gamemode !== GameMode::CREATIVE;
1296 if($this->hasFiniteResources()){
1297 return parent::getDrops();
1304 if($this->hasFiniteResources()){
1305 return parent::getXpDropAmount();
1311 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1312 if($this->gamemode === GameMode::SPECTATOR){
1313 $this->onGround =
false;
1316 $bb =
new AxisAlignedBB(
1317 $this->boundingBox->minX,
1318 $this->location->y - 0.2,
1319 $this->boundingBox->minZ,
1320 $this->boundingBox->maxX,
1321 $this->location->y + 0.2,
1322 $this->boundingBox->maxZ
1327 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1329 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1337 protected function checkNearEntities() : void{
1338 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1339 $entity->scheduleUpdate();
1341 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1345 $entity->onCollideWithPlayer($this);
1349 public function getInAirTicks() : int{
1350 return $this->inAirTicks;
1362 Timings::$playerMove->startTiming();
1364 $this->actuallyHandleMovement($newPos);
1366 Timings::$playerMove->stopTiming();
1370 private function actuallyHandleMovement(Vector3 $newPos) : void{
1371 $this->moveRateLimit--;
1372 if($this->moveRateLimit < 0){
1376 $oldPos = $this->location;
1377 $distanceSquared = $newPos->distanceSquared($oldPos);
1381 if($distanceSquared > 225){
1393 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1394 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1396 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1398 $this->nextChunkOrderRun = 0;
1401 if(!$revert && $distanceSquared !== 0.0){
1402 $dx = $newPos->x - $oldPos->x;
1403 $dy = $newPos->y - $oldPos->y;
1404 $dz = $newPos->z - $oldPos->z;
1406 $this->move($dx, $dy, $dz);
1410 $this->revertMovement($oldPos);
1418 $now = microtime(true);
1419 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1420 $exceededRateLimit = $this->moveRateLimit < 0;
1421 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1422 $this->lastMovementProcess = $now;
1424 $from = clone $this->lastLocation;
1425 $to = clone $this->location;
1427 $delta = $to->distanceSquared($from);
1428 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1430 if($delta > 0.0001 || $deltaAngle > 1.0){
1431 if(PlayerMoveEvent::hasHandlers()){
1436 if($ev->isCancelled()){
1437 $this->revertMovement($from);
1441 if($to->distanceSquared($ev->getTo()) > 0.01){
1442 $this->teleport($ev->getTo());
1447 $this->lastLocation = $to;
1448 $this->broadcastMovement();
1450 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1451 if($horizontalDistanceTravelled > 0){
1453 if($this->isSprinting()){
1454 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1456 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1459 if($this->nextChunkOrderRun > 20){
1460 $this->nextChunkOrderRun = 20;
1465 if($exceededRateLimit){
1466 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1467 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1471 protected function revertMovement(Location $from) : void{
1472 $this->setPosition($from);
1473 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1476 protected function calculateFallDamage(
float $fallDistance) : float{
1477 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1485 public function setMotion(
Vector3 $motion) : bool{
1486 if(parent::setMotion($motion)){
1487 $this->broadcastMotion();
1488 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1495 protected function updateMovement(
bool $teleport =
false) : void{
1499 protected function tryChangeMovement() : void{
1503 public function onUpdate(int $currentTick) : bool{
1504 $tickDiff = $currentTick - $this->lastUpdate;
1510 $this->messageCounter = 2;
1512 $this->lastUpdate = $currentTick;
1514 if($this->justCreated){
1515 $this->onFirstUpdate($currentTick);
1518 if(!$this->isAlive() && $this->spawned){
1519 $this->onDeathUpdate($tickDiff);
1523 $this->timings->startTiming();
1526 Timings::$playerMove->startTiming();
1527 $this->processMostRecentMovements();
1528 $this->motion = Vector3::zero();
1529 if($this->onGround){
1530 $this->inAirTicks = 0;
1532 $this->inAirTicks += $tickDiff;
1534 Timings::$playerMove->stopTiming();
1536 Timings::$entityBaseTick->startTiming();
1537 $this->entityBaseTick($tickDiff);
1538 Timings::$entityBaseTick->stopTiming();
1540 if($this->isCreative() && $this->fireTicks > 1){
1541 $this->fireTicks = 1;
1544 if(!$this->isSpectator() && $this->isAlive()){
1545 Timings::$playerCheckNearEntities->startTiming();
1546 $this->checkNearEntities();
1547 Timings::$playerCheckNearEntities->stopTiming();
1550 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1551 $this->blockBreakHandler =
null;
1555 $this->timings->stopTiming();
1561 return $this->isCreative() || parent::canEat();
1565 return $this->isCreative() || parent::canBreathe();
1574 $eyePos = $this->getEyePos();
1575 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1579 $dV = $this->getDirectionVector();
1580 $eyeDot = $dV->dot($eyePos);
1581 $targetDot = $dV->dot($pos);
1582 return ($targetDot - $eyeDot) >= -$maxDiff;
1589 public function chat(
string $message) : bool{
1590 $this->removeCurrentWindow();
1592 if($this->messageCounter <= 0){
1598 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1599 if(strlen($message) > $maxTotalLength){
1603 $message = TextFormat::clean($message,
false);
1604 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1605 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1606 if(str_starts_with($messagePart,
'./')){
1607 $messagePart = substr($messagePart, 1);
1610 if(str_starts_with($messagePart,
"/")){
1611 Timings::$playerCommand->startTiming();
1612 $this->server->dispatchCommand($this, substr($messagePart, 1));
1613 Timings::$playerCommand->stopTiming();
1615 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1617 if(!$ev->isCancelled()){
1618 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1627 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1628 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1631 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1635 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1637 if($ev->isCancelled()){
1641 $this->hotbar->setSelectedIndex($hotbarSlot);
1642 $this->setUsingItem(
false);
1650 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1651 $heldItemChanged = false;
1653 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1656 $newReplica = clone $oldHeldItem;
1657 $newReplica->setCount($newHeldItem->getCount());
1658 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1659 $newDamage = $newHeldItem->getDamage();
1660 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1661 $newReplica->setDamage($newDamage);
1664 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1666 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1667 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1668 $this->broadcastSound(
new ItemBreakSound());
1670 $this->setMainHandItem($newHeldItem);
1671 $heldItemChanged =
true;
1675 if(!$heldItemChanged){
1676 $newHeldItem = $oldHeldItem;
1679 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1680 $this->setMainHandItem(array_shift($extraReturnedItems));
1682 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1684 $ev =
new PlayerDropItemEvent($this, $drop);
1685 if($this->isSpectator()){
1689 if(!$ev->isCancelled()){
1690 $this->dropItem($drop);
1701 $directionVector = $this->getDirectionVector();
1702 $item = $this->getMainHandItem();
1703 $oldItem = clone $item;
1706 if($this->hasItemCooldown($item) || $this->isSpectator()){
1712 if($ev->isCancelled()){
1716 $returnedItems = [];
1717 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1718 if($result === ItemUseResult::FAIL){
1722 $this->resetItemCooldown($oldItem);
1723 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1725 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1736 $slot = $this->getMainHandItem();
1738 $oldItem = clone $slot;
1741 if($this->hasItemCooldown($slot)){
1746 if($ev->isCancelled() || !$this->consumeObject($slot)){
1750 $this->setUsingItem(
false);
1751 $this->resetItemCooldown($oldItem);
1754 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1769 $item = $this->getMainHandItem();
1770 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1774 $oldItem = clone $item;
1776 $returnedItems = [];
1777 $result = $item->onReleaseUsing($this, $returnedItems);
1778 if($result === ItemUseResult::SUCCESS){
1779 $this->resetItemCooldown($oldItem);
1780 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1786 $this->setUsingItem(
false);
1790 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1791 $block = $this->getWorld()->getBlock($pos);
1792 if($block instanceof UnknownBlock){
1796 $item = $block->getPickedItem($addTileNBT);
1798 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1799 $existingSlot = $this->inventory->first($item);
1800 if($existingSlot === -1 && $this->hasFiniteResources()){
1805 if(!$ev->isCancelled()){
1806 $this->equipOrAddPickedItem($existingSlot, $item);
1812 public function pickEntity(
int $entityId) : bool{
1813 $entity = $this->getWorld()->getEntity($entityId);
1814 if($entity ===
null){
1818 $item = $entity->getPickedItem();
1823 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1824 $existingSlot = $this->inventory->first($item);
1825 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1830 if(!$ev->isCancelled()){
1831 $this->equipOrAddPickedItem($existingSlot, $item);
1837 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1838 if($existingSlot !== -1){
1839 if($existingSlot < $this->hotbar->getSize()){
1840 $this->hotbar->setSelectedIndex($existingSlot);
1842 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1845 $firstEmpty = $this->inventory->firstEmpty();
1846 if($firstEmpty === -1){
1847 $this->setMainHandItem($item);
1848 }elseif($firstEmpty < $this->hotbar->getSize()){
1849 $this->inventory->setItem($firstEmpty, $item);
1850 $this->hotbar->setSelectedIndex($firstEmpty);
1852 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1853 $this->setMainHandItem($item);
1864 if($pos->distanceSquared($this->location) > 10000){
1868 $target = $this->getWorld()->getBlock($pos);
1870 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1871 if($this->isSpectator()){
1875 if($ev->isCancelled()){
1878 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1879 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1883 $block = $target->getSide($face);
1884 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1885 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1886 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1890 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1891 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1897 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1898 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1899 $this->blockBreakHandler->setTargetedFace($face);
1903 public function stopBreakBlock(Vector3 $pos) : void{
1904 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1905 $this->blockBreakHandler =
null;
1915 $this->removeCurrentWindow();
1917 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1918 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1919 $this->stopBreakBlock($pos);
1920 $item = $this->getMainHandItem();
1921 $oldItem = clone $item;
1922 $returnedItems = [];
1923 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1924 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1925 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1929 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1941 $this->setUsingItem(false);
1943 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1944 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1945 $item = $this->getMainHandItem();
1946 $oldItem = clone $item;
1947 $returnedItems = [];
1948 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1949 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1953 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1966 if(!$entity->isAlive()){
1970 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1974 $heldItem = $this->getMainHandItem();
1975 $oldItem = clone $heldItem;
1977 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1978 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1979 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1981 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1985 $meleeEnchantmentDamage = 0;
1987 $meleeEnchantments = [];
1988 foreach($heldItem->getEnchantments() as $enchantment){
1989 $type = $enchantment->getType();
1990 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1991 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1992 $meleeEnchantments[] = $enchantment;
1995 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1997 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1998 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2001 $entity->attack($ev);
2002 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2004 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2005 if($ev->isCancelled()){
2006 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2009 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2011 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2012 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2015 foreach($meleeEnchantments as $enchantment){
2016 $type = $enchantment->getType();
2017 assert($type instanceof MeleeWeaponEnchantment);
2018 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2021 if($this->isAlive()){
2024 $returnedItems = [];
2025 $heldItem->onAttackEntity($entity, $returnedItems);
2026 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2028 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2041 if(!$ev->isCancelled()){
2042 $this->broadcastSound(new EntityAttackNoDamageSound());
2043 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2053 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2054 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2060 $item = $this->getMainHandItem();
2061 $oldItem = clone $item;
2062 if(!$ev->isCancelled()){
2063 if($item->onInteractEntity($this, $entity, $clickPos)){
2064 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2065 if($item instanceof Durable && $item->isBroken()){
2066 $this->broadcastSound(new ItemBreakSound());
2068 $this->setMainHandItem($item);
2071 return $entity->
onInteract($this, $clickPos);
2076 public function toggleSprint(
bool $sprint) : bool{
2077 if($sprint === $this->sprinting){
2080 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2082 if($ev->isCancelled()){
2085 $this->setSprinting($sprint);
2089 public function toggleSneak(
bool $sneak) : bool{
2090 if($sneak === $this->sneaking){
2093 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2095 if($ev->isCancelled()){
2098 $this->setSneaking($sneak);
2102 public function toggleFlight(
bool $fly) : bool{
2103 if($fly === $this->flying){
2106 $ev =
new PlayerToggleFlightEvent($this, $fly);
2107 if(!$this->allowFlight){
2111 if($ev->isCancelled()){
2114 $this->setFlying($fly);
2118 public function toggleGlide(
bool $glide) : bool{
2119 if($glide === $this->gliding){
2122 $ev =
new PlayerToggleGlideEvent($this, $glide);
2124 if($ev->isCancelled()){
2127 $this->setGliding($glide);
2131 public function toggleSwim(
bool $swim) : bool{
2132 if($swim === $this->swimming){
2135 $ev =
new PlayerToggleSwimEvent($this, $swim);
2137 if($ev->isCancelled()){
2140 $this->setSwimming($swim);
2144 public function emote(
string $emoteId) : void{
2145 $currentTick = $this->
server->getTick();
2146 if($currentTick - $this->lastEmoteTick > 5){
2147 $this->lastEmoteTick = $currentTick;
2148 $event =
new PlayerEmoteEvent($this, $emoteId);
2150 if(!$event->isCancelled()){
2151 $emoteId = $event->getEmoteId();
2152 parent::emote($emoteId);
2162 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2172 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2173 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2174 if($subtitle !==
""){
2175 $this->sendSubTitle($subtitle);
2177 $this->getNetworkSession()->onTitle($title);
2184 $this->getNetworkSession()->onSubTitle($subtitle);
2191 $this->getNetworkSession()->onActionBar($message);
2198 $this->getNetworkSession()->onClearTitle();
2205 $this->getNetworkSession()->onResetTitleOptions();
2216 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2217 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2225 $this->getNetworkSession()->onChatMessage($message);
2228 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2229 $this->getNetworkSession()->onJukeboxPopup($message);
2238 $this->getNetworkSession()->onPopup($message);
2241 public function sendTip(
string $message) : void{
2242 $this->getNetworkSession()->onTip($message);
2249 $this->getNetworkSession()->onToastNotification($title, $body);
2258 $id = $this->formIdCounter++;
2259 if($this->getNetworkSession()->onFormSent($id, $form)){
2260 $this->forms[$id] = $form;
2264 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2265 if(!isset($this->forms[$formId])){
2266 $this->logger->debug(
"Got unexpected response for form $formId");
2271 $this->forms[$formId]->handleResponse($this, $responseData);
2272 }
catch(FormValidationException $e){
2273 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2274 $this->logger->logException($e);
2276 unset($this->forms[$formId]);
2286 $this->getNetworkSession()->onCloseAllForms();
2301 if(!$ev->isCancelled()){
2302 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2317 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2319 if(!$ev->isCancelled()){
2320 $reason = $ev->getDisconnectReason();
2322 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2324 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2325 if($disconnectScreenMessage ===
""){
2326 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2328 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2350 if(!$this->isConnected()){
2354 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2355 $this->onPostDisconnect($reason, $quitMessage);
2366 if($this->isConnected()){
2367 throw new \LogicException(
"Player is still connected");
2371 $this->server->unsubscribeFromAllBroadcastChannels($this);
2373 $this->removeCurrentWindow();
2375 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2377 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2378 $this->server->broadcastMessage($quitMessage);
2382 $this->spawned =
false;
2385 $this->blockBreakHandler =
null;
2386 $this->despawnFromAll();
2388 $this->
server->removeOnlinePlayer($this);
2390 foreach($this->
server->getOnlinePlayers() as $player){
2391 if(!$player->canSee($this)){
2392 $player->showPlayer($this);
2395 $this->hiddenPlayers = [];
2397 if($this->location->isValid()){
2398 foreach($this->usedChunks as $index => $status){
2399 World::getXZ($index, $chunkX, $chunkZ);
2400 $this->unloadChunk($chunkX, $chunkZ);
2403 if(count($this->usedChunks) !== 0){
2404 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2406 $this->loadQueue = [];
2408 $this->removeCurrentWindow();
2409 $this->removePermanentWindows();
2411 $this->perm->getPermissionRecalculationCallbacks()->clear();
2413 $this->flagForDespawn();
2417 $this->disconnect(
"Player destroyed");
2418 $this->cursorInventory->removeAllWindows();
2419 $this->craftingGrid->removeAllWindows();
2420 parent::onDispose();
2424 $this->networkSession = null;
2425 $this->spawnPosition =
null;
2426 $this->deathPosition =
null;
2427 $this->blockBreakHandler =
null;
2428 parent::destroyCycles();
2438 public function __destruct(){
2439 parent::__destruct();
2440 $this->logger->debug(
"Destroyed by garbage collector");
2448 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2452 $nbt = $this->saveNBT();
2454 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2456 if($this->location->isValid()){
2457 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2460 if($this->hasValidCustomSpawn()){
2461 $spawn = $this->getSpawn();
2462 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2463 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2464 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2465 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2468 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2469 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2470 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2471 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2472 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2475 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2476 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2477 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2486 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2492 $this->removeCurrentWindow();
2494 $this->setDeathPosition($this->getPosition());
2496 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2499 if(!$ev->getKeepInventory()){
2500 foreach($ev->getDrops() as $item){
2501 $this->getWorld()->dropItem($this->location, $item);
2504 $this->hotbar->setSelectedIndex(0);
2505 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2506 $clearInventory($this->inventory);
2507 $clearInventory($this->armorInventory);
2508 $clearInventory($this->offHandInventory);
2511 if(!$ev->getKeepXp()){
2512 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2513 $this->xpManager->setXpAndProgress(0, 0.0);
2516 if($ev->getDeathMessage() !==
""){
2517 $this->server->broadcastMessage($ev->getDeathMessage());
2520 $this->startDeathAnimation();
2522 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2526 parent::onDeathUpdate($tickDiff);
2530 public function respawn() : void{
2531 if($this->
server->isHardcore()){
2532 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2533 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2538 $this->actuallyRespawn();
2541 protected function actuallyRespawn() : void{
2542 if($this->respawnLocked){
2545 $this->respawnLocked =
true;
2547 $this->logger->debug(
"Waiting for safe respawn position to be located");
2548 $spawn = $this->getSpawn();
2549 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2550 function(Position $safeSpawn) :
void{
2551 if(!$this->isConnected()){
2554 $this->logger->debug(
"Respawn position located, completing respawn");
2555 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2556 $spawnPosition = $ev->getRespawnPosition();
2557 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2558 if($spawnBlock instanceof RespawnAnchor){
2559 if($spawnBlock->getCharges() > 0){
2560 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2561 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2563 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2564 if($defaultSpawn !==
null){
2565 $this->setSpawn($defaultSpawn);
2566 $ev->setRespawnPosition($defaultSpawn);
2567 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2573 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2574 $this->teleport($realSpawn);
2576 $this->setSprinting(
false);
2577 $this->setSneaking(
false);
2578 $this->setFlying(
false);
2580 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2581 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2582 $this->deadTicks = 0;
2583 $this->noDamageTicks = 60;
2585 $this->effectManager->clear();
2586 $this->setHealth($this->getMaxHealth());
2588 foreach($this->attributeMap->getAll() as $attr){
2589 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2592 $attr->resetToDefault();
2595 $this->spawnToAll();
2596 $this->scheduleUpdate();
2598 $this->getNetworkSession()->onServerRespawn();
2599 $this->respawnLocked =
false;
2602 if($this->isConnected()){
2603 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2610 parent::applyPostDamageEffects($source);
2612 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2616 if(!$this->isAlive()){
2620 if($this->isCreative()
2621 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2624 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2628 parent::attack($source);
2631 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2632 parent::syncNetworkData($properties);
2634 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2635 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2637 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2638 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2640 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2641 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2643 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2644 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2646 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2647 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2648 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2652 public function sendData(?array $targets, ?array $data =
null) : void{
2653 if($targets === null){
2654 $targets = $this->getViewers();
2657 parent::sendData($targets, $data);
2661 if($this->spawned && $targets === null){
2662 $targets = $this->getViewers();
2665 parent::broadcastAnimation($animation, $targets);
2669 if($this->spawned && $targets === null){
2670 $targets = $this->getViewers();
2673 parent::broadcastSound($sound, $targets);
2679 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2680 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2686 if(parent::teleport($pos, $yaw, $pitch)){
2688 $this->removeCurrentWindow();
2691 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2692 $this->broadcastMovement(
true);
2694 $this->spawnToAll();
2696 $this->resetFallDistance();
2697 $this->nextChunkOrderRun = 0;
2698 if($this->spawnChunkLoadCount !== -1){
2699 $this->spawnChunkLoadCount = 0;
2701 $this->blockBreakHandler =
null;
2705 $this->resetLastMovements();
2713 protected function addDefaultWindows() : void{
2714 $this->cursorInventory = new SimpleInventory(1);
2715 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2717 $this->addPermanentWindows([
2718 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2719 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2720 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2721 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2722 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2726 public function getCursorInventory() : Inventory{
2727 return $this->cursorInventory;
2730 public function getCraftingGrid() : CraftingGrid{
2731 return $this->craftingGrid;
2739 return $this->creativeInventory;
2746 $this->creativeInventory = $inventory;
2747 if($this->spawned && $this->isConnected()){
2748 $this->getNetworkSession()->getInvManager()?->syncCreative();
2756 private function doCloseInventory() : void{
2757 $windowsToClear = [];
2758 $mainInventoryWindow =
null;
2759 foreach($this->permanentWindows as $window){
2760 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2761 $windowsToClear[] = $window;
2762 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2763 $mainInventoryWindow = $window;
2766 if($mainInventoryWindow ===
null){
2770 throw new AssumptionFailedError(
"This should never be null");
2773 if($this->currentWindow instanceof TemporaryInventoryWindow){
2774 $windowsToClear[] = $this->currentWindow;
2777 $builder =
new TransactionBuilder();
2778 foreach($windowsToClear as $window){
2779 $contents = $window->getInventory()->getContents();
2781 if(count($contents) > 0){
2782 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2783 foreach($drops as $drop){
2784 $builder->addAction(
new DropItemAction($drop));
2787 $builder->getActionBuilder($window)->clearAll();
2791 $actions = $builder->generateActions();
2792 if(count($actions) !== 0){
2793 $transaction =
new InventoryTransaction($this, $actions);
2795 $transaction->execute();
2796 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2797 }
catch(TransactionCancelledException){
2798 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2799 foreach($windowsToClear as $window){
2800 $window->getInventory()->clearAll();
2802 }
catch(TransactionValidationException $e){
2803 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2812 return $this->currentWindow;
2819 if($window === $this->currentWindow){
2822 if($window->getViewer() !== $this){
2823 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2827 if($ev->isCancelled()){
2831 $this->removeCurrentWindow();
2833 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2834 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2836 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2837 $inventoryManager->onCurrentWindowChange($window);
2839 $this->currentWindow = $window;
2843 public function removeCurrentWindow() : void{
2844 $this->doCloseInventory();
2845 if($this->currentWindow !==
null){
2846 $currentWindow = $this->currentWindow;
2847 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2848 $this->currentWindow->onClose();
2849 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2850 $inventoryManager->onCurrentWindowRemove();
2852 $this->currentWindow =
null;
2853 (
new InventoryCloseEvent($currentWindow, $this))->call();
2861 foreach($windows as $window){
2863 $this->permanentWindows[spl_object_id($window)] = $window;
2867 protected function removePermanentWindows() : void{
2868 foreach($this->permanentWindows as $window){
2871 $this->permanentWindows = [];
2879 return $this->permanentWindows;
2886 $block = $this->getWorld()->getBlock($position);
2888 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2889 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2891 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2895 use ChunkListenerNoOpTrait {
2896 onChunkChanged as
private;
2897 onChunkUnloaded as
private;
2901 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2902 if($status === UsedChunkStatus::SENT){
2903 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2904 $this->nextChunkOrderRun = 0;
2909 if($this->isUsingChunk($chunkX, $chunkZ)){
2910 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2911 $this->unloadChunk($chunkX, $chunkZ);