176 use PermissibleDelegateTrait;
178 private const MOVES_PER_TICK = 2;
179 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
182 private const MAX_CHAT_CHAR_LENGTH = 512;
188 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
189 private const MAX_REACH_DISTANCE_CREATIVE = 13;
190 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
191 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
193 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
195 public const TAG_FIRST_PLAYED =
"firstPlayed";
196 public const TAG_LAST_PLAYED =
"lastPlayed";
197 private const TAG_GAME_MODE =
"playerGameType";
198 private const TAG_SPAWN_WORLD =
"SpawnLevel";
199 private const TAG_SPAWN_X =
"SpawnX";
200 private const TAG_SPAWN_Y =
"SpawnY";
201 private const TAG_SPAWN_Z =
"SpawnZ";
202 private const TAG_DEATH_WORLD =
"DeathLevel";
203 private const TAG_DEATH_X =
"DeathPositionX";
204 private const TAG_DEATH_Y =
"DeathPositionY";
205 private const TAG_DEATH_Z =
"DeathPositionZ";
206 public const TAG_LEVEL =
"Level";
207 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
217 $lname = strtolower($name);
218 $len = strlen($name);
219 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
224 public bool $spawned =
false;
226 protected string $username;
227 protected string $displayName;
228 protected string $xuid =
"";
229 protected bool $authenticated;
232 protected ?InventoryWindow $currentWindow =
null;
234 protected array $permanentWindows = [];
235 protected Inventory $cursorInventory;
236 protected CraftingGrid $craftingGrid;
237 protected CreativeInventory $creativeInventory;
239 protected int $messageCounter = 2;
241 protected DateTimeImmutable $firstPlayed;
242 protected DateTimeImmutable $lastPlayed;
243 protected GameMode $gamemode;
249 protected array $usedChunks = [];
254 private array $activeChunkGenerationRequests = [];
259 protected array $loadQueue = [];
260 protected int $nextChunkOrderRun = 5;
263 private array $tickingChunks = [];
265 protected int $viewDistance = -1;
266 protected int $spawnThreshold;
267 protected int $spawnChunkLoadCount = 0;
268 protected int $chunksPerTick;
269 protected ChunkSelector $chunkSelector;
270 protected ChunkLoader $chunkLoader;
271 protected ChunkTicker $chunkTicker;
274 protected array $hiddenPlayers = [];
276 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
277 protected ?
float $lastMovementProcess =
null;
279 protected int $inAirTicks = 0;
281 protected float $stepHeight = 0.6;
283 protected ?Vector3 $sleeping =
null;
284 private ?
Position $spawnPosition =
null;
286 private bool $respawnLocked =
false;
288 private ?
Position $deathPosition =
null;
291 protected bool $autoJump =
true;
292 protected bool $allowFlight =
false;
293 protected bool $blockCollision =
true;
294 protected bool $flying =
false;
296 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
299 protected ?
int $lineHeight =
null;
302 protected string $locale =
"en_US";
304 protected int $startAction = -1;
310 protected array $usedItemsCooldown = [];
312 private int $lastEmoteTick = 0;
314 protected int $formIdCounter = 0;
316 protected array $forms = [];
318 protected \Logger $logger;
323 $username = TextFormat::clean($playerInfo->getUsername());
324 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
327 $this->networkSession = $session;
328 $this->playerInfo = $playerInfo;
329 $this->authenticated = $authenticated;
331 $this->username = $username;
332 $this->displayName = $this->username;
333 $this->locale = $this->playerInfo->getLocale();
335 $this->uuid = $this->playerInfo->getUuid();
336 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
338 $this->creativeInventory = CreativeInventory::getInstance();
340 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
341 if($this->
server->isOp($this->username)){
342 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
347 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
348 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
353 $world = $spawnLocation->
getWorld();
355 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
356 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
357 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
358 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
359 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
361 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
365 $this->setNameTag($this->username);
368 private function callDummyItemHeldEvent() : void{
369 $slot = $this->hotbar->getSelectedIndex();
378 protected function initEntity(
CompoundTag $nbt) : void{
379 parent::initEntity($nbt);
380 $this->addDefaultWindows();
382 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
383 function(Inventory $unused,
int $slot) :
void{
384 if($slot === $this->hotbar->getSelectedIndex()){
385 $this->setUsingItem(
false);
387 $this->callDummyItemHeldEvent();
391 $this->setUsingItem(
false);
392 $this->callDummyItemHeldEvent();
396 $now = (int) (microtime(
true) * 1000);
397 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
398 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
400 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
401 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
403 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
404 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
406 $this->internalSetGameMode($this->
server->getGamemode());
409 $this->keepMovement =
true;
411 $this->setNameTagVisible();
412 $this->setNameTagAlwaysVisible();
413 $this->setCanClimb();
415 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
416 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
418 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
419 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
423 public function getLeaveMessage() : Translatable|string{
425 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
431 public function isAuthenticated() : bool{
432 return $this->authenticated;
457 return parent::getUniqueId();
464 return $this->firstPlayed;
471 return $this->lastPlayed;
474 public function hasPlayedBefore() : bool{
475 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
488 if($this->allowFlight !== $value){
489 $this->allowFlight = $value;
490 $this->getNetworkSession()->syncAbilities($this);
501 return $this->allowFlight;
513 if($this->blockCollision !== $value){
514 $this->blockCollision = $value;
515 $this->getNetworkSession()->syncAbilities($this);
524 return $this->blockCollision;
527 public function setFlying(
bool $value) : void{
528 if($this->flying !== $value){
529 $this->flying = $value;
530 $this->resetFallDistance();
531 $this->getNetworkSession()->syncAbilities($this);
535 public function isFlying() : bool{
536 return $this->flying;
553 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
554 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
555 $this->getNetworkSession()->syncAbilities($this);
571 return $this->flightSpeedMultiplier;
574 public function setAutoJump(
bool $value) : void{
575 if($this->autoJump !== $value){
576 $this->autoJump = $value;
577 $this->getNetworkSession()->syncAdventureSettings();
581 public function hasAutoJump() : bool{
582 return $this->autoJump;
585 public function spawnTo(Player $player) : void{
586 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
587 parent::spawnTo($player);
591 public function getServer() : Server{
596 return $this->lineHeight ?? 7;
600 if($height !== null && $height < 1){
601 throw new \InvalidArgumentException(
"Line height must be at least 1");
603 $this->lineHeight = $height;
608 public function canSee(
Player $player) : bool{
609 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
612 public function hidePlayer(
Player $player) : void{
613 if($player === $this){
616 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
617 $player->despawnFrom($this);
620 public function showPlayer(Player $player) : void{
621 if($player === $this){
624 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
625 if($player->isOnline()){
626 $player->spawnTo($this);
630 public function canCollideWith(Entity $entity) : bool{
634 public function canBeCollidedWith() : bool{
635 return !$this->isSpectator() && parent::canBeCollidedWith();
638 public function resetFallDistance() : void{
639 parent::resetFallDistance();
640 $this->inAirTicks = 0;
643 public function getViewDistance() : int{
644 return $this->viewDistance;
647 public function setViewDistance(
int $distance) : void{
648 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
650 if($newViewDistance !== $this->viewDistance){
651 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
655 $this->viewDistance = $newViewDistance;
657 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
659 $this->nextChunkOrderRun = 0;
661 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
663 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
666 public function isOnline() : bool{
667 return $this->isConnected();
670 public function isConnected() : bool{
671 return $this->networkSession !== null && $this->networkSession->isConnected();
674 public function getNetworkSession() : NetworkSession{
675 if($this->networkSession === null){
676 throw new \LogicException(
"Player is not connected");
678 return $this->networkSession;
685 return $this->username;
692 return $this->displayName;
695 public function setDisplayName(
string $name) : void{
699 $this->displayName = $ev->getNewName();
710 return $this->locale;
713 public function getLanguage() :
Language{
714 return $this->
server->getLanguage();
721 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
725 if($ev->isCancelled()){
726 $this->sendSkin([$this]);
730 $this->setSkin($ev->getNewSkin());
731 $this->sendSkin($this->server->getOnlinePlayers());
740 public function sendSkin(?array $targets =
null) : void{
741 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
748 return $this->startAction > -1;
751 public function setUsingItem(
bool $value) : void{
752 $this->startAction = $value ? $this->
server->getTick() : -1;
753 $this->networkPropertiesDirty =
true;
761 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
768 $this->checkItemCooldowns();
769 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
776 $this->checkItemCooldowns();
777 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
784 $ticks = $ticks ?? $item->getCooldownTicks();
786 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
787 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
791 protected function checkItemCooldowns() : void{
792 $serverTick = $this->
server->getTick();
793 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
794 if($cooldownUntil <= $serverTick){
795 unset($this->usedItemsCooldown[$itemId]);
800 protected function setPosition(Vector3 $pos) : bool{
801 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
802 if(parent::setPosition($pos)){
803 $newWorld = $this->getWorld();
804 if($oldWorld !== $newWorld){
805 if($oldWorld !==
null){
806 foreach($this->usedChunks as $index => $status){
807 World::getXZ($index, $X, $Z);
808 $this->unloadChunk($X, $Z, $oldWorld);
812 $this->usedChunks = [];
813 $this->loadQueue = [];
814 $this->getNetworkSession()->onEnterWorld();
823 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
824 $world = $world ?? $this->getWorld();
825 $index = World::chunkHash($x, $z);
826 if(isset($this->usedChunks[$index])){
827 foreach($world->getChunkEntities($x, $z) as $entity){
828 if($entity !== $this){
829 $entity->despawnFrom($this);
832 $this->getNetworkSession()->stopUsingChunk($x, $z);
833 unset($this->usedChunks[$index]);
834 unset($this->activeChunkGenerationRequests[$index]);
836 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
837 $world->unregisterChunkListener($this, $x, $z);
838 unset($this->loadQueue[$index]);
839 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
840 unset($this->tickingChunks[$index]);
843 protected function spawnEntitiesOnAllChunks() : void{
844 foreach($this->usedChunks as $chunkHash => $status){
845 if($status === UsedChunkStatus::SENT){
846 World::getXZ($chunkHash, $chunkX, $chunkZ);
847 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
852 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
853 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
854 if($entity !== $this && !$entity->isFlaggedForDespawn()){
855 $entity->spawnTo($this);
865 if(!$this->isConnected()){
869 Timings::$playerChunkSend->startTiming();
872 $world = $this->getWorld();
874 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
875 foreach($this->loadQueue as $index => $distance){
876 if($count >= $limit){
882 World::getXZ($index, $X, $Z);
886 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
887 $this->activeChunkGenerationRequests[$index] =
true;
888 unset($this->loadQueue[$index]);
889 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
890 $world->registerChunkListener($this, $X, $Z);
891 if(isset($this->tickingChunks[$index])){
892 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
895 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
896 function() use ($X, $Z, $index, $world) :
void{
897 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
900 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
906 unset($this->activeChunkGenerationRequests[$index]);
907 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
909 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
910 $this->usedChunks[$index] = UsedChunkStatus::SENT;
911 if($this->spawnChunkLoadCount === -1){
912 $this->spawnEntitiesOnChunk($X, $Z);
913 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
914 $this->spawnChunkLoadCount = -1;
916 $this->spawnEntitiesOnAllChunks();
918 $this->getNetworkSession()->notifyTerrainReady();
920 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
923 static function() :
void{
929 Timings::$playerChunkSend->stopTiming();
932 private function recheckBroadcastPermissions() : void{
934 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
935 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
936 ] as $permission => $channel){
937 if($this->hasPermission($permission)){
938 $this->
server->subscribeToBroadcastChannel($channel, $this);
940 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
953 $this->spawned =
true;
954 $this->recheckBroadcastPermissions();
955 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
956 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
957 $this->recheckBroadcastPermissions();
961 $ev =
new PlayerJoinEvent($this,
962 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
965 if($ev->getJoinMessage() !==
""){
966 $this->server->broadcastMessage($ev->getJoinMessage());
969 $this->noDamageTicks = 60;
973 if($this->getHealth() <= 0){
974 $this->logger->debug(
"Quit while dead, forcing respawn");
975 $this->actuallyRespawn();
986 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
987 $world = $this->getWorld();
988 foreach($oldTickingChunks as $hash => $_){
989 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
991 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
992 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
995 foreach($newTickingChunks as $hash => $_){
996 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
998 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
999 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1009 if(!$this->isConnected() || $this->viewDistance === -1){
1013 Timings::$playerChunkOrder->startTiming();
1016 $tickingChunks = [];
1017 $unloadChunks = $this->usedChunks;
1019 $world = $this->getWorld();
1020 $tickingChunkRadius = $world->getChunkTickRadius();
1022 foreach($this->chunkSelector->selectChunks(
1023 $this->server->getAllowedViewDistance($this->viewDistance),
1024 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1025 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1026 ) as $radius => $hash){
1027 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1028 $newOrder[$hash] =
true;
1030 if($radius < $tickingChunkRadius){
1031 $tickingChunks[$hash] =
true;
1033 unset($unloadChunks[$hash]);
1036 foreach($unloadChunks as $index => $status){
1037 World::getXZ($index, $X, $Z);
1038 $this->unloadChunk($X, $Z);
1041 $this->loadQueue = $newOrder;
1043 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1044 $this->tickingChunks = $tickingChunks;
1046 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1047 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1050 Timings::$playerChunkOrder->stopTiming();
1058 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1066 return $this->usedChunks;
1073 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1080 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1081 return $status === UsedChunkStatus::SENT;
1088 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1089 $this->nextChunkOrderRun = PHP_INT_MAX;
1090 $this->orderChunks();
1093 if(count($this->loadQueue) > 0){
1094 $this->requestChunks();
1098 public function getDeathPosition() : ?Position{
1099 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1100 $this->deathPosition =
null;
1102 return $this->deathPosition;
1110 if($pos instanceof
Position && $pos->world !==
null){
1111 $world = $pos->world;
1113 $world = $this->getWorld();
1115 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1117 $this->deathPosition =
null;
1119 $this->networkPropertiesDirty =
true;
1126 if($this->hasValidCustomSpawn()){
1127 return $this->spawnPosition;
1129 $world = $this->
server->getWorldManager()->getDefaultWorld();
1131 return $world->getSpawnLocation();
1135 public function hasValidCustomSpawn() : bool{
1136 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1148 $world = $this->getWorld();
1150 $world = $pos->getWorld();
1152 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1154 $this->spawnPosition =
null;
1156 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1159 public function isSleeping() : bool{
1160 return $this->sleeping !== null;
1163 public function sleepOn(Vector3 $pos) : bool{
1164 $pos = $pos->floor();
1165 $b = $this->getWorld()->getBlock($pos);
1167 $ev =
new PlayerBedEnterEvent($this, $b);
1169 if($ev->isCancelled()){
1173 if($b instanceof Bed){
1175 $this->getWorld()->setBlock($pos, $b);
1178 $this->sleeping = $pos;
1179 $this->networkPropertiesDirty =
true;
1181 $this->setSpawn($pos);
1183 $this->getWorld()->setSleepTicks(60);
1188 public function stopSleep() : void{
1189 if($this->sleeping instanceof Vector3){
1190 $b = $this->getWorld()->getBlock($this->sleeping);
1191 if($b instanceof Bed){
1192 $b->setOccupied(
false);
1193 $this->getWorld()->setBlock($this->sleeping, $b);
1195 (
new PlayerBedLeaveEvent($this, $b))->call();
1197 $this->sleeping =
null;
1198 $this->networkPropertiesDirty =
true;
1200 $this->getWorld()->setSleepTicks(0);
1202 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1206 public function getGamemode() : GameMode{
1207 return $this->gamemode;
1210 protected function internalSetGameMode(GameMode $gameMode) : void{
1211 $this->gamemode = $gameMode;
1213 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1214 $this->hungerManager->setEnabled($this->isSurvival());
1216 if($this->isSpectator()){
1217 $this->setFlying(
true);
1218 $this->setHasBlockCollision(
false);
1220 $this->onGround =
false;
1224 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1226 if($this->isSurvival()){
1227 $this->setFlying(
false);
1229 $this->setHasBlockCollision(
true);
1230 $this->setSilent(
false);
1231 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1239 if($this->gamemode === $gm){
1245 if($ev->isCancelled()){
1249 $this->internalSetGameMode($gm);
1251 if($this->isSpectator()){
1252 $this->despawnFromAll();
1254 $this->spawnToAll();
1257 $this->getNetworkSession()->syncGameMode($this->gamemode);
1268 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1278 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1288 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1291 public function isSpectator() : bool{
1292 return $this->gamemode === GameMode::SPECTATOR;
1299 return $this->gamemode !== GameMode::CREATIVE;
1303 if($this->hasFiniteResources()){
1304 return parent::getDrops();
1311 if($this->hasFiniteResources()){
1312 return parent::getXpDropAmount();
1318 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1319 if(!$this->blockCollision){
1320 $this->onGround =
false;
1323 $bb =
new AxisAlignedBB(
1324 $this->boundingBox->minX,
1325 $this->location->y - 0.2,
1326 $this->boundingBox->minZ,
1327 $this->boundingBox->maxX,
1328 $this->location->y + 0.2,
1329 $this->boundingBox->maxZ
1334 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1336 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1344 protected function checkNearEntities() : void{
1345 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1346 $entity->scheduleUpdate();
1348 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1352 $entity->onCollideWithPlayer($this);
1356 public function getInAirTicks() : int{
1357 return $this->inAirTicks;
1369 Timings::$playerMove->startTiming();
1371 $this->actuallyHandleMovement($newPos);
1373 Timings::$playerMove->stopTiming();
1377 private function actuallyHandleMovement(Vector3 $newPos) : void{
1378 $this->moveRateLimit--;
1379 if($this->moveRateLimit < 0){
1383 $oldPos = $this->location;
1384 $distanceSquared = $newPos->distanceSquared($oldPos);
1388 if($distanceSquared > 225){
1400 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1401 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1403 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1405 $this->nextChunkOrderRun = 0;
1408 if(!$revert && $distanceSquared !== 0.0){
1409 $dx = $newPos->x - $oldPos->x;
1410 $dy = $newPos->y - $oldPos->y;
1411 $dz = $newPos->z - $oldPos->z;
1413 $this->move($dx, $dy, $dz);
1417 $this->revertMovement($oldPos);
1425 $now = microtime(true);
1426 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1427 $exceededRateLimit = $this->moveRateLimit < 0;
1428 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1429 $this->lastMovementProcess = $now;
1431 $from = clone $this->lastLocation;
1432 $to = clone $this->location;
1434 $delta = $to->distanceSquared($from);
1435 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1437 if($delta > 0.0001 || $deltaAngle > 1.0){
1438 if(PlayerMoveEvent::hasHandlers()){
1443 if($ev->isCancelled()){
1444 $this->revertMovement($from);
1448 if($to->distanceSquared($ev->getTo()) > 0.01){
1449 $this->teleport($ev->getTo());
1454 $this->lastLocation = $to;
1455 $this->broadcastMovement();
1457 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1458 if($horizontalDistanceTravelled > 0){
1460 if($this->isSprinting()){
1461 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1463 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1466 if($this->nextChunkOrderRun > 20){
1467 $this->nextChunkOrderRun = 20;
1472 if($exceededRateLimit){
1473 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1474 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1478 protected function revertMovement(Location $from) : void{
1479 $this->setPosition($from);
1480 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1483 protected function calculateFallDamage(
float $fallDistance) : float{
1484 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1492 public function setMotion(
Vector3 $motion) : bool{
1493 if(parent::setMotion($motion)){
1494 $this->broadcastMotion();
1495 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1502 protected function updateMovement(
bool $teleport =
false) : void{
1506 protected function tryChangeMovement() : void{
1510 public function onUpdate(int $currentTick) : bool{
1511 $tickDiff = $currentTick - $this->lastUpdate;
1517 $this->messageCounter = 2;
1519 $this->lastUpdate = $currentTick;
1521 if($this->justCreated){
1522 $this->onFirstUpdate($currentTick);
1525 if(!$this->isAlive() && $this->spawned){
1526 $this->onDeathUpdate($tickDiff);
1530 $this->timings->startTiming();
1533 Timings::$playerMove->startTiming();
1534 $this->processMostRecentMovements();
1535 $this->motion = Vector3::zero();
1536 if($this->onGround){
1537 $this->inAirTicks = 0;
1539 $this->inAirTicks += $tickDiff;
1541 Timings::$playerMove->stopTiming();
1543 Timings::$entityBaseTick->startTiming();
1544 $this->entityBaseTick($tickDiff);
1545 Timings::$entityBaseTick->stopTiming();
1547 if($this->isCreative() && $this->fireTicks > 1){
1548 $this->fireTicks = 1;
1551 if(!$this->isSpectator() && $this->isAlive()){
1552 Timings::$playerCheckNearEntities->startTiming();
1553 $this->checkNearEntities();
1554 Timings::$playerCheckNearEntities->stopTiming();
1557 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1558 $this->blockBreakHandler =
null;
1562 $this->timings->stopTiming();
1568 return $this->isCreative() || parent::canEat();
1572 return $this->isCreative() || parent::canBreathe();
1581 $eyePos = $this->getEyePos();
1582 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1586 $dV = $this->getDirectionVector();
1587 $eyeDot = $dV->dot($eyePos);
1588 $targetDot = $dV->dot($pos);
1589 return ($targetDot - $eyeDot) >= -$maxDiff;
1596 public function chat(
string $message) : bool{
1597 $this->removeCurrentWindow();
1599 if($this->messageCounter <= 0){
1605 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1606 if(strlen($message) > $maxTotalLength){
1610 $message = TextFormat::clean($message,
false);
1611 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1612 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1613 if(str_starts_with($messagePart,
'./')){
1614 $messagePart = substr($messagePart, 1);
1617 if(str_starts_with($messagePart,
"/")){
1618 Timings::$playerCommand->startTiming();
1619 $this->server->dispatchCommand($this, substr($messagePart, 1));
1620 Timings::$playerCommand->stopTiming();
1622 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1624 if(!$ev->isCancelled()){
1625 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1634 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1635 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1638 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1642 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1644 if($ev->isCancelled()){
1648 $this->hotbar->setSelectedIndex($hotbarSlot);
1649 $this->setUsingItem(
false);
1657 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1658 $heldItemChanged = false;
1660 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1663 $newReplica = clone $oldHeldItem;
1664 $newReplica->setCount($newHeldItem->getCount());
1665 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1666 $newDamage = $newHeldItem->getDamage();
1667 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1668 $newReplica->setDamage($newDamage);
1671 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1673 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1674 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1675 $this->broadcastSound(
new ItemBreakSound());
1677 $this->setMainHandItem($newHeldItem);
1678 $heldItemChanged =
true;
1682 if(!$heldItemChanged){
1683 $newHeldItem = $oldHeldItem;
1686 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1687 $this->setMainHandItem(array_shift($extraReturnedItems));
1689 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1691 $ev =
new PlayerDropItemEvent($this, $drop);
1692 if($this->isSpectator()){
1696 if(!$ev->isCancelled()){
1697 $this->dropItem($drop);
1708 $directionVector = $this->getDirectionVector();
1709 $item = $this->getMainHandItem();
1710 $oldItem = clone $item;
1713 if($this->hasItemCooldown($item) || $this->isSpectator()){
1719 if($ev->isCancelled()){
1723 $returnedItems = [];
1724 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1725 if($result === ItemUseResult::FAIL){
1729 $this->resetItemCooldown($oldItem);
1730 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1732 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1743 $slot = $this->getMainHandItem();
1745 $oldItem = clone $slot;
1748 if($this->hasItemCooldown($slot)){
1753 if($ev->isCancelled() || !$this->consumeObject($slot)){
1757 $this->setUsingItem(
false);
1758 $this->resetItemCooldown($oldItem);
1761 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1776 $item = $this->getMainHandItem();
1777 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1781 $oldItem = clone $item;
1783 $returnedItems = [];
1784 $result = $item->onReleaseUsing($this, $returnedItems);
1785 if($result === ItemUseResult::SUCCESS){
1786 $this->resetItemCooldown($oldItem);
1787 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1793 $this->setUsingItem(
false);
1797 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1798 $block = $this->getWorld()->getBlock($pos);
1799 if($block instanceof UnknownBlock){
1803 $item = $block->getPickedItem($addTileNBT);
1805 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1806 $existingSlot = $this->inventory->first($item);
1807 if($existingSlot === -1 && $this->hasFiniteResources()){
1812 if(!$ev->isCancelled()){
1813 $this->equipOrAddPickedItem($existingSlot, $item);
1819 public function pickEntity(
int $entityId) : bool{
1820 $entity = $this->getWorld()->getEntity($entityId);
1821 if($entity ===
null){
1825 $item = $entity->getPickedItem();
1830 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1831 $existingSlot = $this->inventory->first($item);
1832 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1837 if(!$ev->isCancelled()){
1838 $this->equipOrAddPickedItem($existingSlot, $item);
1844 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1845 if($existingSlot !== -1){
1846 if($existingSlot < $this->hotbar->getSize()){
1847 $this->hotbar->setSelectedIndex($existingSlot);
1849 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1852 $firstEmpty = $this->inventory->firstEmpty();
1853 if($firstEmpty === -1){
1854 $this->setMainHandItem($item);
1855 }elseif($firstEmpty < $this->hotbar->getSize()){
1856 $this->inventory->setItem($firstEmpty, $item);
1857 $this->hotbar->setSelectedIndex($firstEmpty);
1859 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1860 $this->setMainHandItem($item);
1871 if($pos->distanceSquared($this->location) > 10000){
1875 $target = $this->getWorld()->getBlock($pos);
1877 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1878 if($this->isSpectator()){
1882 if($ev->isCancelled()){
1885 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1886 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1890 $block = $target->getSide($face);
1891 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1892 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1893 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1897 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1898 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1904 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1905 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1906 $this->blockBreakHandler->setTargetedFace($face);
1910 public function stopBreakBlock(Vector3 $pos) : void{
1911 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1912 $this->blockBreakHandler =
null;
1922 $this->removeCurrentWindow();
1924 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1925 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1926 $this->stopBreakBlock($pos);
1927 $item = $this->getMainHandItem();
1928 $oldItem = clone $item;
1929 $returnedItems = [];
1930 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1931 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1932 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1936 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1948 $this->setUsingItem(false);
1950 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1951 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1952 $item = $this->getMainHandItem();
1953 $oldItem = clone $item;
1954 $returnedItems = [];
1955 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1956 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1960 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1973 if(!$entity->isAlive()){
1977 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1981 $heldItem = $this->getMainHandItem();
1982 $oldItem = clone $heldItem;
1984 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1985 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1986 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1988 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1992 $meleeEnchantmentDamage = 0;
1994 $meleeEnchantments = [];
1995 foreach($heldItem->getEnchantments() as $enchantment){
1996 $type = $enchantment->getType();
1997 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1998 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1999 $meleeEnchantments[] = $enchantment;
2002 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2004 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2005 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2008 $entity->attack($ev);
2009 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2011 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2012 if($ev->isCancelled()){
2013 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2016 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2018 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2019 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2022 foreach($meleeEnchantments as $enchantment){
2023 $type = $enchantment->getType();
2024 assert($type instanceof MeleeWeaponEnchantment);
2025 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2028 if($this->isAlive()){
2031 $returnedItems = [];
2032 $heldItem->onAttackEntity($entity, $returnedItems);
2033 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2035 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2048 if(!$ev->isCancelled()){
2049 $this->broadcastSound(new EntityAttackNoDamageSound());
2050 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2060 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2061 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2067 $item = $this->getMainHandItem();
2068 $oldItem = clone $item;
2069 if(!$ev->isCancelled()){
2070 if($item->onInteractEntity($this, $entity, $clickPos)){
2071 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2072 if($item instanceof Durable && $item->isBroken()){
2073 $this->broadcastSound(new ItemBreakSound());
2075 $this->setMainHandItem($item);
2078 return $entity->
onInteract($this, $clickPos);
2083 public function toggleSprint(
bool $sprint) : bool{
2084 if($sprint === $this->sprinting){
2087 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2089 if($ev->isCancelled()){
2092 $this->setSprinting($sprint);
2096 public function toggleSneak(
bool $sneak) : bool{
2097 if($sneak === $this->sneaking){
2100 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2102 if($ev->isCancelled()){
2105 $this->setSneaking($sneak);
2109 public function toggleFlight(
bool $fly) : bool{
2110 if($fly === $this->flying){
2113 $ev =
new PlayerToggleFlightEvent($this, $fly);
2114 if(!$this->allowFlight){
2118 if($ev->isCancelled()){
2121 $this->setFlying($fly);
2125 public function toggleGlide(
bool $glide) : bool{
2126 if($glide === $this->gliding){
2129 $ev =
new PlayerToggleGlideEvent($this, $glide);
2131 if($ev->isCancelled()){
2134 $this->setGliding($glide);
2138 public function toggleSwim(
bool $swim) : bool{
2139 if($swim === $this->swimming){
2142 $ev =
new PlayerToggleSwimEvent($this, $swim);
2144 if($ev->isCancelled()){
2147 $this->setSwimming($swim);
2151 public function emote(
string $emoteId) : void{
2152 $currentTick = $this->
server->getTick();
2153 if($currentTick - $this->lastEmoteTick > 5){
2154 $this->lastEmoteTick = $currentTick;
2155 $event =
new PlayerEmoteEvent($this, $emoteId);
2157 if(!$event->isCancelled()){
2158 $emoteId = $event->getEmoteId();
2159 parent::emote($emoteId);
2169 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2179 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2180 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2181 if($subtitle !==
""){
2182 $this->sendSubTitle($subtitle);
2184 $this->getNetworkSession()->onTitle($title);
2191 $this->getNetworkSession()->onSubTitle($subtitle);
2198 $this->getNetworkSession()->onActionBar($message);
2205 $this->getNetworkSession()->onClearTitle();
2212 $this->getNetworkSession()->onResetTitleOptions();
2223 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2224 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2232 $this->getNetworkSession()->onChatMessage($message);
2235 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2236 $this->getNetworkSession()->onJukeboxPopup($message);
2245 $this->getNetworkSession()->onPopup($message);
2248 public function sendTip(
string $message) : void{
2249 $this->getNetworkSession()->onTip($message);
2256 $this->getNetworkSession()->onToastNotification($title, $body);
2265 $id = $this->formIdCounter++;
2266 if($this->getNetworkSession()->onFormSent($id, $form)){
2267 $this->forms[$id] = $form;
2271 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2272 if(!isset($this->forms[$formId])){
2273 $this->logger->debug(
"Got unexpected response for form $formId");
2278 $this->forms[$formId]->handleResponse($this, $responseData);
2279 }
catch(FormValidationException $e){
2280 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2281 $this->logger->logException($e);
2283 unset($this->forms[$formId]);
2293 $this->getNetworkSession()->onCloseAllForms();
2308 if(!$ev->isCancelled()){
2309 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2324 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2326 if(!$ev->isCancelled()){
2327 $reason = $ev->getDisconnectReason();
2329 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2331 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2332 if($disconnectScreenMessage ===
""){
2333 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2335 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2357 if(!$this->isConnected()){
2361 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2362 $this->onPostDisconnect($reason, $quitMessage);
2373 if($this->isConnected()){
2374 throw new \LogicException(
"Player is still connected");
2378 $this->server->unsubscribeFromAllBroadcastChannels($this);
2380 $this->removeCurrentWindow();
2382 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2384 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2385 $this->server->broadcastMessage($quitMessage);
2389 $this->spawned =
false;
2392 $this->blockBreakHandler =
null;
2393 $this->despawnFromAll();
2395 $this->
server->removeOnlinePlayer($this);
2397 foreach($this->
server->getOnlinePlayers() as $player){
2398 if(!$player->canSee($this)){
2399 $player->showPlayer($this);
2402 $this->hiddenPlayers = [];
2404 if($this->location->isValid()){
2405 foreach($this->usedChunks as $index => $status){
2406 World::getXZ($index, $chunkX, $chunkZ);
2407 $this->unloadChunk($chunkX, $chunkZ);
2410 if(count($this->usedChunks) !== 0){
2411 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2413 $this->loadQueue = [];
2415 $this->removeCurrentWindow();
2416 $this->removePermanentWindows();
2418 $this->perm->getPermissionRecalculationCallbacks()->clear();
2420 $this->flagForDespawn();
2424 $this->disconnect(
"Player destroyed");
2425 $this->cursorInventory->removeAllWindows();
2426 $this->craftingGrid->removeAllWindows();
2427 parent::onDispose();
2431 $this->networkSession = null;
2432 $this->spawnPosition =
null;
2433 $this->deathPosition =
null;
2434 $this->blockBreakHandler =
null;
2435 parent::destroyCycles();
2445 public function __destruct(){
2446 parent::__destruct();
2447 $this->logger->debug(
"Destroyed by garbage collector");
2455 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2459 $nbt = $this->saveNBT();
2461 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2463 if($this->location->isValid()){
2464 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2467 if($this->hasValidCustomSpawn()){
2468 $spawn = $this->getSpawn();
2469 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2470 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2471 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2472 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2475 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2476 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2477 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2478 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2479 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2482 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2483 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2484 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2493 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2499 $this->removeCurrentWindow();
2501 $this->setDeathPosition($this->getPosition());
2503 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2506 if(!$ev->getKeepInventory()){
2507 foreach($ev->getDrops() as $item){
2508 $this->getWorld()->dropItem($this->location, $item);
2511 $this->hotbar->setSelectedIndex(0);
2512 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2513 $clearInventory($this->inventory);
2514 $clearInventory($this->armorInventory);
2515 $clearInventory($this->offHandInventory);
2518 if(!$ev->getKeepXp()){
2519 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2520 $this->xpManager->setXpAndProgress(0, 0.0);
2523 if($ev->getDeathMessage() !==
""){
2524 $this->server->broadcastMessage($ev->getDeathMessage());
2527 $this->startDeathAnimation();
2529 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2533 parent::onDeathUpdate($tickDiff);
2537 public function respawn() : void{
2538 if($this->
server->isHardcore()){
2539 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2540 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2545 $this->actuallyRespawn();
2548 protected function actuallyRespawn() : void{
2549 if($this->respawnLocked){
2552 $this->respawnLocked =
true;
2554 $this->logger->debug(
"Waiting for safe respawn position to be located");
2555 $spawn = $this->getSpawn();
2556 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2557 function(Position $safeSpawn) :
void{
2558 if(!$this->isConnected()){
2561 $this->logger->debug(
"Respawn position located, completing respawn");
2562 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2563 $spawnPosition = $ev->getRespawnPosition();
2564 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2565 if($spawnBlock instanceof RespawnAnchor){
2566 if($spawnBlock->getCharges() > 0){
2567 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2568 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2570 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2571 if($defaultSpawn !==
null){
2572 $this->setSpawn($defaultSpawn);
2573 $ev->setRespawnPosition($defaultSpawn);
2574 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2580 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2581 $this->teleport($realSpawn);
2583 $this->setSprinting(
false);
2584 $this->setSneaking(
false);
2585 $this->setFlying(
false);
2587 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2588 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2589 $this->deadTicks = 0;
2590 $this->noDamageTicks = 60;
2592 $this->effectManager->clear();
2593 $this->setHealth($this->getMaxHealth());
2595 foreach($this->attributeMap->getAll() as $attr){
2596 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2599 $attr->resetToDefault();
2602 $this->spawnToAll();
2603 $this->scheduleUpdate();
2605 $this->getNetworkSession()->onServerRespawn();
2606 $this->respawnLocked =
false;
2609 if($this->isConnected()){
2610 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2617 parent::applyPostDamageEffects($source);
2619 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2623 if(!$this->isAlive()){
2627 if($this->isCreative()
2628 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2631 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2635 parent::attack($source);
2638 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2639 parent::syncNetworkData($properties);
2641 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2642 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2644 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2645 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2647 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2648 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2650 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2651 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2653 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2654 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2655 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2659 public function sendData(?array $targets, ?array $data =
null) : void{
2660 if($targets === null){
2661 $targets = $this->getViewers();
2664 parent::sendData($targets, $data);
2668 if($this->spawned && $targets === null){
2669 $targets = $this->getViewers();
2672 parent::broadcastAnimation($animation, $targets);
2676 if($this->spawned && $targets === null){
2677 $targets = $this->getViewers();
2680 parent::broadcastSound($sound, $targets);
2686 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2687 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2693 if(parent::teleport($pos, $yaw, $pitch)){
2695 $this->removeCurrentWindow();
2698 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2699 $this->broadcastMovement(
true);
2701 $this->spawnToAll();
2703 $this->resetFallDistance();
2704 $this->nextChunkOrderRun = 0;
2705 if($this->spawnChunkLoadCount !== -1){
2706 $this->spawnChunkLoadCount = 0;
2708 $this->blockBreakHandler =
null;
2712 $this->resetLastMovements();
2720 protected function addDefaultWindows() : void{
2721 $this->cursorInventory = new SimpleInventory(1);
2722 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2724 $this->addPermanentWindows([
2725 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2726 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2727 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2728 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2729 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2733 public function getCursorInventory() : Inventory{
2734 return $this->cursorInventory;
2737 public function getCraftingGrid() : CraftingGrid{
2738 return $this->craftingGrid;
2746 return $this->creativeInventory;
2753 $this->creativeInventory = $inventory;
2754 if($this->spawned && $this->isConnected()){
2755 $this->getNetworkSession()->getInvManager()?->syncCreative();
2763 private function doCloseInventory() : void{
2764 $windowsToClear = [];
2765 $mainInventoryWindow =
null;
2766 foreach($this->permanentWindows as $window){
2767 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2768 $windowsToClear[] = $window;
2769 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2770 $mainInventoryWindow = $window;
2773 if($mainInventoryWindow ===
null){
2777 throw new AssumptionFailedError(
"This should never be null");
2780 if($this->currentWindow instanceof TemporaryInventoryWindow){
2781 $windowsToClear[] = $this->currentWindow;
2784 $builder =
new TransactionBuilder();
2785 foreach($windowsToClear as $window){
2786 $contents = $window->getInventory()->getContents();
2788 if(count($contents) > 0){
2789 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2790 foreach($drops as $drop){
2791 $builder->addAction(
new DropItemAction($drop));
2794 $builder->getActionBuilder($window)->clearAll();
2798 $actions = $builder->generateActions();
2799 if(count($actions) !== 0){
2800 $transaction =
new InventoryTransaction($this, $actions);
2802 $transaction->execute();
2803 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2804 }
catch(TransactionCancelledException){
2805 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2806 foreach($windowsToClear as $window){
2807 $window->getInventory()->clearAll();
2809 }
catch(TransactionValidationException $e){
2810 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2819 return $this->currentWindow;
2826 if($window === $this->currentWindow){
2829 if($window->getViewer() !== $this){
2830 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2834 if($ev->isCancelled()){
2838 $this->removeCurrentWindow();
2840 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2841 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2843 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2844 $inventoryManager->onCurrentWindowChange($window);
2846 $this->currentWindow = $window;
2850 public function removeCurrentWindow() : void{
2851 $this->doCloseInventory();
2852 if($this->currentWindow !==
null){
2853 $currentWindow = $this->currentWindow;
2854 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2855 $this->currentWindow->onClose();
2856 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2857 $inventoryManager->onCurrentWindowRemove();
2859 $this->currentWindow =
null;
2860 (
new InventoryCloseEvent($currentWindow, $this))->call();
2868 foreach($windows as $window){
2870 $this->permanentWindows[spl_object_id($window)] = $window;
2874 protected function removePermanentWindows() : void{
2875 foreach($this->permanentWindows as $window){
2878 $this->permanentWindows = [];
2886 return $this->permanentWindows;
2893 $block = $this->getWorld()->getBlock($position);
2895 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2896 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2898 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2902 use ChunkListenerNoOpTrait {
2903 onChunkChanged as
private;
2904 onChunkUnloaded as
private;
2908 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2909 if($status === UsedChunkStatus::SENT){
2910 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2911 $this->nextChunkOrderRun = 0;
2916 if($this->isUsingChunk($chunkX, $chunkZ)){
2917 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2918 $this->unloadChunk($chunkX, $chunkZ);