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;
295 protected bool $sneakPressed =
false;
297 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
300 protected ?
int $lineHeight =
null;
303 protected string $locale =
"en_US";
305 protected int $startAction = -1;
311 protected array $usedItemsCooldown = [];
313 private int $lastEmoteTick = 0;
315 protected int $formIdCounter = 0;
317 protected array $forms = [];
319 protected \Logger $logger;
324 $username = TextFormat::clean($playerInfo->getUsername());
325 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
328 $this->networkSession = $session;
329 $this->playerInfo = $playerInfo;
330 $this->authenticated = $authenticated;
332 $this->username = $username;
333 $this->displayName = $this->username;
334 $this->locale = $this->playerInfo->getLocale();
336 $this->uuid = $this->playerInfo->getUuid();
337 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
339 $this->creativeInventory = CreativeInventory::getInstance();
341 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
342 if($this->
server->isOp($this->username)){
343 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
348 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
349 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
354 $world = $spawnLocation->
getWorld();
356 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
357 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
358 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
359 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
360 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
362 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
366 $this->setNameTag($this->username);
369 private function callDummyItemHeldEvent() : void{
370 $slot = $this->hotbar->getSelectedIndex();
379 protected function initEntity(
CompoundTag $nbt) : void{
380 parent::initEntity($nbt);
381 $this->addDefaultWindows();
383 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
384 function(Inventory $unused,
int $slot) :
void{
385 if($slot === $this->hotbar->getSelectedIndex()){
386 $this->setUsingItem(
false);
388 $this->callDummyItemHeldEvent();
392 $this->setUsingItem(
false);
393 $this->callDummyItemHeldEvent();
397 $now = (int) (microtime(
true) * 1000);
398 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
399 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
401 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
402 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
404 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
405 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
407 $this->internalSetGameMode($this->
server->getGamemode());
410 $this->keepMovement =
true;
412 $this->setNameTagVisible();
413 $this->setNameTagAlwaysVisible();
414 $this->setCanClimb();
416 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
417 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
419 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
420 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
424 public function getLeaveMessage() : Translatable|string{
426 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
432 public function isAuthenticated() : bool{
433 return $this->authenticated;
458 return parent::getUniqueId();
465 return $this->firstPlayed;
472 return $this->lastPlayed;
475 public function hasPlayedBefore() : bool{
476 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
489 if($this->allowFlight !== $value){
490 $this->allowFlight = $value;
491 $this->getNetworkSession()->syncAbilities($this);
502 return $this->allowFlight;
514 if($this->blockCollision !== $value){
515 $this->blockCollision = $value;
516 $this->getNetworkSession()->syncAbilities($this);
525 return $this->blockCollision;
528 public function setFlying(
bool $value) : void{
529 if($this->flying !== $value){
530 $this->flying = $value;
531 $this->resetFallDistance();
532 $this->getNetworkSession()->syncAbilities($this);
536 public function isFlying() : bool{
537 return $this->flying;
554 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
555 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
556 $this->getNetworkSession()->syncAbilities($this);
572 return $this->flightSpeedMultiplier;
575 public function setAutoJump(
bool $value) : void{
576 if($this->autoJump !== $value){
577 $this->autoJump = $value;
578 $this->getNetworkSession()->syncAdventureSettings();
582 public function hasAutoJump() : bool{
583 return $this->autoJump;
586 public function spawnTo(Player $player) : void{
587 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
588 parent::spawnTo($player);
592 public function getServer() : Server{
597 return $this->lineHeight ?? 7;
601 if($height !== null && $height < 1){
602 throw new \InvalidArgumentException(
"Line height must be at least 1");
604 $this->lineHeight = $height;
609 public function canSee(
Player $player) : bool{
610 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
613 public function hidePlayer(
Player $player) : void{
614 if($player === $this){
617 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
618 $player->despawnFrom($this);
621 public function showPlayer(Player $player) : void{
622 if($player === $this){
625 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
626 if($player->isOnline()){
627 $player->spawnTo($this);
631 public function canCollideWith(Entity $entity) : bool{
635 public function canBeCollidedWith() : bool{
636 return !$this->isSpectator() && parent::canBeCollidedWith();
639 public function resetFallDistance() : void{
640 parent::resetFallDistance();
641 $this->inAirTicks = 0;
644 public function getViewDistance() : int{
645 return $this->viewDistance;
648 public function setViewDistance(
int $distance) : void{
649 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
651 if($newViewDistance !== $this->viewDistance){
652 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
656 $this->viewDistance = $newViewDistance;
658 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
660 $this->nextChunkOrderRun = 0;
662 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
664 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
667 public function isOnline() : bool{
668 return $this->isConnected();
671 public function isConnected() : bool{
672 return $this->networkSession !== null && $this->networkSession->isConnected();
675 public function getNetworkSession() : NetworkSession{
676 if($this->networkSession === null){
677 throw new \LogicException(
"Player is not connected");
679 return $this->networkSession;
686 return $this->username;
693 return $this->displayName;
696 public function setDisplayName(
string $name) : void{
700 $this->displayName = $ev->getNewName();
711 return $this->locale;
714 public function getLanguage() :
Language{
715 return $this->
server->getLanguage();
722 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
726 if($ev->isCancelled()){
727 $this->sendSkin([$this]);
731 $this->setSkin($ev->getNewSkin());
732 $this->sendSkin($this->server->getOnlinePlayers());
741 public function sendSkin(?array $targets =
null) : void{
742 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
749 return $this->startAction > -1;
752 public function setUsingItem(
bool $value) : void{
753 $this->startAction = $value ? $this->
server->getTick() : -1;
754 $this->networkPropertiesDirty =
true;
762 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
769 $this->checkItemCooldowns();
770 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
777 $this->checkItemCooldowns();
778 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
785 $ticks = $ticks ?? $item->getCooldownTicks();
787 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
788 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
792 protected function checkItemCooldowns() : void{
793 $serverTick = $this->
server->getTick();
794 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
795 if($cooldownUntil <= $serverTick){
796 unset($this->usedItemsCooldown[$itemId]);
801 protected function setPosition(Vector3 $pos) : bool{
802 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
803 if(parent::setPosition($pos)){
804 $newWorld = $this->getWorld();
805 if($oldWorld !== $newWorld){
806 if($oldWorld !==
null){
807 foreach($this->usedChunks as $index => $status){
808 World::getXZ($index, $X, $Z);
809 $this->unloadChunk($X, $Z, $oldWorld);
813 $this->usedChunks = [];
814 $this->loadQueue = [];
815 $this->getNetworkSession()->onEnterWorld();
824 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
825 $world = $world ?? $this->getWorld();
826 $index = World::chunkHash($x, $z);
827 if(isset($this->usedChunks[$index])){
828 foreach($world->getChunkEntities($x, $z) as $entity){
829 if($entity !== $this){
830 $entity->despawnFrom($this);
833 $this->getNetworkSession()->stopUsingChunk($x, $z);
834 unset($this->usedChunks[$index]);
835 unset($this->activeChunkGenerationRequests[$index]);
837 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
838 $world->unregisterChunkListener($this, $x, $z);
839 unset($this->loadQueue[$index]);
840 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
841 unset($this->tickingChunks[$index]);
844 protected function spawnEntitiesOnAllChunks() : void{
845 foreach($this->usedChunks as $chunkHash => $status){
846 if($status === UsedChunkStatus::SENT){
847 World::getXZ($chunkHash, $chunkX, $chunkZ);
848 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
853 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
854 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
855 if($entity !== $this && !$entity->isFlaggedForDespawn()){
856 $entity->spawnTo($this);
866 if(!$this->isConnected()){
870 Timings::$playerChunkSend->startTiming();
873 $world = $this->getWorld();
875 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
876 foreach($this->loadQueue as $index => $distance){
877 if($count >= $limit){
883 World::getXZ($index, $X, $Z);
887 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
888 $this->activeChunkGenerationRequests[$index] =
true;
889 unset($this->loadQueue[$index]);
890 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
891 $world->registerChunkListener($this, $X, $Z);
892 if(isset($this->tickingChunks[$index])){
893 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
896 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
897 function() use ($X, $Z, $index, $world) :
void{
898 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
901 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
907 unset($this->activeChunkGenerationRequests[$index]);
908 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
910 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
911 $this->usedChunks[$index] = UsedChunkStatus::SENT;
912 if($this->spawnChunkLoadCount === -1){
913 $this->spawnEntitiesOnChunk($X, $Z);
914 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
915 $this->spawnChunkLoadCount = -1;
917 $this->spawnEntitiesOnAllChunks();
919 $this->getNetworkSession()->notifyTerrainReady();
921 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
924 static function() :
void{
930 Timings::$playerChunkSend->stopTiming();
933 private function recheckBroadcastPermissions() : void{
935 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
936 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
937 ] as $permission => $channel){
938 if($this->hasPermission($permission)){
939 $this->
server->subscribeToBroadcastChannel($channel, $this);
941 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
954 $this->spawned =
true;
955 $this->recheckBroadcastPermissions();
956 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
957 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
958 $this->recheckBroadcastPermissions();
962 $ev =
new PlayerJoinEvent($this,
963 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
966 if($ev->getJoinMessage() !==
""){
967 $this->server->broadcastMessage($ev->getJoinMessage());
970 $this->noDamageTicks = 60;
974 if($this->getHealth() <= 0){
975 $this->logger->debug(
"Quit while dead, forcing respawn");
976 $this->actuallyRespawn();
987 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
988 $world = $this->getWorld();
989 foreach($oldTickingChunks as $hash => $_){
990 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
992 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
993 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
996 foreach($newTickingChunks as $hash => $_){
997 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
999 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
1000 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
1010 if(!$this->isConnected() || $this->viewDistance === -1){
1014 Timings::$playerChunkOrder->startTiming();
1017 $tickingChunks = [];
1018 $unloadChunks = $this->usedChunks;
1020 $world = $this->getWorld();
1021 $tickingChunkRadius = $world->getChunkTickRadius();
1023 foreach($this->chunkSelector->selectChunks(
1024 $this->server->getAllowedViewDistance($this->viewDistance),
1025 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1026 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1027 ) as $radius => $hash){
1028 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1029 $newOrder[$hash] =
true;
1031 if($radius < $tickingChunkRadius){
1032 $tickingChunks[$hash] =
true;
1034 unset($unloadChunks[$hash]);
1037 foreach($unloadChunks as $index => $status){
1038 World::getXZ($index, $X, $Z);
1039 $this->unloadChunk($X, $Z);
1042 $this->loadQueue = $newOrder;
1044 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1045 $this->tickingChunks = $tickingChunks;
1047 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1048 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1051 Timings::$playerChunkOrder->stopTiming();
1059 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1067 return $this->usedChunks;
1074 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1081 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1082 return $status === UsedChunkStatus::SENT;
1089 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1090 $this->nextChunkOrderRun = PHP_INT_MAX;
1091 $this->orderChunks();
1094 if(count($this->loadQueue) > 0){
1095 $this->requestChunks();
1099 public function getDeathPosition() : ?Position{
1100 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1101 $this->deathPosition =
null;
1103 return $this->deathPosition;
1111 if($pos instanceof
Position && $pos->world !==
null){
1112 $world = $pos->world;
1114 $world = $this->getWorld();
1116 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1118 $this->deathPosition =
null;
1120 $this->networkPropertiesDirty =
true;
1127 if($this->hasValidCustomSpawn()){
1128 return $this->spawnPosition;
1130 $world = $this->
server->getWorldManager()->getDefaultWorld();
1132 return $world->getSpawnLocation();
1136 public function hasValidCustomSpawn() : bool{
1137 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1149 $world = $this->getWorld();
1151 $world = $pos->getWorld();
1153 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1155 $this->spawnPosition =
null;
1157 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1160 public function isSleeping() : bool{
1161 return $this->sleeping !== null;
1164 public function sleepOn(Vector3 $pos) : bool{
1165 $pos = $pos->floor();
1166 $b = $this->getWorld()->getBlock($pos);
1168 $ev =
new PlayerBedEnterEvent($this, $b);
1170 if($ev->isCancelled()){
1174 if($b instanceof Bed){
1176 $this->getWorld()->setBlock($pos, $b);
1179 $this->sleeping = $pos;
1180 $this->networkPropertiesDirty =
true;
1182 $this->setSpawn($pos);
1184 $this->getWorld()->setSleepTicks(60);
1189 public function stopSleep() : void{
1190 if($this->sleeping instanceof Vector3){
1191 $b = $this->getWorld()->getBlock($this->sleeping);
1192 if($b instanceof Bed){
1193 $b->setOccupied(
false);
1194 $this->getWorld()->setBlock($this->sleeping, $b);
1196 (
new PlayerBedLeaveEvent($this, $b))->call();
1198 $this->sleeping =
null;
1199 $this->networkPropertiesDirty =
true;
1201 $this->getWorld()->setSleepTicks(0);
1203 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1207 public function getGamemode() : GameMode{
1208 return $this->gamemode;
1211 protected function internalSetGameMode(GameMode $gameMode) : void{
1212 $this->gamemode = $gameMode;
1214 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1215 $this->hungerManager->setEnabled($this->isSurvival());
1217 if($this->isSpectator()){
1218 $this->setFlying(
true);
1219 $this->setHasBlockCollision(
false);
1221 $this->onGround =
false;
1225 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1227 if($this->isSurvival()){
1228 $this->setFlying(
false);
1230 $this->setHasBlockCollision(
true);
1231 $this->setSilent(
false);
1232 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1240 if($this->gamemode === $gm){
1246 if($ev->isCancelled()){
1250 $this->internalSetGameMode($gm);
1252 if($this->isSpectator()){
1253 $this->despawnFromAll();
1255 $this->spawnToAll();
1258 $this->getNetworkSession()->syncGameMode($this->gamemode);
1269 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1279 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1289 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1292 public function isSpectator() : bool{
1293 return $this->gamemode === GameMode::SPECTATOR;
1296 public function setSneakPressed(
bool $sneakPressed) : void{
1297 $this->sneakPressed = $sneakPressed;
1305 return $this->sneakPressed;
1312 return $this->gamemode !== GameMode::CREATIVE;
1316 if($this->hasFiniteResources()){
1317 return parent::getDrops();
1324 if($this->hasFiniteResources()){
1325 return parent::getXpDropAmount();
1331 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1332 if(!$this->blockCollision){
1333 $this->onGround =
false;
1336 $bb =
new AxisAlignedBB(
1337 $this->boundingBox->minX,
1338 $this->location->y - 0.2,
1339 $this->boundingBox->minZ,
1340 $this->boundingBox->maxX,
1341 $this->location->y + 0.2,
1342 $this->boundingBox->maxZ
1347 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1349 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1357 protected function checkNearEntities() : void{
1358 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1359 $entity->scheduleUpdate();
1361 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1365 $entity->onCollideWithPlayer($this);
1369 public function getInAirTicks() : int{
1370 return $this->inAirTicks;
1382 Timings::$playerMove->startTiming();
1384 $this->actuallyHandleMovement($newPos);
1386 Timings::$playerMove->stopTiming();
1390 private function actuallyHandleMovement(Vector3 $newPos) : void{
1391 $this->moveRateLimit--;
1392 if($this->moveRateLimit < 0){
1396 $oldPos = $this->location;
1397 $distanceSquared = $newPos->distanceSquared($oldPos);
1401 if($distanceSquared > 225){
1413 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1414 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1416 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1418 $this->nextChunkOrderRun = 0;
1421 if(!$revert && $distanceSquared !== 0.0){
1422 $dx = $newPos->x - $oldPos->x;
1423 $dy = $newPos->y - $oldPos->y;
1424 $dz = $newPos->z - $oldPos->z;
1426 $this->move($dx, $dy, $dz);
1430 $this->revertMovement($oldPos);
1438 $now = microtime(true);
1439 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1440 $exceededRateLimit = $this->moveRateLimit < 0;
1441 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1442 $this->lastMovementProcess = $now;
1444 $from = clone $this->lastLocation;
1445 $to = clone $this->location;
1447 $delta = $to->distanceSquared($from);
1448 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1450 if($delta > 0.0001 || $deltaAngle > 1.0){
1451 if(PlayerMoveEvent::hasHandlers()){
1456 if($ev->isCancelled()){
1457 $this->revertMovement($from);
1461 if($to->distanceSquared($ev->getTo()) > 0.01){
1462 $this->teleport($ev->getTo());
1467 $this->lastLocation = $to;
1468 $this->broadcastMovement();
1470 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1471 if($horizontalDistanceTravelled > 0){
1473 if($this->isSprinting()){
1474 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, EntityExhaustEvent::CAUSE_SPRINTING);
1476 $this->hungerManager->exhaust(0.0, EntityExhaustEvent::CAUSE_WALKING);
1479 if($this->nextChunkOrderRun > 20){
1480 $this->nextChunkOrderRun = 20;
1485 if($exceededRateLimit){
1486 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1487 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1491 protected function revertMovement(Location $from) : void{
1492 $this->setPosition($from);
1493 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1496 protected function calculateFallDamage(
float $fallDistance) : float{
1497 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1505 public function setMotion(
Vector3 $motion) : bool{
1506 if(parent::setMotion($motion)){
1507 $this->broadcastMotion();
1508 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1515 protected function updateMovement(
bool $teleport =
false) : void{
1519 protected function tryChangeMovement() : void{
1523 public function onUpdate(int $currentTick) : bool{
1524 $tickDiff = $currentTick - $this->lastUpdate;
1530 $this->messageCounter = 2;
1532 $this->lastUpdate = $currentTick;
1534 if($this->justCreated){
1535 $this->onFirstUpdate($currentTick);
1538 if(!$this->isAlive() && $this->spawned){
1539 $this->onDeathUpdate($tickDiff);
1543 $this->timings->startTiming();
1546 Timings::$playerMove->startTiming();
1547 $this->processMostRecentMovements();
1548 $this->motion = Vector3::zero();
1549 if($this->onGround){
1550 $this->inAirTicks = 0;
1552 $this->inAirTicks += $tickDiff;
1554 Timings::$playerMove->stopTiming();
1556 Timings::$entityBaseTick->startTiming();
1557 $this->entityBaseTick($tickDiff);
1558 Timings::$entityBaseTick->stopTiming();
1560 if($this->isCreative() && $this->fireTicks > 1){
1561 $this->fireTicks = 1;
1564 if(!$this->isSpectator() && $this->isAlive()){
1565 Timings::$playerCheckNearEntities->startTiming();
1566 $this->checkNearEntities();
1567 Timings::$playerCheckNearEntities->stopTiming();
1570 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1571 $this->blockBreakHandler =
null;
1575 $this->timings->stopTiming();
1581 return $this->isCreative() || parent::canEat();
1585 return $this->isCreative() || parent::canBreathe();
1594 $eyePos = $this->getEyePos();
1595 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1599 $dV = $this->getDirectionVector();
1600 $eyeDot = $dV->dot($eyePos);
1601 $targetDot = $dV->dot($pos);
1602 return ($targetDot - $eyeDot) >= -$maxDiff;
1609 public function chat(
string $message) : bool{
1610 $this->removeCurrentWindow();
1612 if($this->messageCounter <= 0){
1618 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1619 if(strlen($message) > $maxTotalLength){
1623 $message = TextFormat::clean($message,
false);
1624 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1625 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1626 if(str_starts_with($messagePart,
'./')){
1627 $messagePart = substr($messagePart, 1);
1630 if(str_starts_with($messagePart,
"/")){
1631 Timings::$playerCommand->startTiming();
1632 $this->server->dispatchCommand($this, substr($messagePart, 1));
1633 Timings::$playerCommand->stopTiming();
1635 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1637 if(!$ev->isCancelled()){
1638 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1647 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1648 if(!$this->hotbar->isHotbarSlot($hotbarSlot)){
1651 if($hotbarSlot === $this->hotbar->getSelectedIndex()){
1655 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1657 if($ev->isCancelled()){
1661 $this->hotbar->setSelectedIndex($hotbarSlot);
1662 $this->setUsingItem(
false);
1670 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1671 $heldItemChanged = false;
1673 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->getMainHandItem())){
1676 $newReplica = clone $oldHeldItem;
1677 $newReplica->setCount($newHeldItem->getCount());
1678 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1679 $newDamage = $newHeldItem->getDamage();
1680 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1681 $newReplica->setDamage($newDamage);
1684 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1686 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1687 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1688 $this->broadcastSound(
new ItemBreakSound());
1690 $this->setMainHandItem($newHeldItem);
1691 $heldItemChanged =
true;
1695 if(!$heldItemChanged){
1696 $newHeldItem = $oldHeldItem;
1699 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1700 $this->setMainHandItem(array_shift($extraReturnedItems));
1702 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1704 $ev =
new PlayerDropItemEvent($this, $drop);
1705 if($this->isSpectator()){
1709 if(!$ev->isCancelled()){
1710 $this->dropItem($drop);
1721 $directionVector = $this->getDirectionVector();
1722 $item = $this->getMainHandItem();
1723 $oldItem = clone $item;
1726 if($this->hasItemCooldown($item) || $this->isSpectator()){
1732 if($ev->isCancelled()){
1736 $returnedItems = [];
1737 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1738 if($result === ItemUseResult::FAIL){
1742 $this->resetItemCooldown($oldItem);
1743 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1745 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1756 $slot = $this->getMainHandItem();
1758 $oldItem = clone $slot;
1761 if($this->hasItemCooldown($slot)){
1766 if($ev->isCancelled() || !$this->consumeObject($slot)){
1770 $this->setUsingItem(
false);
1771 $this->resetItemCooldown($oldItem);
1774 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1789 $item = $this->getMainHandItem();
1790 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1794 $oldItem = clone $item;
1796 $returnedItems = [];
1797 $result = $item->onReleaseUsing($this, $returnedItems);
1798 if($result === ItemUseResult::SUCCESS){
1799 $this->resetItemCooldown($oldItem);
1800 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1806 $this->setUsingItem(
false);
1810 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1811 $block = $this->getWorld()->getBlock($pos);
1812 if($block instanceof UnknownBlock){
1816 $item = $block->getPickedItem($addTileNBT);
1818 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1819 $existingSlot = $this->inventory->first($item);
1820 if($existingSlot === -1 && $this->hasFiniteResources()){
1825 if(!$ev->isCancelled()){
1826 $this->equipOrAddPickedItem($existingSlot, $item);
1832 public function pickEntity(
int $entityId) : bool{
1833 $entity = $this->getWorld()->getEntity($entityId);
1834 if($entity ===
null){
1838 $item = $entity->getPickedItem();
1843 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1844 $existingSlot = $this->inventory->first($item);
1845 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1850 if(!$ev->isCancelled()){
1851 $this->equipOrAddPickedItem($existingSlot, $item);
1857 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1858 if($existingSlot !== -1){
1859 if($existingSlot < $this->hotbar->getSize()){
1860 $this->hotbar->setSelectedIndex($existingSlot);
1862 $this->inventory->swap($this->hotbar->getSelectedIndex(), $existingSlot);
1865 $firstEmpty = $this->inventory->firstEmpty();
1866 if($firstEmpty === -1){
1867 $this->setMainHandItem($item);
1868 }elseif($firstEmpty < $this->hotbar->getSize()){
1869 $this->inventory->setItem($firstEmpty, $item);
1870 $this->hotbar->setSelectedIndex($firstEmpty);
1872 $this->inventory->swap($this->hotbar->getSelectedIndex(), $firstEmpty);
1873 $this->setMainHandItem($item);
1884 if($pos->distanceSquared($this->location) > 10000){
1888 $target = $this->getWorld()->getBlock($pos);
1890 $ev =
new PlayerInteractEvent($this, $this->getMainHandItem(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1891 if($this->isSpectator()){
1895 if($ev->isCancelled()){
1898 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1899 if($target->onAttack($this->getMainHandItem(), $face, $this)){
1903 $block = $target->getSide($face);
1904 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1905 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1906 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1910 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1911 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1917 public function continueBreakBlock(Vector3 $pos, Facing $face) : void{
1918 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1919 $this->blockBreakHandler->setTargetedFace($face);
1923 public function stopBreakBlock(Vector3 $pos) : void{
1924 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1925 $this->blockBreakHandler =
null;
1935 $this->removeCurrentWindow();
1937 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1938 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1939 $this->stopBreakBlock($pos);
1940 $item = $this->getMainHandItem();
1941 $oldItem = clone $item;
1942 $returnedItems = [];
1943 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1944 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1945 $this->hungerManager->exhaust(0.005, EntityExhaustEvent::CAUSE_MINING);
1949 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1961 $this->setUsingItem(false);
1963 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1964 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1965 $item = $this->getMainHandItem();
1966 $oldItem = clone $item;
1967 $returnedItems = [];
1968 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1969 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1973 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1986 if(!$entity->isAlive()){
1990 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1994 $heldItem = $this->getMainHandItem();
1995 $oldItem = clone $heldItem;
1997 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1998 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1999 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
2001 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
2005 $meleeEnchantmentDamage = 0;
2007 $meleeEnchantments = [];
2008 foreach($heldItem->getEnchantments() as $enchantment){
2009 $type = $enchantment->getType();
2010 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
2011 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
2012 $meleeEnchantments[] = $enchantment;
2015 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
2017 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
2018 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
2021 $entity->attack($ev);
2022 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
2024 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
2025 if($ev->isCancelled()){
2026 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
2029 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2031 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2032 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2035 foreach($meleeEnchantments as $enchantment){
2036 $type = $enchantment->getType();
2037 assert($type instanceof MeleeWeaponEnchantment);
2038 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2041 if($this->isAlive()){
2044 $returnedItems = [];
2045 $heldItem->onAttackEntity($entity, $returnedItems);
2046 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2048 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_ATTACK);
2061 if(!$ev->isCancelled()){
2062 $this->broadcastSound(new EntityAttackNoDamageSound());
2063 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2073 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2074 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2080 $item = $this->getMainHandItem();
2081 $oldItem = clone $item;
2082 if(!$ev->isCancelled()){
2083 if($item->onInteractEntity($this, $entity, $clickPos)){
2084 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->getMainHandItem())){
2085 if($item instanceof Durable && $item->isBroken()){
2086 $this->broadcastSound(new ItemBreakSound());
2088 $this->setMainHandItem($item);
2091 return $entity->
onInteract($this, $clickPos);
2096 public function toggleSprint(
bool $sprint) : bool{
2097 if($sprint === $this->sprinting){
2100 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2102 if($ev->isCancelled()){
2105 $this->setSprinting($sprint);
2109 public function toggleSneak(
bool $sneak,
bool $sneakPressed =
true) : bool{
2110 if($sneak === $this->sneaking && $sneakPressed === $this->sneakPressed){
2113 $this->setSneakPressed($sneakPressed);
2115 $ev =
new PlayerToggleSneakEvent($this, $sneak, $sneakPressed);
2116 if($sneak === $this->sneaking){
2121 if($ev->isCancelled()){
2124 $this->setSneaking($sneak);
2128 public function toggleFlight(
bool $fly) : bool{
2129 if($fly === $this->flying){
2132 $ev =
new PlayerToggleFlightEvent($this, $fly);
2133 if(!$this->allowFlight){
2137 if($ev->isCancelled()){
2140 $this->setFlying($fly);
2144 public function toggleGlide(
bool $glide) : bool{
2145 if($glide === $this->gliding){
2148 $ev =
new PlayerToggleGlideEvent($this, $glide);
2150 if($ev->isCancelled()){
2153 $this->setGliding($glide);
2157 public function toggleSwim(
bool $swim) : bool{
2158 if($swim === $this->swimming){
2161 $ev =
new PlayerToggleSwimEvent($this, $swim);
2163 if($ev->isCancelled()){
2166 $this->setSwimming($swim);
2170 public function emote(
string $emoteId) : void{
2171 $currentTick = $this->
server->getTick();
2172 if($currentTick - $this->lastEmoteTick > 5){
2173 $this->lastEmoteTick = $currentTick;
2174 $event =
new PlayerEmoteEvent($this, $emoteId);
2176 if(!$event->isCancelled()){
2177 $emoteId = $event->getEmoteId();
2178 parent::emote($emoteId);
2188 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2198 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2199 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2200 if($subtitle !==
""){
2201 $this->sendSubTitle($subtitle);
2203 $this->getNetworkSession()->onTitle($title);
2210 $this->getNetworkSession()->onSubTitle($subtitle);
2217 $this->getNetworkSession()->onActionBar($message);
2224 $this->getNetworkSession()->onClearTitle();
2231 $this->getNetworkSession()->onResetTitleOptions();
2242 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2243 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2251 $this->getNetworkSession()->onChatMessage($message);
2254 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2255 $this->getNetworkSession()->onJukeboxPopup($message);
2264 $this->getNetworkSession()->onPopup($message);
2267 public function sendTip(
string $message) : void{
2268 $this->getNetworkSession()->onTip($message);
2275 $this->getNetworkSession()->onToastNotification($title, $body);
2284 $id = $this->formIdCounter++;
2285 if($this->getNetworkSession()->onFormSent($id, $form)){
2286 $this->forms[$id] = $form;
2290 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2291 if(!isset($this->forms[$formId])){
2292 $this->logger->debug(
"Got unexpected response for form $formId");
2297 $this->forms[$formId]->handleResponse($this, $responseData);
2298 }
catch(FormValidationException $e){
2299 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2300 $this->logger->logException($e);
2302 unset($this->forms[$formId]);
2312 $this->getNetworkSession()->onCloseAllForms();
2327 if(!$ev->isCancelled()){
2328 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2343 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2345 if(!$ev->isCancelled()){
2346 $reason = $ev->getDisconnectReason();
2348 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2350 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2351 if($disconnectScreenMessage ===
""){
2352 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2354 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2376 if(!$this->isConnected()){
2380 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2381 $this->onPostDisconnect($reason, $quitMessage);
2392 if($this->isConnected()){
2393 throw new \LogicException(
"Player is still connected");
2397 $this->server->unsubscribeFromAllBroadcastChannels($this);
2399 $this->removeCurrentWindow();
2401 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2403 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2404 $this->server->broadcastMessage($quitMessage);
2408 $this->spawned =
false;
2411 $this->blockBreakHandler =
null;
2412 $this->despawnFromAll();
2414 $this->
server->removeOnlinePlayer($this);
2416 foreach($this->
server->getOnlinePlayers() as $player){
2417 if(!$player->canSee($this)){
2418 $player->showPlayer($this);
2421 $this->hiddenPlayers = [];
2423 if($this->location->isValid()){
2424 foreach($this->usedChunks as $index => $status){
2425 World::getXZ($index, $chunkX, $chunkZ);
2426 $this->unloadChunk($chunkX, $chunkZ);
2429 if(count($this->usedChunks) !== 0){
2430 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2432 $this->loadQueue = [];
2434 $this->removeCurrentWindow();
2435 $this->removePermanentWindows();
2437 $this->perm->getPermissionRecalculationCallbacks()->clear();
2439 $this->flagForDespawn();
2443 $this->disconnect(
"Player destroyed");
2444 $this->cursorInventory->removeAllWindows();
2445 $this->craftingGrid->removeAllWindows();
2446 parent::onDispose();
2450 $this->networkSession = null;
2451 $this->spawnPosition =
null;
2452 $this->deathPosition =
null;
2453 $this->blockBreakHandler =
null;
2454 parent::destroyCycles();
2464 public function __destruct(){
2465 parent::__destruct();
2466 $this->logger->debug(
"Destroyed by garbage collector");
2474 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2478 $nbt = $this->saveNBT();
2480 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2482 if($this->location->isValid()){
2483 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2486 if($this->hasValidCustomSpawn()){
2487 $spawn = $this->getSpawn();
2488 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2489 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2490 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2491 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2494 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2495 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2496 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2497 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2498 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2501 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2502 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2503 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2512 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2518 $this->removeCurrentWindow();
2520 $this->setDeathPosition($this->getPosition());
2522 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2525 if(!$ev->getKeepInventory()){
2526 foreach($ev->getDrops() as $item){
2527 $this->getWorld()->dropItem($this->location, $item);
2530 $this->hotbar->setSelectedIndex(0);
2531 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2532 $clearInventory($this->inventory);
2533 $clearInventory($this->armorInventory);
2534 $clearInventory($this->offHandInventory);
2537 if(!$ev->getKeepXp()){
2538 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2539 $this->xpManager->setXpAndProgress(0, 0.0);
2542 if($ev->getDeathMessage() !==
""){
2543 $this->server->broadcastMessage($ev->getDeathMessage());
2546 $this->startDeathAnimation();
2548 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2552 parent::onDeathUpdate($tickDiff);
2556 public function respawn() : void{
2557 if($this->
server->isHardcore()){
2558 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2559 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2564 $this->actuallyRespawn();
2567 protected function actuallyRespawn() : void{
2568 if($this->respawnLocked){
2571 $this->respawnLocked =
true;
2573 $this->logger->debug(
"Waiting for safe respawn position to be located");
2574 $spawn = $this->getSpawn();
2575 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2576 function(Position $safeSpawn) :
void{
2577 if(!$this->isConnected()){
2580 $this->logger->debug(
"Respawn position located, completing respawn");
2581 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2582 $spawnPosition = $ev->getRespawnPosition();
2583 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2584 if($spawnBlock instanceof RespawnAnchor){
2585 if($spawnBlock->getCharges() > 0){
2586 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2587 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2589 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2590 if($defaultSpawn !==
null){
2591 $this->setSpawn($defaultSpawn);
2592 $ev->setRespawnPosition($defaultSpawn);
2593 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2599 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2600 $this->teleport($realSpawn);
2602 $this->setSprinting(
false);
2603 $this->setSneaking(
false);
2604 $this->setFlying(
false);
2606 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2607 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2608 $this->deadTicks = 0;
2609 $this->noDamageTicks = 60;
2611 $this->effectManager->clear();
2612 $this->setHealth($this->getMaxHealth());
2614 foreach($this->attributeMap->getAll() as $attr){
2615 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2618 $attr->resetToDefault();
2621 $this->spawnToAll();
2622 $this->scheduleUpdate();
2624 $this->getNetworkSession()->onServerRespawn();
2625 $this->respawnLocked =
false;
2628 if($this->isConnected()){
2629 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2636 parent::applyPostDamageEffects($source);
2638 $this->hungerManager->exhaust(0.1, EntityExhaustEvent::CAUSE_DAMAGE);
2642 if(!$this->isAlive()){
2646 if($this->isCreative()
2647 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2650 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2654 parent::attack($source);
2657 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2658 parent::syncNetworkData($properties);
2660 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2661 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2663 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2664 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2666 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2667 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2669 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2670 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2672 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2673 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2674 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2678 public function sendData(?array $targets, ?array $data =
null) : void{
2679 if($targets === null){
2680 $targets = $this->getViewers();
2683 parent::sendData($targets, $data);
2687 if($this->spawned && $targets === null){
2688 $targets = $this->getViewers();
2691 parent::broadcastAnimation($animation, $targets);
2695 if($this->spawned && $targets === null){
2696 $targets = $this->getViewers();
2699 parent::broadcastSound($sound, $targets);
2705 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2706 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2712 if(parent::teleport($pos, $yaw, $pitch)){
2714 $this->removeCurrentWindow();
2717 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2718 $this->broadcastMovement(
true);
2720 $this->spawnToAll();
2722 $this->resetFallDistance();
2723 $this->nextChunkOrderRun = 0;
2724 if($this->spawnChunkLoadCount !== -1){
2725 $this->spawnChunkLoadCount = 0;
2727 $this->blockBreakHandler =
null;
2731 $this->resetLastMovements();
2739 protected function addDefaultWindows() : void{
2740 $this->cursorInventory = new SimpleInventory(1);
2741 $this->craftingGrid =
new CraftingGrid(CraftingGrid::SIZE_SMALL);
2743 $this->addPermanentWindows([
2744 new PlayerInventoryWindow($this, $this->inventory, PlayerInventoryWindow::TYPE_INVENTORY),
2745 new PlayerInventoryWindow($this, $this->armorInventory, PlayerInventoryWindow::TYPE_ARMOR),
2746 new PlayerInventoryWindow($this, $this->cursorInventory, PlayerInventoryWindow::TYPE_CURSOR),
2747 new PlayerInventoryWindow($this, $this->offHandInventory, PlayerInventoryWindow::TYPE_OFFHAND),
2748 new PlayerInventoryWindow($this, $this->craftingGrid, PlayerInventoryWindow::TYPE_CRAFTING),
2752 public function getCursorInventory() : Inventory{
2753 return $this->cursorInventory;
2756 public function getCraftingGrid() : CraftingGrid{
2757 return $this->craftingGrid;
2765 return $this->creativeInventory;
2772 $this->creativeInventory = $inventory;
2773 if($this->spawned && $this->isConnected()){
2774 $this->getNetworkSession()->getInvManager()?->syncCreative();
2782 private function doCloseInventory() : void{
2783 $windowsToClear = [];
2784 $mainInventoryWindow =
null;
2785 foreach($this->permanentWindows as $window){
2786 if($window->getType() === PlayerInventoryWindow::TYPE_CRAFTING || $window->getType() === PlayerInventoryWindow::TYPE_CURSOR){
2787 $windowsToClear[] = $window;
2788 }elseif($window->getType() === PlayerInventoryWindow::TYPE_INVENTORY){
2789 $mainInventoryWindow = $window;
2792 if($mainInventoryWindow ===
null){
2796 throw new AssumptionFailedError(
"This should never be null");
2799 if($this->currentWindow instanceof TemporaryInventoryWindow){
2800 $windowsToClear[] = $this->currentWindow;
2803 $builder =
new TransactionBuilder();
2804 foreach($windowsToClear as $window){
2805 $contents = $window->getInventory()->getContents();
2807 if(count($contents) > 0){
2808 $drops = $builder->getActionBuilder($mainInventoryWindow)->addItem(...$contents);
2809 foreach($drops as $drop){
2810 $builder->addAction(
new DropItemAction($drop));
2813 $builder->getActionBuilder($window)->clearAll();
2817 $actions = $builder->generateActions();
2818 if(count($actions) !== 0){
2819 $transaction =
new InventoryTransaction($this, $actions);
2821 $transaction->execute();
2822 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2823 }
catch(TransactionCancelledException){
2824 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2825 foreach($windowsToClear as $window){
2826 $window->getInventory()->clearAll();
2828 }
catch(TransactionValidationException $e){
2829 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2838 return $this->currentWindow;
2845 if($window === $this->currentWindow){
2848 if($window->getViewer() !== $this){
2849 throw new \InvalidArgumentException(
"Cannot reuse InventoryWindow instances, please create a new one for each player");
2853 if($ev->isCancelled()){
2857 $this->removeCurrentWindow();
2859 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2860 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2862 $this->logger->debug(
"Opening inventory window " . get_class($window) .
"#" . spl_object_id($window));
2863 $inventoryManager->onCurrentWindowChange($window);
2865 $this->currentWindow = $window;
2869 public function removeCurrentWindow() : void{
2870 $this->doCloseInventory();
2871 if($this->currentWindow !==
null){
2872 $currentWindow = $this->currentWindow;
2873 $this->logger->debug(
"Closing inventory window " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2874 $this->currentWindow->onClose();
2875 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2876 $inventoryManager->onCurrentWindowRemove();
2878 $this->currentWindow =
null;
2879 (
new InventoryCloseEvent($currentWindow, $this))->call();
2887 foreach($windows as $window){
2889 $this->permanentWindows[spl_object_id($window)] = $window;
2893 protected function removePermanentWindows() : void{
2894 foreach($this->permanentWindows as $window){
2897 $this->permanentWindows = [];
2905 return $this->permanentWindows;
2912 $block = $this->getWorld()->getBlock($position);
2914 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2915 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2917 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2921 use ChunkListenerNoOpTrait {
2922 onChunkChanged as
private;
2923 onChunkUnloaded as
private;
2927 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2928 if($status === UsedChunkStatus::SENT){
2929 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2930 $this->nextChunkOrderRun = 0;
2935 if($this->isUsingChunk($chunkX, $chunkZ)){
2936 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2937 $this->unloadChunk($chunkX, $chunkZ);