187 public const BROADCAST_CHANNEL_ADMINISTRATIVE =
"pocketmine.broadcast.admin";
188 public const BROADCAST_CHANNEL_USERS =
"pocketmine.broadcast.user";
190 public const DEFAULT_SERVER_NAME = VersionInfo::NAME .
" Server";
191 public const DEFAULT_MAX_PLAYERS = 20;
192 public const DEFAULT_PORT_IPV4 = 19132;
193 public const DEFAULT_PORT_IPV6 = 19133;
194 public const DEFAULT_MAX_VIEW_DISTANCE = 16;
201 public const TARGET_TICKS_PER_SECOND = 20;
205 public const TARGET_SECONDS_PER_TICK = 1 / self::TARGET_TICKS_PER_SECOND;
206 public const TARGET_NANOSECONDS_PER_TICK = 1_000_000_000 / self::TARGET_TICKS_PER_SECOND;
211 private const TPS_OVERLOAD_WARNING_THRESHOLD = self::TARGET_TICKS_PER_SECOND * 0.6;
213 private const TICKS_PER_WORLD_CACHE_CLEAR = 5 * self::TARGET_TICKS_PER_SECOND;
214 private const TICKS_PER_TPS_OVERLOAD_WARNING = 5 * self::TARGET_TICKS_PER_SECOND;
215 private const TICKS_PER_STATS_REPORT = 300 * self::TARGET_TICKS_PER_SECOND;
217 private const DEFAULT_ASYNC_COMPRESSION_THRESHOLD = 10_000;
219 private static ?
Server $instance =
null;
227 private Config $operators;
229 private Config $whitelist;
231 private bool $isRunning =
true;
233 private bool $hasStopped =
false;
237 private float $profilingTickRate = self::TARGET_TICKS_PER_SECOND;
244 private int $tickCounter = 0;
245 private float $nextTick = 0;
247 private array $tickAverage;
249 private array $useAverage;
250 private float $currentTPS = self::TARGET_TICKS_PER_SECOND;
251 private float $currentUse = 0;
252 private float $startTime;
254 private bool $doTitleTick =
true;
256 private int $sendUsageTicker = 0;
271 private int $maxPlayers;
273 private bool $onlineMode =
true;
276 private bool $networkCompressionAsync =
true;
277 private int $networkCompressionAsyncThreshold = self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD;
280 private bool $forceLanguage =
false;
282 private UuidInterface $serverID;
284 private string $dataPath;
285 private string $pluginPath;
293 private array $uniquePlayers = [];
300 private array $playerList = [];
308 private array $broadcastSubscribers = [];
310 public function getName() : string{
314 public function isRunning() : bool{
315 return $this->isRunning;
318 public function getPocketMineVersion() : string{
319 return VersionInfo::VERSION()->getFullVersion(true);
322 public function getVersion() : string{
323 return ProtocolInfo::MINECRAFT_VERSION;
326 public function getApiVersion() : string{
327 return VersionInfo::BASE_VERSION;
330 public function getFilePath() : string{
334 public function getResourcePath() : string{
338 public function getDataPath() : string{
339 return $this->dataPath;
342 public function getPluginPath() : string{
343 return $this->pluginPath;
346 public function getMaxPlayers() : int{
347 return $this->maxPlayers;
350 public function setMaxPlayers(
int $maxPlayers) : void{
351 $this->maxPlayers = $maxPlayers;
359 return $this->onlineMode;
366 return $this->getOnlineMode();
369 public function getPort() : int{
370 return $this->configGroup->getConfigInt(
ServerProperties::SERVER_PORT_IPV4, self::DEFAULT_PORT_IPV4);
373 public function getPortV6() : int{
374 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV6, self::DEFAULT_PORT_IPV6);
377 public function getViewDistance() : int{
378 return max(2, $this->configGroup->getConfigInt(ServerProperties::VIEW_DISTANCE, self::DEFAULT_MAX_VIEW_DISTANCE));
385 return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance())));
388 public function getIp() : string{
390 return $str !==
"" ? $str :
"0.0.0.0";
393 public function getIpV6() : string{
394 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV6);
395 return $str !==
"" ? $str :
"::";
398 public function getServerUniqueId() : UuidInterface{
399 return $this->serverID;
402 public function getGamemode() : GameMode{
403 return GameMode::fromString($this->configGroup->getConfigString(ServerProperties::GAME_MODE)) ?? GameMode::SURVIVAL;
406 public function getForceGamemode() : bool{
407 return $this->configGroup->getConfigBool(ServerProperties::FORCE_GAME_MODE, false);
417 public function hasWhitelist() : bool{
418 return $this->configGroup->getConfigBool(
ServerProperties::WHITELIST, false);
421 public function isHardcore() : bool{
422 return $this->configGroup->getConfigBool(ServerProperties::HARDCORE, false);
425 public function getMotd() : string{
426 return $this->configGroup->getConfigString(ServerProperties::MOTD, self::DEFAULT_SERVER_NAME);
429 public function getLoader() : ThreadSafeClassLoader{
430 return $this->autoloader;
433 public function getLogger() : AttachableThreadSafeLogger{
434 return $this->logger;
437 public function getUpdater() : UpdateChecker{
438 return $this->updater;
441 public function getPluginManager() : PluginManager{
442 return $this->pluginManager;
445 public function getCraftingManager() : CraftingManager{
446 return $this->craftingManager;
449 public function getResourcePackManager() : ResourcePackManager{
450 return $this->resourceManager;
453 public function getWorldManager() : WorldManager{
454 return $this->worldManager;
457 public function getAsyncPool() : AsyncPool{
458 return $this->asyncPool;
461 public function getTick() : int{
462 return $this->tickCounter;
469 return round($this->currentTPS, 2);
476 return round(array_sum($this->tickAverage) / count($this->tickAverage), 2);
483 return round($this->currentUse * 100, 2);
490 return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2);
493 public function getStartTime() : float{
494 return $this->startTime;
497 public function getCommandMap() : SimpleCommandMap{
498 return $this->commandMap;
505 return $this->playerList;
508 public function shouldSavePlayerData() : bool{
509 return $this->configGroup->getPropertyBool(Yml::PLAYER_SAVE_PLAYER_DATA, true);
512 public function getOfflinePlayer(
string $name) : Player|OfflinePlayer|null{
513 $name = strtolower($name);
514 $result = $this->getPlayerExact($name);
516 if($result ===
null){
517 $result =
new OfflinePlayer($name, $this->getOfflinePlayerData($name));
527 return $this->playerDataProvider->hasData($name);
530 public function getOfflinePlayerData(
string $name) : ?
CompoundTag{
533 return $this->playerDataProvider->loadData($name);
534 }
catch(PlayerDataLoadException $e){
535 $this->logger->debug(
"Failed to load player data for $name: " . $e->getMessage());
536 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_data_playerCorrupted($name)));
542 public function saveOfflinePlayerData(
string $name, CompoundTag $nbtTag) : void{
543 $ev = new PlayerDataSaveEvent($nbtTag, $name, $this->getPlayerExact($name));
544 if(!$this->shouldSavePlayerData()){
550 if(!$ev->isCancelled()){
551 Timings::$syncPlayerDataSave->time(function() use ($name, $ev) : void{
553 $this->playerDataProvider->saveData($name, $ev->getSaveData());
554 }catch(PlayerDataSaveException $e){
555 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_data_saveError($name, $e->getMessage())));
556 $this->logger->logException($e);
568 $class = $ev->getPlayerClass();
570 if($offlinePlayerData !==
null && ($world = $this->worldManager->getWorldByName($offlinePlayerData->getString(Player::TAG_LEVEL,
""))) !==
null){
571 $playerPos = EntityDataHelper::parseLocation($offlinePlayerData, $world);
573 $world = $this->worldManager->getDefaultWorld();
575 throw new AssumptionFailedError(
"Default world should always be loaded");
582 $createPlayer =
function(
Location $location) use ($playerPromiseResolver, $class, $session, $playerInfo, $authenticated, $offlinePlayerData) :
void{
584 $player =
new $class($this, $session, $playerInfo, $authenticated, $location, $offlinePlayerData);
585 if(!$player->hasPlayedBefore()){
586 $player->onGround =
true;
588 $playerPromiseResolver->resolve($player);
591 if($playerPos ===
null){
592 $world->requestSafeSpawn()->onCompletion(
593 function(Position $spawn) use ($createPlayer, $playerPromiseResolver, $session, $world) :
void{
594 if(!$session->isConnected()){
595 $playerPromiseResolver->reject();
598 $createPlayer(Location::fromObject($spawn, $world));
600 function() use ($playerPromiseResolver, $session) : void{
601 if($session->isConnected()){
602 $session->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
604 $playerPromiseResolver->reject();
608 $createPlayer($playerPos);
611 return $playerPromiseResolver->getPromise();
626 $name = strtolower($name);
627 $delta = PHP_INT_MAX;
628 foreach($this->getOnlinePlayers() as $player){
629 if(stripos($player->getName(), $name) === 0){
630 $curDelta = strlen($player->getName()) - strlen($name);
631 if($curDelta < $delta){
648 $name = strtolower($name);
649 foreach($this->getOnlinePlayers() as $player){
650 if(strtolower($player->getName()) === $name){
662 return $this->playerList[$rawUUID] ?? null;
669 return $this->getPlayerByRawUUID($uuid->getBytes());
673 return $this->configGroup;
681 if(($command = $this->commandMap->getCommand($name)) instanceof
PluginOwned){
688 public function getNameBans() :
BanList{
689 return $this->banByName;
692 public function getIPBans() : BanList{
693 return $this->banByIP;
696 public function addOp(
string $name) : void{
697 $this->operators->set(strtolower($name), true);
699 if(($player = $this->getPlayerExact($name)) !==
null){
700 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR,
true);
702 $this->operators->save();
705 public function removeOp(
string $name) : void{
706 $lowercaseName = strtolower($name);
707 foreach($this->operators->getAll() as $operatorName => $_){
708 $operatorName = (string) $operatorName;
709 if($lowercaseName === strtolower($operatorName)){
710 $this->operators->remove($operatorName);
714 if(($player = $this->getPlayerExact($name)) !==
null){
715 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
717 $this->operators->save();
720 public function addWhitelist(
string $name) : void{
721 $this->whitelist->set(strtolower($name), true);
722 $this->whitelist->save();
725 public function removeWhitelist(
string $name) : void{
726 $this->whitelist->remove(strtolower($name));
727 $this->whitelist->save();
730 public function isWhitelisted(
string $name) : bool{
731 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
734 public function isOp(
string $name) : bool{
735 return $this->operators->exists($name, true);
738 public function getWhitelisted() : Config{
739 return $this->whitelist;
742 public function getOps() : Config{
743 return $this->operators;
751 $section = $this->configGroup->getProperty(Yml::ALIASES);
753 if(is_array($section)){
754 foreach(Utils::promoteKeys($section) as $key => $value){
758 if(is_array($value)){
761 $commands[] = (string) $value;
764 $result[(string) $key] = $commands;
771 public static function getInstance() : Server{
772 if(self::$instance === null){
773 throw new \RuntimeException(
"Attempt to retrieve Server instance outside server thread");
775 return self::$instance;
778 public function __construct(
779 private ThreadSafeClassLoader $autoloader,
780 private AttachableThreadSafeLogger $logger,
784 if(self::$instance !==
null){
785 throw new \LogicException(
"Only one server instance can exist at once");
787 self::$instance = $this;
788 $this->startTime = microtime(
true);
789 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
790 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
793 $this->tickSleeper =
new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
795 $this->signalHandler =
new SignalHandler(
function() :
void{
796 $this->logger->info(
"Received signal interrupt, stopping the server");
804 Path::join($dataPath,
"worlds"),
805 Path::join($dataPath,
"players")
807 if(!file_exists($neededPath)){
808 mkdir($neededPath, 0777);
812 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
813 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
815 $this->logger->info(
"Loading server configuration");
816 $pocketmineYmlPath = Path::join($this->dataPath,
"pocketmine.yml");
817 if(!file_exists($pocketmineYmlPath)){
818 $content = Filesystem::fileGetContents(Path::join(\
pocketmine\RESOURCE_PATH,
"pocketmine.yml"));
819 if(VersionInfo::IS_DEVELOPMENT_BUILD){
820 $content = str_replace(
"preferred-channel: stable",
"preferred-channel: beta", $content);
822 @file_put_contents($pocketmineYmlPath, $content);
825 $this->configGroup =
new ServerConfigGroup(
826 new Config($pocketmineYmlPath, Config::YAML, []),
827 new Config(Path::join($this->dataPath,
"server.properties"), Config::PROPERTIES, [
828 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
829 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
830 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
831 ServerProperties::ENABLE_IPV6 =>
true,
832 ServerProperties::WHITELIST =>
false,
833 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
834 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name,
835 ServerProperties::FORCE_GAME_MODE =>
false,
836 ServerProperties::HARDCORE =>
false,
837 ServerProperties::PVP =>
true,
838 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
839 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS =>
"",
840 ServerProperties::DEFAULT_WORLD_NAME =>
"world",
841 ServerProperties::DEFAULT_WORLD_SEED =>
"",
842 ServerProperties::DEFAULT_WORLD_GENERATOR =>
"DEFAULT",
843 ServerProperties::ENABLE_QUERY =>
true,
844 ServerProperties::AUTO_SAVE =>
true,
845 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
846 ServerProperties::XBOX_AUTH =>
true,
847 ServerProperties::LANGUAGE =>
"eng"
851 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
852 if($this->logger instanceof MainLogger){
853 $this->logger->setLogDebug($debugLogLevel > 1);
856 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE,
false);
857 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString(
"settings.language", Language::FALLBACK_LANGUAGE));
859 $this->language =
new Language($selectedLang);
860 }
catch(LanguageNotFoundException $e){
861 $this->logger->error($e->getMessage());
863 $this->language =
new Language(Language::FALLBACK_LANGUAGE);
864 }
catch(LanguageNotFoundException $e){
865 $this->logger->emergency(
"Fallback language \"" . Language::FALLBACK_LANGUAGE .
"\" not found");
870 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
872 if(VersionInfo::IS_DEVELOPMENT_BUILD){
873 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS,
false)){
874 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
875 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
876 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
877 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
878 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5(
"https://github.com/pmmp/PocketMine-MP/releases")));
879 $this->forceShutdownExit();
884 $this->logger->warning(str_repeat(
"-", 40));
885 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
886 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
887 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
888 $this->logger->warning(str_repeat(
"-", 40));
891 $this->memoryManager =
new MemoryManager($this);
893 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
895 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS,
"auto")) ===
"auto"){
897 $processors = Utils::getCoreCount() - 2;
900 $poolSize = max(1, $processors);
903 $poolSize = max(1, (
int) $poolSize);
906 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING,
false));
907 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
909 $this->asyncPool =
new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
910 $this->asyncPool->addWorkerStartHook(
function(
int $i) :
void{
911 if(TimingsHandler::isEnabled()){
912 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled(
true), $i);
915 TimingsHandler::getToggleCallbacks()->add(
function(
bool $enable) :
void{
916 foreach($this->asyncPool->getRunningWorkers() as $workerId){
917 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled($enable), $workerId);
920 TimingsHandler::getReloadCallbacks()->add(
function() :
void{
921 foreach($this->asyncPool->getRunningWorkers() as $workerId){
922 $this->asyncPool->submitTaskToWorker(TimingsControlTask::reload(), $workerId);
925 TimingsHandler::getCollectCallbacks()->add(
function() : array{
927 foreach($this->asyncPool->getRunningWorkers() as $workerId){
929 $resolver =
new PromiseResolver();
930 $this->asyncPool->submitTaskToWorker(
new TimingsCollectionTask($resolver), $workerId);
932 $promises[] = $resolver->getPromise();
938 $netCompressionThreshold = -1;
939 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
940 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
942 if($netCompressionThreshold < 0){
943 $netCompressionThreshold =
null;
946 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
947 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
948 $this->logger->warning(
"Invalid network compression level $netCompressionLevel set, setting to default 6");
949 $netCompressionLevel = 6;
951 ZlibCompressor::setInstance(
new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
953 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION,
true);
954 $this->networkCompressionAsyncThreshold = max(
955 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
956 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
959 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION,
true);
961 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK,
true) && Terminal::hasFormattingCodes();
963 $this->operators =
new Config(Path::join($this->dataPath,
"ops.txt"), Config::ENUM);
964 $this->whitelist =
new Config(Path::join($this->dataPath,
"white-list.txt"), Config::ENUM);
966 $bannedTxt = Path::join($this->dataPath,
"banned.txt");
967 $bannedPlayersTxt = Path::join($this->dataPath,
"banned-players.txt");
968 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
969 @rename($bannedTxt, $bannedPlayersTxt);
971 @touch($bannedPlayersTxt);
972 $this->banByName =
new BanList($bannedPlayersTxt);
973 $this->banByName->load();
974 $bannedIpsTxt = Path::join($this->dataPath,
"banned-ips.txt");
975 @touch($bannedIpsTxt);
976 $this->banByIP =
new BanList($bannedIpsTxt);
977 $this->banByIP->load();
979 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
981 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH,
true);
982 if($this->onlineMode){
983 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
985 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
986 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
987 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
990 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE,
false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
991 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
994 @cli_set_process_title($this->getName() .
" " . $this->getPocketMineVersion());
996 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
998 $this->logger->debug(
"Server unique id: " . $this->getServerUniqueId());
999 $this->logger->debug(
"Machine unique id: " . Utils::getMachineUniqueId());
1001 $this->network =
new Network($this->logger);
1002 $this->network->setName($this->getMotd());
1004 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
1006 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW :
"") . $this->getPocketMineVersion() . TextFormat::RESET
1008 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
1010 DefaultPermissions::registerCorePermissions();
1012 $this->commandMap =
new SimpleCommandMap($this);
1014 $this->craftingManager = CraftingManagerFromDataHelper::make(BedrockDataFiles::RECIPES);
1016 $this->resourceManager =
new ResourcePackManager(Path::join($this->dataPath,
"resource_packs"), $this->logger);
1018 $pluginGraylist =
null;
1019 $graylistFile = Path::join($this->dataPath,
"plugin_list.yml");
1020 if(!file_exists($graylistFile)){
1021 copy(Path::join(\
pocketmine\RESOURCE_PATH,
'plugin_list.yml'), $graylistFile);
1024 $array = yaml_parse(Filesystem::fileGetContents($graylistFile));
1025 if(!is_array($array)){
1026 throw new \InvalidArgumentException(
"Expected array for root, but have " . gettype($array));
1028 $pluginGraylist = PluginGraylist::fromArray($array);
1029 }
catch(\InvalidArgumentException $e){
1030 $this->logger->emergency(
"Failed to load $graylistFile: " . $e->getMessage());
1031 $this->forceShutdownExit();
1034 $this->pluginManager =
new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR,
true) ?
null : Path::join($this->dataPath,
"plugin_data"), $pluginGraylist);
1035 $this->pluginManager->registerInterface(
new PharPluginLoader($this->autoloader));
1036 $this->pluginManager->registerInterface(
new ScriptPluginLoader());
1037 $this->pluginManager->registerInterface(
new FolderPluginLoader($this->autoloader));
1039 $providerManager =
new WorldProviderManager();
1041 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT,
""))) !==
null &&
1042 $format instanceof WritableWorldProviderManagerEntry
1044 $providerManager->setDefault($format);
1045 }elseif($formatName !==
""){
1046 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1049 $this->worldManager =
new WorldManager($this, Path::join($this->dataPath,
"worlds"), $providerManager);
1050 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1051 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1053 $this->updater =
new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST,
"update.pmmp.io"));
1055 $this->queryInfo =
new QueryInfo($this);
1057 $this->playerDataProvider =
new DatFilePlayerDataProvider(Path::join($this->dataPath,
"players"));
1059 register_shutdown_function($this->crashDump(...));
1061 $loadErrorCount = 0;
1062 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1063 if($loadErrorCount > 0){
1064 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1065 $this->forceShutdownExit();
1068 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1069 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1070 $this->forceShutdownExit();
1074 if(!$this->startupPrepareWorlds()){
1075 $this->forceShutdownExit();
1079 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1080 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1081 $this->forceShutdownExit();
1085 if(!$this->startupPrepareNetworkInterfaces()){
1086 $this->forceShutdownExit();
1090 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED,
true)){
1091 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1092 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1095 $this->configGroup->save();
1097 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1098 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_donate(TextFormat::AQUA .
"https://patreon.com/pocketminemp" . TextFormat::RESET)));
1099 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(
true) - $this->startTime, 3)))));
1101 $forwarder =
new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1102 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1103 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1106 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT,
true)){
1107 $this->console =
new ConsoleReaderChildProcessDaemon($this->logger);
1110 $this->tickProcessor();
1111 $this->forceShutdown();
1112 }
catch(\Throwable $e){
1113 $this->exceptionHandler($e);
1117 private function startupPrepareWorlds() : bool{
1118 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1119 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1120 if($generatorEntry ===
null){
1121 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1123 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1128 $generatorEntry->validateGeneratorOptions($generatorOptions);
1129 }
catch(InvalidGeneratorOptionsException $e){
1130 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1132 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1136 return $generatorEntry->getGeneratorClass();
1139 $anyWorldFailedToLoad =
false;
1141 foreach(Utils::promoteKeys((array) $this->configGroup->getProperty(Yml::WORLDS, [])) as $name => $options){
1142 if(!is_string($name)){
1146 if($options ===
null){
1148 }elseif(!is_array($options)){
1152 if(!$this->worldManager->loadWorld($name,
true)){
1153 if($this->worldManager->isWorldGenerated($name)){
1155 $anyWorldFailedToLoad = true;
1158 $creationOptions = WorldCreationOptions::create();
1161 $generatorName = $options[
"generator"] ??
"default";
1162 $generatorOptions = isset($options[
"preset"]) && is_string($options[
"preset"]) ? $options[
"preset"] :
"";
1164 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1165 if($generatorClass ===
null){
1166 $anyWorldFailedToLoad =
true;
1169 $creationOptions->setGeneratorClass($generatorClass);
1170 $creationOptions->setGeneratorOptions($generatorOptions);
1172 $creationOptions->setDifficulty($this->getDifficulty());
1173 if(isset($options[
"difficulty"]) && is_string($options[
"difficulty"])){
1174 $creationOptions->setDifficulty(World::getDifficultyFromString($options[
"difficulty"]));
1177 if(isset($options[
"seed"])){
1178 $convertedSeed = Generator::convertSeed((
string) ($options[
"seed"] ??
""));
1179 if($convertedSeed !==
null){
1180 $creationOptions->setSeed($convertedSeed);
1184 $this->worldManager->generateWorld($name, $creationOptions);
1188 if($this->worldManager->getDefaultWorld() ===
null){
1189 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1190 if(trim($default) ===
""){
1191 $this->logger->warning(
"level-name cannot be null, using default");
1193 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1195 if(!$this->worldManager->loadWorld($default,
true)){
1196 if($this->worldManager->isWorldGenerated($default)){
1197 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1201 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1202 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1203 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1205 if($generatorClass ===
null){
1206 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1209 $creationOptions = WorldCreationOptions::create()
1210 ->setGeneratorClass($generatorClass)
1211 ->setGeneratorOptions($generatorOptions);
1212 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1213 if($convertedSeed !==
null){
1214 $creationOptions->setSeed($convertedSeed);
1216 $creationOptions->setDifficulty($this->getDifficulty());
1217 $this->worldManager->generateWorld($default, $creationOptions);
1220 $world = $this->worldManager->getWorldByName($default);
1221 if($world ===
null){
1222 throw new AssumptionFailedError(
"We just loaded/generated the default world, so it must exist");
1224 $this->worldManager->setDefaultWorld($world);
1227 return !$anyWorldFailedToLoad;
1230 private function startupPrepareConnectableNetworkInterfaces(
1235 PacketBroadcaster $packetBroadcaster,
1236 EntityEventBroadcaster $entityEventBroadcaster,
1237 TypeConverter $typeConverter
1239 $prettyIp = $ipV6 ?
"[$ip]" : $ip;
1241 $rakLibRegistered = $this->network->registerInterface(
new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1242 }
catch(NetworkInterfaceStartException $e){
1243 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1250 if($rakLibRegistered){
1251 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (
string) $port)));
1254 if(!$rakLibRegistered){
1257 $this->network->registerInterface(
new DedicatedQueryNetworkInterface($ip, $port, $ipV6,
new \
PrefixedLogger($this->logger,
"Dedicated Query Interface")));
1259 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (
string) $port)));
1264 private function startupPrepareNetworkInterfaces() : bool{
1265 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1267 $typeConverter = TypeConverter::getInstance();
1268 $packetBroadcaster =
new StandardPacketBroadcaster($this);
1269 $entityEventBroadcaster =
new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1272 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(),
false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1274 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6,
true) &&
1275 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(),
true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1282 $this->network->registerRawPacketHandler(
new QueryHandler($this));
1285 foreach($this->getIPBans()->getEntries() as $entry){
1286 $this->network->blockAddress($entry->getName(), -1);
1289 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING,
false)){
1290 $this->network->registerInterface(
new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1301 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1308 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1309 if(count($this->broadcastSubscribers[$channelId]) === 1){
1310 unset($this->broadcastSubscribers[$channelId]);
1312 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1321 foreach(
Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1322 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1333 return $this->broadcastSubscribers[$channelId] ?? [];
1340 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1342 foreach($recipients as $recipient){
1343 $recipient->sendMessage($message);
1346 return count($recipients);
1352 private function getPlayerBroadcastSubscribers(
string $channelId) : array{
1355 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1356 if($subscriber instanceof Player){
1357 $players[spl_object_id($subscriber)] = $subscriber;
1366 public function broadcastTip(
string $tip, ?array $recipients =
null) : int{
1367 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1369 foreach($recipients as $recipient){
1370 $recipient->sendTip($tip);
1373 return count($recipients);
1380 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1382 foreach($recipients as $recipient){
1383 $recipient->sendPopup($popup);
1386 return count($recipients);
1395 public function broadcastTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1, ?array $recipients =
null) : int{
1396 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1398 foreach($recipients as $recipient){
1399 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1402 return count($recipients);
1418 public function prepareBatch(
string $buffer, Compressor $compressor, ?
bool $sync =
null, ?TimingsHandler $timings =
null) : CompressBatchPromise|string{
1419 $timings ??= Timings::$playerNetworkSendCompress;
1421 $timings->startTiming();
1423 $threshold = $compressor->getCompressionThreshold();
1424 if($threshold ===
null || strlen($buffer) < $compressor->getCompressionThreshold()){
1425 $compressionType = CompressionAlgorithm::NONE;
1426 $compressed = $buffer;
1429 $sync ??= !$this->networkCompressionAsync;
1431 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1432 $promise =
new CompressBatchPromise();
1433 $task =
new CompressBatchTask($buffer, $promise, $compressor);
1434 $this->asyncPool->submitTask($task);
1438 $compressionType = $compressor->getNetworkId();
1439 $compressed = $compressor->compress($buffer);
1442 return chr($compressionType) . $compressed;
1444 $timings->stopTiming();
1448 public function enablePlugins(PluginEnableOrder $type) : bool{
1450 foreach($this->pluginManager->getPlugins() as $plugin){
1451 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1452 if(!$this->pluginManager->enablePlugin($plugin)){
1453 $allSuccess =
false;
1458 if($type === PluginEnableOrder::POSTWORLD){
1459 $this->commandMap->registerServerAliases();
1472 if($ev->isCancelled()){
1476 $commandLine = $ev->getCommand();
1479 return $this->commandMap->dispatch($sender, $commandLine);
1486 if($this->isRunning){
1487 $this->isRunning =
false;
1488 $this->signalHandler->unregister();
1492 private function forceShutdownExit() : void{
1493 $this->forceShutdown();
1494 Process::kill(Process::pid());
1497 public function forceShutdown() : void{
1498 if($this->hasStopped){
1502 if($this->doTitleTick){
1506 if($this->isRunning){
1507 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1510 if(!$this->isRunning()){
1511 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1514 $this->hasStopped =
true;
1518 if(isset($this->pluginManager)){
1519 $this->logger->debug(
"Disabling all plugins");
1520 $this->pluginManager->disablePlugins();
1523 if(isset($this->network)){
1524 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE,
"Server closed"));
1527 if(isset($this->worldManager)){
1528 $this->logger->debug(
"Unloading all worlds");
1529 foreach($this->worldManager->getWorlds() as $world){
1530 $this->worldManager->unloadWorld($world,
true);
1534 $this->logger->debug(
"Removing event handlers");
1535 HandlerListManager::global()->unregisterAll();
1537 if(isset($this->asyncPool)){
1538 $this->logger->debug(
"Shutting down async task worker pool");
1539 $this->asyncPool->shutdown();
1542 if(isset($this->configGroup)){
1543 $this->logger->debug(
"Saving properties");
1544 $this->configGroup->save();
1547 if($this->console !==
null){
1548 $this->logger->debug(
"Closing console");
1549 $this->console->quit();
1552 if(isset($this->network)){
1553 $this->logger->debug(
"Stopping network interfaces");
1554 foreach($this->network->getInterfaces() as $interface){
1555 $this->logger->debug(
"Stopping network interface " . get_class($interface));
1556 $this->network->unregisterInterface($interface);
1559 }
catch(\Throwable $e){
1560 $this->logger->logException($e);
1561 $this->logger->emergency(
"Crashed while crashing, killing process");
1562 @Process::kill(Process::pid());
1567 public function getQueryInformation() : QueryInfo{
1568 return $this->queryInfo;
1576 while(@ob_end_flush()){}
1579 if($trace ===
null){
1580 $trace = $e->getTrace();
1586 $this->logger->logException($e, $trace);
1588 if($e instanceof ThreadCrashException){
1589 $info = $e->getCrashInfo();
1590 $type = $info->getType();
1591 $errstr = $info->getMessage();
1592 $errfile = $info->getFile();
1593 $errline = $info->getLine();
1594 $printableTrace = $info->getTrace();
1595 $thread = $info->getThreadName();
1597 $type = get_class($e);
1598 $errstr = $e->getMessage();
1599 $errfile = $e->getFile();
1600 $errline = $e->getLine();
1601 $printableTrace = Utils::printableTraceWithMetadata($trace);
1605 $errstr = preg_replace(
'/\s+/',
' ', trim($errstr));
1609 "message" => $errstr,
1610 "fullFile" => $errfile,
1611 "file" => Filesystem::cleanPath($errfile),
1613 "trace" => $printableTrace,
1617 global $lastExceptionError, $lastError;
1618 $lastExceptionError = $lastError;
1622 private function writeCrashDumpFile(CrashDump $dump) : string{
1623 $crashFolder = Path::join($this->dataPath,
"crashdumps");
1624 if(!is_dir($crashFolder)){
1625 mkdir($crashFolder);
1627 $crashDumpPath = Path::join($crashFolder, date(
"D_M_j-H.i.s-T_Y", (
int) $dump->getData()->time) .
".log");
1629 $fp = @fopen($crashDumpPath,
"wb");
1630 if(!is_resource($fp)){
1631 throw new \RuntimeException(
"Unable to open new file to generate crashdump");
1633 $writer =
new CrashDumpRenderer($fp, $dump->getData());
1634 $writer->renderHumanReadable();
1635 $dump->encodeData($writer);
1638 return $crashDumpPath;
1641 public function crashDump() : void{
1642 while(@ob_end_flush()){}
1643 if(!$this->isRunning){
1646 if($this->sendUsageTicker > 0){
1647 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1649 $this->hasStopped =
false;
1651 ini_set(
"error_reporting",
'0');
1652 ini_set(
"memory_limit",
'-1');
1654 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1655 $dump =
new CrashDump($this, $this->pluginManager ??
null);
1657 $crashDumpPath = $this->writeCrashDumpFile($dump);
1659 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1661 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED,
true)){
1664 $stamp = Path::join($this->dataPath,
"crashdumps",
".last_crash");
1665 $crashInterval = 120;
1666 if(($lastReportTime = @filemtime($stamp)) !==
false && $lastReportTime + $crashInterval >= time()){
1668 $this->logger->debug(
"Not sending crashdump due to last crash less than $crashInterval seconds ago");
1672 if($dump->getData()->error[
"type"] === \ParseError::class){
1676 if(strrpos(VersionInfo::GIT_HASH(),
"-dirty") !==
false || VersionInfo::GIT_HASH() === str_repeat(
"00", 20)){
1677 $this->logger->debug(
"Not sending crashdump due to locally modified");
1682 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS,
true) ?
"https" :
"http") .
"://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST,
"crash.pmmp.io") .
"/submit/api";
1683 $postUrlError =
"Unknown error";
1684 $reply = Internet::postURL($url, [
1686 "name" => $this->getName() .
" " . $this->getPocketMineVersion(),
1688 "reportPaste" => base64_encode($dump->getEncodedData())
1689 ], 10, [], $postUrlError);
1691 if($reply !==
null && is_object($data = json_decode($reply->getBody()))){
1692 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1693 $reportId = $data->crashId;
1694 $reportUrl = $data->crashUrl;
1695 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (
string) $reportId)));
1696 }elseif(isset($data->error) && is_string($data->error)){
1697 $this->logger->emergency(
"Automatic crash report submission failed: $data->error");
1699 $this->logger->emergency(
"Invalid JSON response received from crash archive: " . $reply->getBody());
1702 $this->logger->emergency(
"Failed to communicate with crash archive: $postUrlError");
1706 }
catch(\Throwable $e){
1707 $this->logger->logException($e);
1709 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1710 }
catch(\Throwable $e){}
1713 $this->forceShutdown();
1714 $this->isRunning =
false;
1717 $uptime = time() - ((int) $this->startTime);
1719 $spacing = $minUptime - $uptime;
1721 echo
"--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1724 @Process::kill(Process::pid());
1736 return $this->tickSleeper;
1739 private function tickProcessor() : void{
1740 $this->nextTick = microtime(true);
1742 while($this->isRunning){
1746 $this->tickSleeper->sleepUntil($this->nextTick);
1750 public function addOnlinePlayer(Player $player) : bool{
1751 $ev = new PlayerLoginEvent($player,
"Plugin reason");
1753 if($ev->isCancelled() || !$player->isConnected()){
1754 $player->disconnect($ev->getKickMessage());
1759 $session = $player->getNetworkSession();
1760 $position = $player->getPosition();
1761 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1762 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1764 (
string) $session->getPort(),
1765 (
string) $player->getId(),
1766 $position->getWorld()->getDisplayName(),
1767 (
string) round($position->x, 4),
1768 (
string) round($position->y, 4),
1769 (
string) round($position->z, 4)
1772 foreach($this->playerList as $p){
1773 $p->getNetworkSession()->onPlayerAdded($player);
1775 $rawUUID = $player->getUniqueId()->getBytes();
1776 $this->playerList[$rawUUID] = $player;
1778 if($this->sendUsageTicker > 0){
1779 $this->uniquePlayers[$rawUUID] = $rawUUID;
1785 public function removeOnlinePlayer(Player $player) : void{
1786 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1787 unset($this->playerList[$rawUUID]);
1788 foreach($this->playerList as $p){
1789 $p->getNetworkSession()->onPlayerRemoved($player);
1794 public function sendUsage(
int $type = SendUsageTask::TYPE_STATUS) : void{
1795 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1796 $this->asyncPool->submitTask(
new SendUsageTask($this, $type, $this->uniquePlayers));
1798 $this->uniquePlayers = [];
1801 public function getLanguage() : Language{
1802 return $this->language;
1805 public function isLanguageForced() : bool{
1806 return $this->forceLanguage;
1809 public function getNetwork() : Network{
1810 return $this->network;
1813 public function getMemoryManager() : MemoryManager{
1814 return $this->memoryManager;
1817 private function titleTick() : void{
1818 Timings::$titleTick->startTiming();
1820 $u = Process::getAdvancedMemoryUsage();
1821 $usage = sprintf(
"%g/%g/%g MB @ %d threads", round(($u[0] / 1024) / 1024, 2), round(($u[1] / 1024) / 1024, 2), round(($u[2] / 1024) / 1024, 2), Process::getThreadCount());
1823 $online = count($this->playerList);
1824 $connecting = $this->network->getConnectionCount() - $online;
1825 $bandwidthStats = $this->network->getBandwidthTracker();
1827 echo
"\x1b]0;" . $this->getName() .
" " .
1828 $this->getPocketMineVersion() .
1829 " | Online $online/" . $this->maxPlayers .
1830 ($connecting > 0 ?
" (+$connecting connecting)" :
"") .
1831 " | Memory " . $usage .
1832 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1833 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1834 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1835 " | Load " . $this->getTickUsageAverage() .
"%\x07";
1837 Timings::$titleTick->stopTiming();
1843 private function tick() : void{
1844 $tickTime = microtime(true);
1845 if(($tickTime - $this->nextTick) < -0.025){
1849 Timings::$serverTick->startTiming();
1851 ++$this->tickCounter;
1853 Timings::$scheduler->startTiming();
1854 $this->pluginManager->tickSchedulers($this->tickCounter);
1855 Timings::$scheduler->stopTiming();
1857 Timings::$schedulerAsync->startTiming();
1858 $this->asyncPool->collectTasks();
1859 Timings::$schedulerAsync->stopTiming();
1861 $this->worldManager->tick($this->tickCounter);
1863 Timings::$connection->startTiming();
1864 $this->network->tick();
1865 Timings::$connection->stopTiming();
1867 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1868 if($this->doTitleTick){
1871 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1872 $this->currentUse = 0;
1874 $queryRegenerateEvent =
new QueryRegenerateEvent(
new QueryInfo($this));
1875 $queryRegenerateEvent->call();
1876 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1878 $this->network->updateName();
1879 $this->network->getBandwidthTracker()->rotateAverageHistory();
1882 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1883 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1884 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1887 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1888 foreach($this->worldManager->getWorlds() as $world){
1889 $world->clearCache();
1893 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1894 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1897 $this->memoryManager->check();
1899 if($this->console !==
null){
1900 Timings::$serverCommand->startTiming();
1901 while(($line = $this->console->readLine()) !==
null){
1902 $this->consoleSender ??=
new ConsoleCommandSender($this, $this->language);
1903 $this->dispatchCommand($this->consoleSender, $line);
1905 Timings::$serverCommand->stopTiming();
1908 Timings::$serverTick->stopTiming();
1910 $now = microtime(
true);
1911 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1912 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1913 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1915 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1917 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1918 $this->tickAverage[$idx] = $this->currentTPS;
1919 $this->useAverage[$idx] = $this->currentUse;
1920 $this->tickSleeper->resetNotificationProcessingTime();
1922 if(($this->nextTick - $tickTime) < -1){
1923 $this->nextTick = $tickTime;
1925 $this->nextTick += self::TARGET_SECONDS_PER_TICK;