174 use PermissibleDelegateTrait;
176 private const MOVES_PER_TICK = 2;
177 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
180 private const MAX_CHAT_CHAR_LENGTH = 512;
186 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
187 private const MAX_REACH_DISTANCE_CREATIVE = 13;
188 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
189 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
191 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
193 public const TAG_FIRST_PLAYED =
"firstPlayed";
194 public const TAG_LAST_PLAYED =
"lastPlayed";
195 private const TAG_GAME_MODE =
"playerGameType";
196 private const TAG_SPAWN_WORLD =
"SpawnLevel";
197 private const TAG_SPAWN_X =
"SpawnX";
198 private const TAG_SPAWN_Y =
"SpawnY";
199 private const TAG_SPAWN_Z =
"SpawnZ";
200 private const TAG_DEATH_WORLD =
"DeathLevel";
201 private const TAG_DEATH_X =
"DeathPositionX";
202 private const TAG_DEATH_Y =
"DeathPositionY";
203 private const TAG_DEATH_Z =
"DeathPositionZ";
204 public const TAG_LEVEL =
"Level";
205 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
215 $lname = strtolower($name);
216 $len = strlen($name);
217 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
222 public bool $spawned =
false;
224 protected string $username;
225 protected string $displayName;
226 protected string $xuid =
"";
227 protected bool $authenticated;
230 protected ?Inventory $currentWindow =
null;
232 protected array $permanentWindows = [];
233 protected PlayerCursorInventory $cursorInventory;
234 protected PlayerCraftingInventory $craftingGrid;
235 protected CreativeInventory $creativeInventory;
237 protected int $messageCounter = 2;
239 protected DateTimeImmutable $firstPlayed;
240 protected DateTimeImmutable $lastPlayed;
241 protected GameMode $gamemode;
247 protected array $usedChunks = [];
252 private array $activeChunkGenerationRequests = [];
257 protected array $loadQueue = [];
258 protected int $nextChunkOrderRun = 5;
261 private array $tickingChunks = [];
263 protected int $viewDistance = -1;
264 protected int $spawnThreshold;
265 protected int $spawnChunkLoadCount = 0;
266 protected int $chunksPerTick;
267 protected ChunkSelector $chunkSelector;
268 protected ChunkLoader $chunkLoader;
269 protected ChunkTicker $chunkTicker;
272 protected array $hiddenPlayers = [];
274 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
275 protected ?
float $lastMovementProcess =
null;
277 protected int $inAirTicks = 0;
279 protected float $stepHeight = 0.6;
281 protected ?Vector3 $sleeping =
null;
282 private ?
Position $spawnPosition =
null;
284 private bool $respawnLocked =
false;
286 private ?
Position $deathPosition =
null;
289 protected bool $autoJump =
true;
290 protected bool $allowFlight =
false;
291 protected bool $blockCollision =
true;
292 protected bool $flying =
false;
294 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
297 protected ?
int $lineHeight =
null;
298 protected string $locale =
"en_US";
300 protected int $startAction = -1;
306 protected array $usedItemsCooldown = [];
308 private int $lastEmoteTick = 0;
310 protected int $formIdCounter = 0;
312 protected array $forms = [];
314 protected \Logger $logger;
319 $username = TextFormat::clean($playerInfo->getUsername());
320 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
323 $this->networkSession = $session;
324 $this->playerInfo = $playerInfo;
325 $this->authenticated = $authenticated;
327 $this->username = $username;
328 $this->displayName = $this->username;
329 $this->locale = $this->playerInfo->getLocale();
331 $this->uuid = $this->playerInfo->getUuid();
332 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
334 $this->creativeInventory = CreativeInventory::getInstance();
336 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
337 if($this->
server->isOp($this->username)){
338 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
341 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
342 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
345 $this->chunkLoader =
new class implements
ChunkLoader{};
347 $world = $spawnLocation->
getWorld();
349 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
350 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
351 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
352 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
353 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
355 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
359 $this->setNameTag($this->username);
362 private function callDummyItemHeldEvent() : void{
363 $slot = $this->inventory->getHeldItemIndex();
372 protected function initEntity(
CompoundTag $nbt) : void{
373 parent::initEntity($nbt);
374 $this->addDefaultWindows();
376 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
377 function(Inventory $unused,
int $slot) :
void{
378 if($slot === $this->inventory->getHeldItemIndex()){
379 $this->setUsingItem(
false);
381 $this->callDummyItemHeldEvent();
385 $this->setUsingItem(
false);
386 $this->callDummyItemHeldEvent();
390 $now = (int) (microtime(
true) * 1000);
391 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
392 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
394 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
395 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
397 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
398 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
400 $this->internalSetGameMode($this->
server->getGamemode());
403 $this->keepMovement =
true;
405 $this->setNameTagVisible();
406 $this->setNameTagAlwaysVisible();
407 $this->setCanClimb();
409 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
410 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
412 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
413 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
417 public function getLeaveMessage() : Translatable|string{
419 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
425 public function isAuthenticated() : bool{
426 return $this->authenticated;
451 return parent::getUniqueId();
458 return $this->firstPlayed;
465 return $this->lastPlayed;
468 public function hasPlayedBefore() : bool{
469 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
482 if($this->allowFlight !== $value){
483 $this->allowFlight = $value;
484 $this->getNetworkSession()->syncAbilities($this);
495 return $this->allowFlight;
507 if($this->blockCollision !== $value){
508 $this->blockCollision = $value;
509 $this->getNetworkSession()->syncAbilities($this);
518 return $this->blockCollision;
521 public function setFlying(
bool $value) : void{
522 if($this->flying !== $value){
523 $this->flying = $value;
524 $this->resetFallDistance();
525 $this->getNetworkSession()->syncAbilities($this);
529 public function isFlying() : bool{
530 return $this->flying;
547 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
548 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
549 $this->getNetworkSession()->syncAbilities($this);
565 return $this->flightSpeedMultiplier;
568 public function setAutoJump(
bool $value) : void{
569 if($this->autoJump !== $value){
570 $this->autoJump = $value;
571 $this->getNetworkSession()->syncAdventureSettings();
575 public function hasAutoJump() : bool{
576 return $this->autoJump;
579 public function spawnTo(Player $player) : void{
580 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
581 parent::spawnTo($player);
585 public function getServer() : Server{
590 return $this->lineHeight ?? 7;
594 if($height !== null && $height < 1){
595 throw new \InvalidArgumentException(
"Line height must be at least 1");
597 $this->lineHeight = $height;
600 public function canSee(
Player $player) : bool{
601 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
604 public function hidePlayer(Player $player) : void{
605 if($player === $this){
608 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
609 $player->despawnFrom($this);
612 public function showPlayer(Player $player) : void{
613 if($player === $this){
616 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
617 if($player->isOnline()){
618 $player->spawnTo($this);
622 public function canCollideWith(Entity $entity) : bool{
626 public function canBeCollidedWith() : bool{
627 return !$this->isSpectator() && parent::canBeCollidedWith();
630 public function resetFallDistance() : void{
631 parent::resetFallDistance();
632 $this->inAirTicks = 0;
635 public function getViewDistance() : int{
636 return $this->viewDistance;
639 public function setViewDistance(
int $distance) : void{
640 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
642 if($newViewDistance !== $this->viewDistance){
643 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
647 $this->viewDistance = $newViewDistance;
649 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
651 $this->nextChunkOrderRun = 0;
653 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
655 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
658 public function isOnline() : bool{
659 return $this->isConnected();
662 public function isConnected() : bool{
663 return $this->networkSession !== null && $this->networkSession->isConnected();
666 public function getNetworkSession() : NetworkSession{
667 if($this->networkSession === null){
668 throw new \LogicException(
"Player is not connected");
670 return $this->networkSession;
677 return $this->username;
684 return $this->displayName;
687 public function setDisplayName(
string $name) : void{
691 $this->displayName = $ev->getNewName();
702 return $this->locale;
705 public function getLanguage() :
Language{
706 return $this->
server->getLanguage();
713 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
717 if($ev->isCancelled()){
718 $this->sendSkin([$this]);
722 $this->setSkin($ev->getNewSkin());
723 $this->sendSkin($this->server->getOnlinePlayers());
732 public function sendSkin(?array $targets =
null) : void{
733 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
740 return $this->startAction > -1;
743 public function setUsingItem(
bool $value) : void{
744 $this->startAction = $value ? $this->
server->getTick() : -1;
745 $this->networkPropertiesDirty =
true;
753 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
760 $this->checkItemCooldowns();
761 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
768 $this->checkItemCooldowns();
769 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
776 $ticks = $ticks ?? $item->getCooldownTicks();
778 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
779 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
783 protected function checkItemCooldowns() : void{
784 $serverTick = $this->
server->getTick();
785 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
786 if($cooldownUntil <= $serverTick){
787 unset($this->usedItemsCooldown[$itemId]);
792 protected function setPosition(Vector3 $pos) : bool{
793 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
794 if(parent::setPosition($pos)){
795 $newWorld = $this->getWorld();
796 if($oldWorld !== $newWorld){
797 if($oldWorld !==
null){
798 foreach($this->usedChunks as $index => $status){
799 World::getXZ($index, $X, $Z);
800 $this->unloadChunk($X, $Z, $oldWorld);
804 $this->usedChunks = [];
805 $this->loadQueue = [];
806 $this->getNetworkSession()->onEnterWorld();
815 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
816 $world = $world ?? $this->getWorld();
817 $index = World::chunkHash($x, $z);
818 if(isset($this->usedChunks[$index])){
819 foreach($world->getChunkEntities($x, $z) as $entity){
820 if($entity !== $this){
821 $entity->despawnFrom($this);
824 $this->getNetworkSession()->stopUsingChunk($x, $z);
825 unset($this->usedChunks[$index]);
826 unset($this->activeChunkGenerationRequests[$index]);
828 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
829 $world->unregisterChunkListener($this, $x, $z);
830 unset($this->loadQueue[$index]);
831 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
832 unset($this->tickingChunks[$index]);
835 protected function spawnEntitiesOnAllChunks() : void{
836 foreach($this->usedChunks as $chunkHash => $status){
837 if($status === UsedChunkStatus::SENT){
838 World::getXZ($chunkHash, $chunkX, $chunkZ);
839 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
844 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
845 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
846 if($entity !== $this && !$entity->isFlaggedForDespawn()){
847 $entity->spawnTo($this);
857 if(!$this->isConnected()){
861 Timings::$playerChunkSend->startTiming();
864 $world = $this->getWorld();
866 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
867 foreach($this->loadQueue as $index => $distance){
868 if($count >= $limit){
874 World::getXZ($index, $X, $Z);
878 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
879 $this->activeChunkGenerationRequests[$index] =
true;
880 unset($this->loadQueue[$index]);
881 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
882 $world->registerChunkListener($this, $X, $Z);
883 if(isset($this->tickingChunks[$index])){
884 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
887 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
888 function() use ($X, $Z, $index, $world) :
void{
889 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
892 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
898 unset($this->activeChunkGenerationRequests[$index]);
899 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
901 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
902 $this->usedChunks[$index] = UsedChunkStatus::SENT;
903 if($this->spawnChunkLoadCount === -1){
904 $this->spawnEntitiesOnChunk($X, $Z);
905 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
906 $this->spawnChunkLoadCount = -1;
908 $this->spawnEntitiesOnAllChunks();
910 $this->getNetworkSession()->notifyTerrainReady();
912 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
915 static function() :
void{
921 Timings::$playerChunkSend->stopTiming();
924 private function recheckBroadcastPermissions() : void{
926 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
927 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
928 ] as $permission => $channel){
929 if($this->hasPermission($permission)){
930 $this->
server->subscribeToBroadcastChannel($channel, $this);
932 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
945 $this->spawned =
true;
946 $this->recheckBroadcastPermissions();
947 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
948 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
949 $this->recheckBroadcastPermissions();
953 $ev =
new PlayerJoinEvent($this,
954 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
957 if($ev->getJoinMessage() !==
""){
958 $this->server->broadcastMessage($ev->getJoinMessage());
961 $this->noDamageTicks = 60;
965 if($this->getHealth() <= 0){
966 $this->logger->debug(
"Quit while dead, forcing respawn");
967 $this->actuallyRespawn();
978 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
979 $world = $this->getWorld();
980 foreach($oldTickingChunks as $hash => $_){
981 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
983 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
984 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
987 foreach($newTickingChunks as $hash => $_){
988 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
990 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
991 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1001 if(!$this->isConnected() || $this->viewDistance === -1){
1005 Timings::$playerChunkOrder->startTiming();
1008 $tickingChunks = [];
1009 $unloadChunks = $this->usedChunks;
1011 $world = $this->getWorld();
1012 $tickingChunkRadius = $world->getChunkTickRadius();
1014 foreach($this->chunkSelector->selectChunks(
1015 $this->server->getAllowedViewDistance($this->viewDistance),
1016 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1017 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1018 ) as $radius => $hash){
1019 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1020 $newOrder[$hash] =
true;
1022 if($radius < $tickingChunkRadius){
1023 $tickingChunks[$hash] =
true;
1025 unset($unloadChunks[$hash]);
1028 foreach($unloadChunks as $index => $status){
1029 World::getXZ($index, $X, $Z);
1030 $this->unloadChunk($X, $Z);
1033 $this->loadQueue = $newOrder;
1035 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1036 $this->tickingChunks = $tickingChunks;
1038 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1039 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1042 Timings::$playerChunkOrder->stopTiming();
1050 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1058 return $this->usedChunks;
1065 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1072 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1073 return $status === UsedChunkStatus::SENT;
1080 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1081 $this->nextChunkOrderRun = PHP_INT_MAX;
1082 $this->orderChunks();
1085 if(count($this->loadQueue) > 0){
1086 $this->requestChunks();
1090 public function getDeathPosition() : ?Position{
1091 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1092 $this->deathPosition =
null;
1094 return $this->deathPosition;
1102 if($pos instanceof
Position && $pos->world !==
null){
1103 $world = $pos->world;
1105 $world = $this->getWorld();
1107 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1109 $this->deathPosition =
null;
1111 $this->networkPropertiesDirty =
true;
1118 if($this->hasValidCustomSpawn()){
1119 return $this->spawnPosition;
1121 $world = $this->
server->getWorldManager()->getDefaultWorld();
1123 return $world->getSpawnLocation();
1127 public function hasValidCustomSpawn() : bool{
1128 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1140 $world = $this->getWorld();
1142 $world = $pos->getWorld();
1144 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1146 $this->spawnPosition =
null;
1148 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1151 public function isSleeping() : bool{
1152 return $this->sleeping !== null;
1155 public function sleepOn(Vector3 $pos) : bool{
1156 $pos = $pos->floor();
1157 $b = $this->getWorld()->getBlock($pos);
1159 $ev =
new PlayerBedEnterEvent($this, $b);
1161 if($ev->isCancelled()){
1165 if($b instanceof Bed){
1167 $this->getWorld()->setBlock($pos, $b);
1170 $this->sleeping = $pos;
1171 $this->networkPropertiesDirty =
true;
1173 $this->setSpawn($pos);
1175 $this->getWorld()->setSleepTicks(60);
1180 public function stopSleep() : void{
1181 if($this->sleeping instanceof Vector3){
1182 $b = $this->getWorld()->getBlock($this->sleeping);
1183 if($b instanceof Bed){
1184 $b->setOccupied(
false);
1185 $this->getWorld()->setBlock($this->sleeping, $b);
1187 (
new PlayerBedLeaveEvent($this, $b))->call();
1189 $this->sleeping =
null;
1190 $this->networkPropertiesDirty =
true;
1192 $this->getWorld()->setSleepTicks(0);
1194 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1198 public function getGamemode() : GameMode{
1199 return $this->gamemode;
1202 protected function internalSetGameMode(GameMode $gameMode) : void{
1203 $this->gamemode = $gameMode;
1205 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1206 $this->hungerManager->setEnabled($this->isSurvival());
1208 if($this->isSpectator()){
1209 $this->setFlying(
true);
1210 $this->setHasBlockCollision(
false);
1212 $this->onGround =
false;
1216 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1218 if($this->isSurvival()){
1219 $this->setFlying(
false);
1221 $this->setHasBlockCollision(
true);
1222 $this->setSilent(
false);
1223 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1231 if($this->gamemode === $gm){
1237 if($ev->isCancelled()){
1241 $this->internalSetGameMode($gm);
1243 if($this->isSpectator()){
1244 $this->despawnFromAll();
1246 $this->spawnToAll();
1249 $this->getNetworkSession()->syncGameMode($this->gamemode);
1260 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1270 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1280 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1283 public function isSpectator() : bool{
1284 return $this->gamemode === GameMode::SPECTATOR;
1291 return $this->gamemode !== GameMode::CREATIVE;
1295 if($this->hasFiniteResources()){
1296 return parent::getDrops();
1303 if($this->hasFiniteResources()){
1304 return parent::getXpDropAmount();
1310 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1311 if($this->gamemode === GameMode::SPECTATOR){
1312 $this->onGround =
false;
1314 $bb = clone $this->boundingBox;
1315 $bb->minY = $this->location->y - 0.2;
1316 $bb->maxY = $this->location->y + 0.2;
1320 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1322 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1330 protected function checkNearEntities() : void{
1331 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1332 $entity->scheduleUpdate();
1334 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1338 $entity->onCollideWithPlayer($this);
1342 public function getInAirTicks() : int{
1343 return $this->inAirTicks;
1355 Timings::$playerMove->startTiming();
1357 $this->actuallyHandleMovement($newPos);
1359 Timings::$playerMove->stopTiming();
1363 private function actuallyHandleMovement(Vector3 $newPos) : void{
1364 $this->moveRateLimit--;
1365 if($this->moveRateLimit < 0){
1369 $oldPos = $this->location;
1370 $distanceSquared = $newPos->distanceSquared($oldPos);
1374 if($distanceSquared > 225){
1386 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1387 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1389 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1391 $this->nextChunkOrderRun = 0;
1394 if(!$revert && $distanceSquared !== 0.0){
1395 $dx = $newPos->x - $oldPos->x;
1396 $dy = $newPos->y - $oldPos->y;
1397 $dz = $newPos->z - $oldPos->z;
1399 $this->move($dx, $dy, $dz);
1403 $this->revertMovement($oldPos);
1411 $now = microtime(true);
1412 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1413 $exceededRateLimit = $this->moveRateLimit < 0;
1414 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1415 $this->lastMovementProcess = $now;
1417 $from = clone $this->lastLocation;
1418 $to = clone $this->location;
1420 $delta = $to->distanceSquared($from);
1421 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1423 if($delta > 0.0001 || $deltaAngle > 1.0){
1424 if(PlayerMoveEvent::hasHandlers()){
1429 if($ev->isCancelled()){
1430 $this->revertMovement($from);
1434 if($to->distanceSquared($ev->getTo()) > 0.01){
1435 $this->teleport($ev->getTo());
1440 $this->lastLocation = $to;
1441 $this->broadcastMovement();
1443 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1444 if($horizontalDistanceTravelled > 0){
1446 if($this->isSprinting()){
1447 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1449 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1452 if($this->nextChunkOrderRun > 20){
1453 $this->nextChunkOrderRun = 20;
1458 if($exceededRateLimit){
1459 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1460 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1464 protected function revertMovement(Location $from) : void{
1465 $this->setPosition($from);
1466 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1469 protected function calculateFallDamage(
float $fallDistance) : float{
1470 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1478 public function setMotion(
Vector3 $motion) : bool{
1479 if(parent::setMotion($motion)){
1480 $this->broadcastMotion();
1481 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1488 protected function updateMovement(
bool $teleport =
false) : void{
1492 protected function tryChangeMovement() : void{
1496 public function onUpdate(int $currentTick) : bool{
1497 $tickDiff = $currentTick - $this->lastUpdate;
1503 $this->messageCounter = 2;
1505 $this->lastUpdate = $currentTick;
1507 if($this->justCreated){
1508 $this->onFirstUpdate($currentTick);
1511 if(!$this->isAlive() && $this->spawned){
1512 $this->onDeathUpdate($tickDiff);
1516 $this->timings->startTiming();
1519 Timings::$playerMove->startTiming();
1520 $this->processMostRecentMovements();
1521 $this->motion = Vector3::zero();
1522 if($this->onGround){
1523 $this->inAirTicks = 0;
1525 $this->inAirTicks += $tickDiff;
1527 Timings::$playerMove->stopTiming();
1529 Timings::$entityBaseTick->startTiming();
1530 $this->entityBaseTick($tickDiff);
1531 Timings::$entityBaseTick->stopTiming();
1533 if($this->isCreative() && $this->fireTicks > 1){
1534 $this->fireTicks = 1;
1537 if(!$this->isSpectator() && $this->isAlive()){
1538 Timings::$playerCheckNearEntities->startTiming();
1539 $this->checkNearEntities();
1540 Timings::$playerCheckNearEntities->stopTiming();
1543 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1544 $this->blockBreakHandler =
null;
1548 $this->timings->stopTiming();
1554 return $this->isCreative() || parent::canEat();
1558 return $this->isCreative() || parent::canBreathe();
1567 $eyePos = $this->getEyePos();
1568 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1572 $dV = $this->getDirectionVector();
1573 $eyeDot = $dV->dot($eyePos);
1574 $targetDot = $dV->dot($pos);
1575 return ($targetDot - $eyeDot) >= -$maxDiff;
1582 public function chat(
string $message) : bool{
1583 $this->removeCurrentWindow();
1585 if($this->messageCounter <= 0){
1591 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1592 if(strlen($message) > $maxTotalLength){
1596 $message = TextFormat::clean($message,
false);
1597 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1598 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1599 if(str_starts_with($messagePart,
'./')){
1600 $messagePart = substr($messagePart, 1);
1603 if(str_starts_with($messagePart,
"/")){
1604 Timings::$playerCommand->startTiming();
1605 $this->server->dispatchCommand($this, substr($messagePart, 1));
1606 Timings::$playerCommand->stopTiming();
1608 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1610 if(!$ev->isCancelled()){
1611 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1620 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1621 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1624 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1628 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1630 if($ev->isCancelled()){
1634 $this->inventory->setHeldItemIndex($hotbarSlot);
1635 $this->setUsingItem(
false);
1643 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1644 $heldItemChanged = false;
1646 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1649 $newReplica = clone $oldHeldItem;
1650 $newReplica->setCount($newHeldItem->getCount());
1651 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1652 $newReplica->setDamage($newHeldItem->getDamage());
1654 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1656 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1657 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1658 $this->broadcastSound(
new ItemBreakSound());
1660 $this->inventory->setItemInHand($newHeldItem);
1661 $heldItemChanged =
true;
1665 if(!$heldItemChanged){
1666 $newHeldItem = $oldHeldItem;
1669 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1670 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1672 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1674 $ev =
new PlayerDropItemEvent($this, $drop);
1675 if($this->isSpectator()){
1679 if(!$ev->isCancelled()){
1680 $this->dropItem($drop);
1691 $directionVector = $this->getDirectionVector();
1692 $item = $this->inventory->getItemInHand();
1693 $oldItem = clone $item;
1696 if($this->hasItemCooldown($item) || $this->isSpectator()){
1702 if($ev->isCancelled()){
1706 $returnedItems = [];
1707 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1708 if($result === ItemUseResult::FAIL){
1712 $this->resetItemCooldown($oldItem);
1713 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1715 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1726 $slot = $this->inventory->getItemInHand();
1728 $oldItem = clone $slot;
1731 if($this->hasItemCooldown($slot)){
1736 if($ev->isCancelled() || !$this->consumeObject($slot)){
1740 $this->setUsingItem(
false);
1741 $this->resetItemCooldown($oldItem);
1744 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1759 $item = $this->inventory->getItemInHand();
1760 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1764 $oldItem = clone $item;
1766 $returnedItems = [];
1767 $result = $item->onReleaseUsing($this, $returnedItems);
1768 if($result === ItemUseResult::SUCCESS){
1769 $this->resetItemCooldown($oldItem);
1770 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1776 $this->setUsingItem(
false);
1780 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1781 $block = $this->getWorld()->getBlock($pos);
1782 if($block instanceof UnknownBlock){
1786 $item = $block->getPickedItem($addTileNBT);
1788 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1789 $existingSlot = $this->inventory->first($item);
1790 if($existingSlot === -1 && $this->hasFiniteResources()){
1795 if(!$ev->isCancelled()){
1796 $this->equipOrAddPickedItem($existingSlot, $item);
1802 public function pickEntity(
int $entityId) : bool{
1803 $entity = $this->getWorld()->getEntity($entityId);
1804 if($entity ===
null){
1808 $item = $entity->getPickedItem();
1813 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1814 $existingSlot = $this->inventory->first($item);
1815 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1820 if(!$ev->isCancelled()){
1821 $this->equipOrAddPickedItem($existingSlot, $item);
1827 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1828 if($existingSlot !== -1){
1829 if($existingSlot < $this->inventory->getHotbarSize()){
1830 $this->inventory->setHeldItemIndex($existingSlot);
1832 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1835 $firstEmpty = $this->inventory->firstEmpty();
1836 if($firstEmpty === -1){
1837 $this->inventory->setItemInHand($item);
1838 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1839 $this->inventory->setItem($firstEmpty, $item);
1840 $this->inventory->setHeldItemIndex($firstEmpty);
1842 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1843 $this->inventory->setItemInHand($item);
1854 if($pos->distanceSquared($this->location) > 10000){
1858 $target = $this->getWorld()->getBlock($pos);
1860 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1861 if($this->isSpectator()){
1865 if($ev->isCancelled()){
1868 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1869 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1873 $block = $target->getSide($face);
1874 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1875 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1876 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1880 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1881 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1887 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1888 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1889 $this->blockBreakHandler->setTargetedFace($face);
1893 public function stopBreakBlock(Vector3 $pos) : void{
1894 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1895 $this->blockBreakHandler =
null;
1905 $this->removeCurrentWindow();
1907 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1908 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1909 $this->stopBreakBlock($pos);
1910 $item = $this->inventory->getItemInHand();
1911 $oldItem = clone $item;
1912 $returnedItems = [];
1913 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1914 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1915 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1919 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1931 $this->setUsingItem(false);
1933 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1934 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1935 $item = $this->inventory->getItemInHand();
1936 $oldItem = clone $item;
1937 $returnedItems = [];
1938 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1939 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1943 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1956 if(!$entity->isAlive()){
1960 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1964 $heldItem = $this->inventory->getItemInHand();
1965 $oldItem = clone $heldItem;
1967 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1968 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1969 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1971 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1975 $meleeEnchantmentDamage = 0;
1977 $meleeEnchantments = [];
1978 foreach($heldItem->getEnchantments() as $enchantment){
1979 $type = $enchantment->getType();
1980 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1981 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1982 $meleeEnchantments[] = $enchantment;
1985 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1987 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1988 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1991 $entity->attack($ev);
1992 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1994 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1995 if($ev->isCancelled()){
1996 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1999 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2001 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2002 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2005 foreach($meleeEnchantments as $enchantment){
2006 $type = $enchantment->getType();
2007 assert($type instanceof MeleeWeaponEnchantment);
2008 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2011 if($this->isAlive()){
2014 $returnedItems = [];
2015 $heldItem->onAttackEntity($entity, $returnedItems);
2016 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2018 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2031 if(!$ev->isCancelled()){
2032 $this->broadcastSound(new EntityAttackNoDamageSound());
2033 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2043 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2044 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2050 $item = $this->inventory->getItemInHand();
2051 $oldItem = clone $item;
2052 if(!$ev->isCancelled()){
2053 if($item->onInteractEntity($this, $entity, $clickPos)){
2054 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2055 if($item instanceof Durable && $item->isBroken()){
2056 $this->broadcastSound(new ItemBreakSound());
2058 $this->inventory->setItemInHand($item);
2061 return $entity->
onInteract($this, $clickPos);
2066 public function toggleSprint(
bool $sprint) : bool{
2067 if($sprint === $this->sprinting){
2070 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2072 if($ev->isCancelled()){
2075 $this->setSprinting($sprint);
2079 public function toggleSneak(
bool $sneak) : bool{
2080 if($sneak === $this->sneaking){
2083 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2085 if($ev->isCancelled()){
2088 $this->setSneaking($sneak);
2092 public function toggleFlight(
bool $fly) : bool{
2093 if($fly === $this->flying){
2096 $ev =
new PlayerToggleFlightEvent($this, $fly);
2097 if(!$this->allowFlight){
2101 if($ev->isCancelled()){
2104 $this->setFlying($fly);
2108 public function toggleGlide(
bool $glide) : bool{
2109 if($glide === $this->gliding){
2112 $ev =
new PlayerToggleGlideEvent($this, $glide);
2114 if($ev->isCancelled()){
2117 $this->setGliding($glide);
2121 public function toggleSwim(
bool $swim) : bool{
2122 if($swim === $this->swimming){
2125 $ev =
new PlayerToggleSwimEvent($this, $swim);
2127 if($ev->isCancelled()){
2130 $this->setSwimming($swim);
2134 public function emote(
string $emoteId) : void{
2135 $currentTick = $this->
server->getTick();
2136 if($currentTick - $this->lastEmoteTick > 5){
2137 $this->lastEmoteTick = $currentTick;
2138 $event =
new PlayerEmoteEvent($this, $emoteId);
2140 if(!$event->isCancelled()){
2141 $emoteId = $event->getEmoteId();
2142 parent::emote($emoteId);
2152 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2162 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2163 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2164 if($subtitle !==
""){
2165 $this->sendSubTitle($subtitle);
2167 $this->getNetworkSession()->onTitle($title);
2174 $this->getNetworkSession()->onSubTitle($subtitle);
2181 $this->getNetworkSession()->onActionBar($message);
2188 $this->getNetworkSession()->onClearTitle();
2195 $this->getNetworkSession()->onResetTitleOptions();
2206 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2207 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2215 $this->getNetworkSession()->onChatMessage($message);
2218 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2219 $this->getNetworkSession()->onJukeboxPopup($message);
2228 $this->getNetworkSession()->onPopup($message);
2231 public function sendTip(
string $message) : void{
2232 $this->getNetworkSession()->onTip($message);
2239 $this->getNetworkSession()->onToastNotification($title, $body);
2248 $id = $this->formIdCounter++;
2249 if($this->getNetworkSession()->onFormSent($id, $form)){
2250 $this->forms[$id] = $form;
2254 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2255 if(!isset($this->forms[$formId])){
2256 $this->logger->debug(
"Got unexpected response for form $formId");
2261 $this->forms[$formId]->handleResponse($this, $responseData);
2262 }
catch(FormValidationException $e){
2263 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2264 $this->logger->logException($e);
2266 unset($this->forms[$formId]);
2276 $this->getNetworkSession()->onCloseAllForms();
2291 if(!$ev->isCancelled()){
2292 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2307 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2309 if(!$ev->isCancelled()){
2310 $reason = $ev->getDisconnectReason();
2312 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2314 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2315 if($disconnectScreenMessage ===
""){
2316 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2318 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2340 if(!$this->isConnected()){
2344 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2345 $this->onPostDisconnect($reason, $quitMessage);
2356 if($this->isConnected()){
2357 throw new \LogicException(
"Player is still connected");
2361 $this->server->unsubscribeFromAllBroadcastChannels($this);
2363 $this->removeCurrentWindow();
2365 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2367 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2368 $this->server->broadcastMessage($quitMessage);
2372 $this->spawned =
false;
2375 $this->blockBreakHandler =
null;
2376 $this->despawnFromAll();
2378 $this->
server->removeOnlinePlayer($this);
2380 foreach($this->
server->getOnlinePlayers() as $player){
2381 if(!$player->canSee($this)){
2382 $player->showPlayer($this);
2385 $this->hiddenPlayers = [];
2387 if($this->location->isValid()){
2388 foreach($this->usedChunks as $index => $status){
2389 World::getXZ($index, $chunkX, $chunkZ);
2390 $this->unloadChunk($chunkX, $chunkZ);
2393 if(count($this->usedChunks) !== 0){
2394 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2396 $this->loadQueue = [];
2398 $this->removeCurrentWindow();
2399 $this->removePermanentInventories();
2401 $this->perm->getPermissionRecalculationCallbacks()->clear();
2403 $this->flagForDespawn();
2407 $this->disconnect(
"Player destroyed");
2408 $this->cursorInventory->removeAllViewers();
2409 $this->craftingGrid->removeAllViewers();
2410 parent::onDispose();
2414 $this->networkSession = null;
2415 unset($this->cursorInventory);
2416 unset($this->craftingGrid);
2417 $this->spawnPosition =
null;
2418 $this->deathPosition =
null;
2419 $this->blockBreakHandler =
null;
2420 parent::destroyCycles();
2430 public function __destruct(){
2431 parent::__destruct();
2432 $this->logger->debug(
"Destroyed by garbage collector");
2440 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2444 $nbt = $this->saveNBT();
2446 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2448 if($this->location->isValid()){
2449 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2452 if($this->hasValidCustomSpawn()){
2453 $spawn = $this->getSpawn();
2454 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2455 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2456 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2457 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2460 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2461 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2462 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2463 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2464 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2467 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2468 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2469 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2478 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2484 $this->removeCurrentWindow();
2486 $this->setDeathPosition($this->getPosition());
2488 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2491 if(!$ev->getKeepInventory()){
2492 foreach($ev->getDrops() as $item){
2493 $this->getWorld()->dropItem($this->location, $item);
2496 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2497 $this->inventory->setHeldItemIndex(0);
2498 $clearInventory($this->inventory);
2499 $clearInventory($this->armorInventory);
2500 $clearInventory($this->offHandInventory);
2503 if(!$ev->getKeepXp()){
2504 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2505 $this->xpManager->setXpAndProgress(0, 0.0);
2508 if($ev->getDeathMessage() !==
""){
2509 $this->server->broadcastMessage($ev->getDeathMessage());
2512 $this->startDeathAnimation();
2514 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2518 parent::onDeathUpdate($tickDiff);
2522 public function respawn() : void{
2523 if($this->
server->isHardcore()){
2524 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2525 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2530 $this->actuallyRespawn();
2533 protected function actuallyRespawn() : void{
2534 if($this->respawnLocked){
2537 $this->respawnLocked =
true;
2539 $this->logger->debug(
"Waiting for safe respawn position to be located");
2540 $spawn = $this->getSpawn();
2541 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2542 function(Position $safeSpawn) :
void{
2543 if(!$this->isConnected()){
2546 $this->logger->debug(
"Respawn position located, completing respawn");
2547 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2548 $spawnPosition = $ev->getRespawnPosition();
2549 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2550 if($spawnBlock instanceof RespawnAnchor){
2551 if($spawnBlock->getCharges() > 0){
2552 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2553 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2555 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2556 if($defaultSpawn !==
null){
2557 $this->setSpawn($defaultSpawn);
2558 $ev->setRespawnPosition($defaultSpawn);
2559 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2565 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2566 $this->teleport($realSpawn);
2568 $this->setSprinting(
false);
2569 $this->setSneaking(
false);
2570 $this->setFlying(
false);
2572 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2573 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2574 $this->deadTicks = 0;
2575 $this->noDamageTicks = 60;
2577 $this->effectManager->clear();
2578 $this->setHealth($this->getMaxHealth());
2580 foreach($this->attributeMap->getAll() as $attr){
2581 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2584 $attr->resetToDefault();
2587 $this->spawnToAll();
2588 $this->scheduleUpdate();
2590 $this->getNetworkSession()->onServerRespawn();
2591 $this->respawnLocked =
false;
2594 if($this->isConnected()){
2595 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2602 parent::applyPostDamageEffects($source);
2604 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2608 if(!$this->isAlive()){
2612 if($this->isCreative()
2613 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2616 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2620 parent::attack($source);
2623 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2624 parent::syncNetworkData($properties);
2626 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2627 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2629 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2630 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2632 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2633 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2635 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2636 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2638 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2639 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2640 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2644 public function sendData(?array $targets, ?array $data =
null) : void{
2645 if($targets === null){
2646 $targets = $this->getViewers();
2649 parent::sendData($targets, $data);
2653 if($this->spawned && $targets === null){
2654 $targets = $this->getViewers();
2657 parent::broadcastAnimation($animation, $targets);
2661 if($this->spawned && $targets === null){
2662 $targets = $this->getViewers();
2665 parent::broadcastSound($sound, $targets);
2671 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2672 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2678 if(parent::teleport($pos, $yaw, $pitch)){
2680 $this->removeCurrentWindow();
2683 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2684 $this->broadcastMovement(
true);
2686 $this->spawnToAll();
2688 $this->resetFallDistance();
2689 $this->nextChunkOrderRun = 0;
2690 if($this->spawnChunkLoadCount !== -1){
2691 $this->spawnChunkLoadCount = 0;
2693 $this->blockBreakHandler =
null;
2697 $this->resetLastMovements();
2705 protected function addDefaultWindows() : void{
2706 $this->cursorInventory = new PlayerCursorInventory($this);
2707 $this->craftingGrid =
new PlayerCraftingInventory($this);
2709 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2714 public function getCursorInventory() : PlayerCursorInventory{
2715 return $this->cursorInventory;
2718 public function getCraftingGrid() : CraftingGrid{
2719 return $this->craftingGrid;
2727 return $this->creativeInventory;
2734 $this->creativeInventory = $inventory;
2735 if($this->spawned && $this->isConnected()){
2736 $this->getNetworkSession()->getInvManager()?->syncCreative();
2744 private function doCloseInventory() : void{
2745 $inventories = [$this->craftingGrid, $this->cursorInventory];
2746 if($this->currentWindow instanceof TemporaryInventory){
2747 $inventories[] = $this->currentWindow;
2750 $builder =
new TransactionBuilder();
2751 foreach($inventories as $inventory){
2752 $contents = $inventory->getContents();
2754 if(count($contents) > 0){
2755 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2756 foreach($drops as $drop){
2757 $builder->addAction(
new DropItemAction($drop));
2760 $builder->getInventory($inventory)->clearAll();
2764 $actions = $builder->generateActions();
2765 if(count($actions) !== 0){
2766 $transaction =
new InventoryTransaction($this, $actions);
2768 $transaction->execute();
2769 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2770 }
catch(TransactionCancelledException){
2771 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2772 foreach($inventories as $inventory){
2773 $inventory->clearAll();
2775 }
catch(TransactionValidationException $e){
2776 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2785 return $this->currentWindow;
2792 if($inventory === $this->currentWindow){
2797 if($ev->isCancelled()){
2801 $this->removeCurrentWindow();
2803 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2804 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2806 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2807 $inventoryManager->onCurrentWindowChange($inventory);
2808 $inventory->onOpen($this);
2809 $this->currentWindow = $inventory;
2813 public function removeCurrentWindow() : void{
2814 $this->doCloseInventory();
2815 if($this->currentWindow !==
null){
2816 $currentWindow = $this->currentWindow;
2817 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2818 $this->currentWindow->onClose($this);
2819 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2820 $inventoryManager->onCurrentWindowRemove();
2822 $this->currentWindow =
null;
2823 (
new InventoryCloseEvent($currentWindow, $this))->call();
2827 protected function addPermanentInventories(Inventory ...$inventories) : void{
2828 foreach($inventories as $inventory){
2829 $inventory->onOpen($this);
2830 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2834 protected function removePermanentInventories() : void{
2835 foreach($this->permanentWindows as $inventory){
2836 $inventory->onClose($this);
2838 $this->permanentWindows = [];
2846 $block = $this->getWorld()->getBlock($position);
2848 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2849 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2851 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2855 use ChunkListenerNoOpTrait {
2856 onChunkChanged as
private;
2857 onChunkUnloaded as
private;
2861 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2862 if($status === UsedChunkStatus::SENT){
2863 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2864 $this->nextChunkOrderRun = 0;
2869 if($this->isUsingChunk($chunkX, $chunkZ)){
2870 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2871 $this->unloadChunk($chunkX, $chunkZ);