183 public const BROADCAST_CHANNEL_ADMINISTRATIVE =
"pocketmine.broadcast.admin";
184 public const BROADCAST_CHANNEL_USERS =
"pocketmine.broadcast.user";
186 public const DEFAULT_SERVER_NAME = VersionInfo::NAME .
" Server";
187 public const DEFAULT_MAX_PLAYERS = 20;
188 public const DEFAULT_PORT_IPV4 = 19132;
189 public const DEFAULT_PORT_IPV6 = 19133;
190 public const DEFAULT_MAX_VIEW_DISTANCE = 16;
197 public const TARGET_TICKS_PER_SECOND = 20;
201 public const TARGET_SECONDS_PER_TICK = 1 / self::TARGET_TICKS_PER_SECOND;
202 public const TARGET_NANOSECONDS_PER_TICK = 1_000_000_000 / self::TARGET_TICKS_PER_SECOND;
207 private const TPS_OVERLOAD_WARNING_THRESHOLD = self::TARGET_TICKS_PER_SECOND * 0.6;
209 private const TICKS_PER_WORLD_CACHE_CLEAR = 5 * self::TARGET_TICKS_PER_SECOND;
210 private const TICKS_PER_TPS_OVERLOAD_WARNING = 5 * self::TARGET_TICKS_PER_SECOND;
211 private const TICKS_PER_STATS_REPORT = 300 * self::TARGET_TICKS_PER_SECOND;
213 private const DEFAULT_ASYNC_COMPRESSION_THRESHOLD = 10_000;
215 private static ?
Server $instance =
null;
223 private Config $operators;
225 private Config $whitelist;
227 private bool $isRunning =
true;
229 private bool $hasStopped =
false;
233 private float $profilingTickRate = self::TARGET_TICKS_PER_SECOND;
240 private int $tickCounter = 0;
241 private float $nextTick = 0;
243 private array $tickAverage;
245 private array $useAverage;
246 private float $currentTPS = self::TARGET_TICKS_PER_SECOND;
247 private float $currentUse = 0;
248 private float $startTime;
250 private bool $doTitleTick =
true;
252 private int $sendUsageTicker = 0;
267 private int $maxPlayers;
269 private bool $onlineMode =
true;
272 private bool $networkCompressionAsync =
true;
273 private int $networkCompressionAsyncThreshold = self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD;
276 private bool $forceLanguage =
false;
278 private UuidInterface $serverID;
280 private string $dataPath;
281 private string $pluginPath;
289 private array $uniquePlayers = [];
296 private array $playerList = [];
304 private array $broadcastSubscribers = [];
306 public function getName() : string{
310 public function isRunning() : bool{
311 return $this->isRunning;
314 public function getPocketMineVersion() : string{
315 return VersionInfo::VERSION()->getFullVersion(true);
318 public function getVersion() : string{
319 return ProtocolInfo::MINECRAFT_VERSION;
322 public function getApiVersion() : string{
323 return VersionInfo::BASE_VERSION;
326 public function getFilePath() : string{
330 public function getResourcePath() : string{
334 public function getDataPath() : string{
335 return $this->dataPath;
338 public function getPluginPath() : string{
339 return $this->pluginPath;
342 public function getMaxPlayers() : int{
343 return $this->maxPlayers;
351 return $this->onlineMode;
358 return $this->getOnlineMode();
361 public function getPort() : int{
362 return $this->configGroup->getConfigInt(
ServerProperties::SERVER_PORT_IPV4, self::DEFAULT_PORT_IPV4);
365 public function getPortV6() : int{
366 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV6, self::DEFAULT_PORT_IPV6);
369 public function getViewDistance() : int{
370 return max(2, $this->configGroup->getConfigInt(ServerProperties::VIEW_DISTANCE, self::DEFAULT_MAX_VIEW_DISTANCE));
377 return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance())));
380 public function getIp() : string{
382 return $str !==
"" ? $str :
"0.0.0.0";
385 public function getIpV6() : string{
386 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV6);
387 return $str !==
"" ? $str :
"::";
390 public function getServerUniqueId() : UuidInterface{
391 return $this->serverID;
394 public function getGamemode() : GameMode{
395 return GameMode::fromString($this->configGroup->getConfigString(ServerProperties::GAME_MODE)) ?? GameMode::SURVIVAL;
398 public function getForceGamemode() : bool{
399 return $this->configGroup->getConfigBool(ServerProperties::FORCE_GAME_MODE, false);
409 public function hasWhitelist() : bool{
410 return $this->configGroup->getConfigBool(
ServerProperties::WHITELIST, false);
413 public function isHardcore() : bool{
414 return $this->configGroup->getConfigBool(ServerProperties::HARDCORE, false);
417 public function getMotd() : string{
418 return $this->configGroup->getConfigString(ServerProperties::MOTD, self::DEFAULT_SERVER_NAME);
421 public function getLoader() : ThreadSafeClassLoader{
422 return $this->autoloader;
425 public function getLogger() : AttachableThreadSafeLogger{
426 return $this->logger;
429 public function getUpdater() : UpdateChecker{
430 return $this->updater;
433 public function getPluginManager() : PluginManager{
434 return $this->pluginManager;
437 public function getCraftingManager() : CraftingManager{
438 return $this->craftingManager;
441 public function getResourcePackManager() : ResourcePackManager{
442 return $this->resourceManager;
445 public function getWorldManager() : WorldManager{
446 return $this->worldManager;
449 public function getAsyncPool() : AsyncPool{
450 return $this->asyncPool;
453 public function getTick() : int{
454 return $this->tickCounter;
461 return round($this->currentTPS, 2);
468 return round(array_sum($this->tickAverage) / count($this->tickAverage), 2);
475 return round($this->currentUse * 100, 2);
482 return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2);
485 public function getStartTime() : float{
486 return $this->startTime;
489 public function getCommandMap() : SimpleCommandMap{
490 return $this->commandMap;
497 return $this->playerList;
500 public function shouldSavePlayerData() : bool{
501 return $this->configGroup->getPropertyBool(Yml::PLAYER_SAVE_PLAYER_DATA, true);
504 public function getOfflinePlayer(
string $name) : Player|OfflinePlayer|null{
505 $name = strtolower($name);
506 $result = $this->getPlayerExact($name);
508 if($result ===
null){
509 $result =
new OfflinePlayer($name, $this->getOfflinePlayerData($name));
519 return $this->playerDataProvider->hasData($name);
522 public function getOfflinePlayerData(
string $name) : ?
CompoundTag{
525 return $this->playerDataProvider->loadData($name);
526 }
catch(PlayerDataLoadException $e){
527 $this->logger->debug(
"Failed to load player data for $name: " . $e->getMessage());
528 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_data_playerCorrupted($name)));
534 public function saveOfflinePlayerData(
string $name, CompoundTag $nbtTag) : void{
535 $ev = new PlayerDataSaveEvent($nbtTag, $name, $this->getPlayerExact($name));
536 if(!$this->shouldSavePlayerData()){
542 if(!$ev->isCancelled()){
543 Timings::$syncPlayerDataSave->time(function() use ($name, $ev) : void{
545 $this->playerDataProvider->saveData($name, $ev->getSaveData());
546 }catch(PlayerDataSaveException $e){
547 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_data_saveError($name, $e->getMessage())));
548 $this->logger->logException($e);
560 $class = $ev->getPlayerClass();
562 if($offlinePlayerData !==
null && ($world = $this->worldManager->getWorldByName($offlinePlayerData->getString(Player::TAG_LEVEL,
""))) !==
null){
563 $playerPos = EntityDataHelper::parseLocation($offlinePlayerData, $world);
565 $world = $this->worldManager->getDefaultWorld();
567 throw new AssumptionFailedError(
"Default world should always be loaded");
574 $createPlayer =
function(
Location $location) use ($playerPromiseResolver, $class, $session, $playerInfo, $authenticated, $offlinePlayerData) :
void{
576 $player =
new $class($this, $session, $playerInfo, $authenticated, $location, $offlinePlayerData);
577 if(!$player->hasPlayedBefore()){
578 $player->onGround =
true;
580 $playerPromiseResolver->resolve($player);
583 if($playerPos ===
null){
584 $world->requestSafeSpawn()->onCompletion(
585 function(Position $spawn) use ($createPlayer, $playerPromiseResolver, $session, $world) :
void{
586 if(!$session->isConnected()){
587 $playerPromiseResolver->reject();
590 $createPlayer(Location::fromObject($spawn, $world));
592 function() use ($playerPromiseResolver, $session) : void{
593 if($session->isConnected()){
594 $session->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
596 $playerPromiseResolver->reject();
600 $createPlayer($playerPos);
603 return $playerPromiseResolver->getPromise();
618 $name = strtolower($name);
619 $delta = PHP_INT_MAX;
620 foreach($this->getOnlinePlayers() as $player){
621 if(stripos($player->getName(), $name) === 0){
622 $curDelta = strlen($player->getName()) - strlen($name);
623 if($curDelta < $delta){
640 $name = strtolower($name);
641 foreach($this->getOnlinePlayers() as $player){
642 if(strtolower($player->getName()) === $name){
654 return $this->playerList[$rawUUID] ?? null;
661 return $this->getPlayerByRawUUID($uuid->getBytes());
665 return $this->configGroup;
673 if(($command = $this->commandMap->getCommand($name)) instanceof
PluginOwned){
680 public function getNameBans() :
BanList{
681 return $this->banByName;
684 public function getIPBans() : BanList{
685 return $this->banByIP;
688 public function addOp(
string $name) : void{
689 $this->operators->set(strtolower($name), true);
691 if(($player = $this->getPlayerExact($name)) !==
null){
692 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR,
true);
694 $this->operators->save();
697 public function removeOp(
string $name) : void{
698 $lowercaseName = strtolower($name);
699 foreach($this->operators->getAll() as $operatorName => $_){
700 $operatorName = (string) $operatorName;
701 if($lowercaseName === strtolower($operatorName)){
702 $this->operators->remove($operatorName);
706 if(($player = $this->getPlayerExact($name)) !==
null){
707 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
709 $this->operators->save();
712 public function addWhitelist(
string $name) : void{
713 $this->whitelist->set(strtolower($name), true);
714 $this->whitelist->save();
717 public function removeWhitelist(
string $name) : void{
718 $this->whitelist->remove(strtolower($name));
719 $this->whitelist->save();
722 public function isWhitelisted(
string $name) : bool{
723 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
726 public function isOp(
string $name) : bool{
727 return $this->operators->exists($name, true);
730 public function getWhitelisted() : Config{
731 return $this->whitelist;
734 public function getOps() : Config{
735 return $this->operators;
742 $section = $this->configGroup->getProperty(Yml::ALIASES);
744 if(is_array($section)){
745 foreach($section as $key => $value){
747 if(is_array($value)){
750 $commands[] = (string) $value;
753 $result[$key] = $commands;
760 public static function getInstance() : Server{
761 if(self::$instance === null){
762 throw new \RuntimeException(
"Attempt to retrieve Server instance outside server thread");
764 return self::$instance;
767 public function __construct(
768 private ThreadSafeClassLoader $autoloader,
769 private AttachableThreadSafeLogger $logger,
773 if(self::$instance !==
null){
774 throw new \LogicException(
"Only one server instance can exist at once");
776 self::$instance = $this;
777 $this->startTime = microtime(
true);
778 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
779 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
782 $this->tickSleeper =
new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
784 $this->signalHandler =
new SignalHandler(
function() :
void{
785 $this->logger->info(
"Received signal interrupt, stopping the server");
793 Path::join($dataPath,
"worlds"),
794 Path::join($dataPath,
"players")
796 if(!file_exists($neededPath)){
797 mkdir($neededPath, 0777);
801 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
802 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
804 $this->logger->info(
"Loading server configuration");
805 $pocketmineYmlPath = Path::join($this->dataPath,
"pocketmine.yml");
806 if(!file_exists($pocketmineYmlPath)){
807 $content = Filesystem::fileGetContents(Path::join(\
pocketmine\RESOURCE_PATH,
"pocketmine.yml"));
808 if(VersionInfo::IS_DEVELOPMENT_BUILD){
809 $content = str_replace(
"preferred-channel: stable",
"preferred-channel: beta", $content);
811 @file_put_contents($pocketmineYmlPath, $content);
814 $this->configGroup =
new ServerConfigGroup(
815 new Config($pocketmineYmlPath, Config::YAML, []),
816 new Config(Path::join($this->dataPath,
"server.properties"), Config::PROPERTIES, [
817 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
818 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
819 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
820 ServerProperties::ENABLE_IPV6 =>
true,
821 ServerProperties::WHITELIST =>
false,
822 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
823 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name,
824 ServerProperties::FORCE_GAME_MODE =>
false,
825 ServerProperties::HARDCORE =>
false,
826 ServerProperties::PVP =>
true,
827 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
828 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS =>
"",
829 ServerProperties::DEFAULT_WORLD_NAME =>
"world",
830 ServerProperties::DEFAULT_WORLD_SEED =>
"",
831 ServerProperties::DEFAULT_WORLD_GENERATOR =>
"DEFAULT",
832 ServerProperties::ENABLE_QUERY =>
true,
833 ServerProperties::AUTO_SAVE =>
true,
834 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
835 ServerProperties::XBOX_AUTH =>
true,
836 ServerProperties::LANGUAGE =>
"eng"
840 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
841 if($this->logger instanceof MainLogger){
842 $this->logger->setLogDebug($debugLogLevel > 1);
845 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE,
false);
846 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString(
"settings.language", Language::FALLBACK_LANGUAGE));
848 $this->language =
new Language($selectedLang);
849 }
catch(LanguageNotFoundException $e){
850 $this->logger->error($e->getMessage());
852 $this->language =
new Language(Language::FALLBACK_LANGUAGE);
853 }
catch(LanguageNotFoundException $e){
854 $this->logger->emergency(
"Fallback language \"" . Language::FALLBACK_LANGUAGE .
"\" not found");
859 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
861 if(VersionInfo::IS_DEVELOPMENT_BUILD){
862 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS,
false)){
863 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
864 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
865 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
866 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
867 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5(
"https://github.com/pmmp/PocketMine-MP/releases")));
868 $this->forceShutdownExit();
873 $this->logger->warning(str_repeat(
"-", 40));
874 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
875 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
876 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
877 $this->logger->warning(str_repeat(
"-", 40));
880 $this->memoryManager =
new MemoryManager($this);
882 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
884 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS,
"auto")) ===
"auto"){
886 $processors = Utils::getCoreCount() - 2;
889 $poolSize = max(1, $processors);
892 $poolSize = max(1, (
int) $poolSize);
895 $this->asyncPool =
new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
897 $netCompressionThreshold = -1;
898 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
899 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
901 if($netCompressionThreshold < 0){
902 $netCompressionThreshold =
null;
905 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
906 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
907 $this->logger->warning(
"Invalid network compression level $netCompressionLevel set, setting to default 6");
908 $netCompressionLevel = 6;
910 ZlibCompressor::setInstance(
new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
912 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION,
true);
913 $this->networkCompressionAsyncThreshold = max(
914 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
915 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
918 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION,
true);
920 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK,
true) && Terminal::hasFormattingCodes();
922 $this->operators =
new Config(Path::join($this->dataPath,
"ops.txt"), Config::ENUM);
923 $this->whitelist =
new Config(Path::join($this->dataPath,
"white-list.txt"), Config::ENUM);
925 $bannedTxt = Path::join($this->dataPath,
"banned.txt");
926 $bannedPlayersTxt = Path::join($this->dataPath,
"banned-players.txt");
927 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
928 @rename($bannedTxt, $bannedPlayersTxt);
930 @touch($bannedPlayersTxt);
931 $this->banByName =
new BanList($bannedPlayersTxt);
932 $this->banByName->load();
933 $bannedIpsTxt = Path::join($this->dataPath,
"banned-ips.txt");
934 @touch($bannedIpsTxt);
935 $this->banByIP =
new BanList($bannedIpsTxt);
936 $this->banByIP->load();
938 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
940 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH,
true);
941 if($this->onlineMode){
942 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
944 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
945 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
946 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
949 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE,
false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
950 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
953 @cli_set_process_title($this->getName() .
" " . $this->getPocketMineVersion());
955 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
957 $this->logger->debug(
"Server unique id: " . $this->getServerUniqueId());
958 $this->logger->debug(
"Machine unique id: " . Utils::getMachineUniqueId());
960 $this->network =
new Network($this->logger);
961 $this->network->setName($this->getMotd());
963 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
965 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW :
"") . $this->getPocketMineVersion() . TextFormat::RESET
967 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
969 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING,
false));
970 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
972 DefaultPermissions::registerCorePermissions();
974 $this->commandMap =
new SimpleCommandMap($this);
976 $this->craftingManager = CraftingManagerFromDataHelper::make(Path::join(\
pocketmine\BEDROCK_DATA_PATH,
"recipes"));
978 $this->resourceManager =
new ResourcePackManager(Path::join($this->dataPath,
"resource_packs"), $this->logger);
980 $pluginGraylist =
null;
981 $graylistFile = Path::join($this->dataPath,
"plugin_list.yml");
982 if(!file_exists($graylistFile)){
983 copy(Path::join(\
pocketmine\RESOURCE_PATH,
'plugin_list.yml'), $graylistFile);
986 $pluginGraylist = PluginGraylist::fromArray(yaml_parse(Filesystem::fileGetContents($graylistFile)));
987 }
catch(\InvalidArgumentException $e){
988 $this->logger->emergency(
"Failed to load $graylistFile: " . $e->getMessage());
989 $this->forceShutdownExit();
992 $this->pluginManager =
new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR,
true) ?
null : Path::join($this->dataPath,
"plugin_data"), $pluginGraylist);
993 $this->pluginManager->registerInterface(
new PharPluginLoader($this->autoloader));
994 $this->pluginManager->registerInterface(
new ScriptPluginLoader());
995 $this->pluginManager->registerInterface(
new FolderPluginLoader($this->autoloader));
997 $providerManager =
new WorldProviderManager();
999 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT,
""))) !==
null &&
1000 $format instanceof WritableWorldProviderManagerEntry
1002 $providerManager->setDefault($format);
1003 }elseif($formatName !==
""){
1004 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1007 $this->worldManager =
new WorldManager($this, Path::join($this->dataPath,
"worlds"), $providerManager);
1008 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1009 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1011 $this->updater =
new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST,
"update.pmmp.io"));
1013 $this->queryInfo =
new QueryInfo($this);
1015 $this->playerDataProvider =
new DatFilePlayerDataProvider(Path::join($this->dataPath,
"players"));
1017 register_shutdown_function($this->crashDump(...));
1019 $loadErrorCount = 0;
1020 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1021 if($loadErrorCount > 0){
1022 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1023 $this->forceShutdownExit();
1026 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1027 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1028 $this->forceShutdownExit();
1032 if(!$this->startupPrepareWorlds()){
1033 $this->forceShutdownExit();
1037 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1038 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1039 $this->forceShutdownExit();
1043 if(!$this->startupPrepareNetworkInterfaces()){
1044 $this->forceShutdownExit();
1048 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED,
true)){
1049 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1050 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1053 $this->configGroup->save();
1055 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1056 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_donate(TextFormat::AQUA .
"https://patreon.com/pocketminemp" . TextFormat::RESET)));
1057 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(
true) - $this->startTime, 3)))));
1059 $forwarder =
new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1060 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1061 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1064 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT,
true)){
1065 $this->console =
new ConsoleReaderChildProcessDaemon($this->logger);
1068 $this->tickProcessor();
1069 $this->forceShutdown();
1070 }
catch(\Throwable $e){
1071 $this->exceptionHandler($e);
1075 private function startupPrepareWorlds() : bool{
1076 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1077 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1078 if($generatorEntry ===
null){
1079 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1081 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1086 $generatorEntry->validateGeneratorOptions($generatorOptions);
1087 }
catch(InvalidGeneratorOptionsException $e){
1088 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1090 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1094 return $generatorEntry->getGeneratorClass();
1097 $anyWorldFailedToLoad =
false;
1099 foreach((array) $this->configGroup->getProperty(Yml::WORLDS, []) as $name => $options){
1100 if($options === null){
1102 }elseif(!is_array($options)){
1106 if(!$this->worldManager->loadWorld($name,
true)){
1107 if($this->worldManager->isWorldGenerated($name)){
1109 $anyWorldFailedToLoad = true;
1112 $creationOptions = WorldCreationOptions::create();
1115 $generatorName = $options[
"generator"] ??
"default";
1116 $generatorOptions = isset($options[
"preset"]) && is_string($options[
"preset"]) ? $options[
"preset"] :
"";
1118 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1119 if($generatorClass ===
null){
1120 $anyWorldFailedToLoad =
true;
1123 $creationOptions->setGeneratorClass($generatorClass);
1124 $creationOptions->setGeneratorOptions($generatorOptions);
1126 $creationOptions->setDifficulty($this->getDifficulty());
1127 if(isset($options[
"difficulty"]) && is_string($options[
"difficulty"])){
1128 $creationOptions->setDifficulty(World::getDifficultyFromString($options[
"difficulty"]));
1131 if(isset($options[
"seed"])){
1132 $convertedSeed = Generator::convertSeed((
string) ($options[
"seed"] ??
""));
1133 if($convertedSeed !==
null){
1134 $creationOptions->setSeed($convertedSeed);
1138 $this->worldManager->generateWorld($name, $creationOptions);
1142 if($this->worldManager->getDefaultWorld() ===
null){
1143 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1144 if(trim($default) ==
""){
1145 $this->logger->warning(
"level-name cannot be null, using default");
1147 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1149 if(!$this->worldManager->loadWorld($default,
true)){
1150 if($this->worldManager->isWorldGenerated($default)){
1151 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1155 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1156 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1157 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1159 if($generatorClass ===
null){
1160 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1163 $creationOptions = WorldCreationOptions::create()
1164 ->setGeneratorClass($generatorClass)
1165 ->setGeneratorOptions($generatorOptions);
1166 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1167 if($convertedSeed !==
null){
1168 $creationOptions->setSeed($convertedSeed);
1170 $creationOptions->setDifficulty($this->getDifficulty());
1171 $this->worldManager->generateWorld($default, $creationOptions);
1174 $world = $this->worldManager->getWorldByName($default);
1175 if($world ===
null){
1176 throw new AssumptionFailedError(
"We just loaded/generated the default world, so it must exist");
1178 $this->worldManager->setDefaultWorld($world);
1181 return !$anyWorldFailedToLoad;
1184 private function startupPrepareConnectableNetworkInterfaces(
1189 PacketBroadcaster $packetBroadcaster,
1190 EntityEventBroadcaster $entityEventBroadcaster,
1191 TypeConverter $typeConverter
1193 $prettyIp = $ipV6 ?
"[$ip]" : $ip;
1195 $rakLibRegistered = $this->network->registerInterface(
new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1196 }
catch(NetworkInterfaceStartException $e){
1197 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1204 if($rakLibRegistered){
1205 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (
string) $port)));
1208 if(!$rakLibRegistered){
1211 $this->network->registerInterface(
new DedicatedQueryNetworkInterface($ip, $port, $ipV6,
new \
PrefixedLogger($this->logger,
"Dedicated Query Interface")));
1213 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (
string) $port)));
1218 private function startupPrepareNetworkInterfaces() : bool{
1219 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1221 $typeConverter = TypeConverter::getInstance();
1222 $packetBroadcaster =
new StandardPacketBroadcaster($this);
1223 $entityEventBroadcaster =
new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1226 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(),
false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1228 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6,
true) &&
1229 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(),
true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1236 $this->network->registerRawPacketHandler(
new QueryHandler($this));
1239 foreach($this->getIPBans()->getEntries() as $entry){
1240 $this->network->blockAddress($entry->getName(), -1);
1243 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING,
false)){
1244 $this->network->registerInterface(
new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1255 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1262 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1263 if(count($this->broadcastSubscribers[$channelId]) === 1){
1264 unset($this->broadcastSubscribers[$channelId]);
1266 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1275 foreach(
Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1276 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1287 return $this->broadcastSubscribers[$channelId] ?? [];
1294 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1296 foreach($recipients as $recipient){
1297 $recipient->sendMessage($message);
1300 return count($recipients);
1306 private function getPlayerBroadcastSubscribers(
string $channelId) : array{
1309 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1310 if($subscriber instanceof Player){
1311 $players[spl_object_id($subscriber)] = $subscriber;
1320 public function broadcastTip(
string $tip, ?array $recipients =
null) : int{
1321 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1323 foreach($recipients as $recipient){
1324 $recipient->sendTip($tip);
1327 return count($recipients);
1334 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1336 foreach($recipients as $recipient){
1337 $recipient->sendPopup($popup);
1340 return count($recipients);
1349 public function broadcastTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1, ?array $recipients =
null) : int{
1350 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1352 foreach($recipients as $recipient){
1353 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1356 return count($recipients);
1372 public function prepareBatch(
string $buffer, Compressor $compressor, ?
bool $sync =
null, ?TimingsHandler $timings =
null) : CompressBatchPromise|string{
1373 $timings ??= Timings::$playerNetworkSendCompress;
1375 $timings->startTiming();
1377 $threshold = $compressor->getCompressionThreshold();
1378 if($threshold ===
null || strlen($buffer) < $compressor->getCompressionThreshold()){
1379 $compressionType = CompressionAlgorithm::NONE;
1380 $compressed = $buffer;
1383 $sync ??= !$this->networkCompressionAsync;
1385 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1386 $promise =
new CompressBatchPromise();
1387 $task =
new CompressBatchTask($buffer, $promise, $compressor);
1388 $this->asyncPool->submitTask($task);
1392 $compressionType = $compressor->getNetworkId();
1393 $compressed = $compressor->compress($buffer);
1396 return chr($compressionType) . $compressed;
1398 $timings->stopTiming();
1402 public function enablePlugins(PluginEnableOrder $type) : bool{
1404 foreach($this->pluginManager->getPlugins() as $plugin){
1405 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1406 if(!$this->pluginManager->enablePlugin($plugin)){
1407 $allSuccess =
false;
1412 if($type === PluginEnableOrder::POSTWORLD){
1413 $this->commandMap->registerServerAliases();
1426 if($ev->isCancelled()){
1430 $commandLine = $ev->getCommand();
1433 return $this->commandMap->dispatch($sender, $commandLine);
1440 if($this->isRunning){
1441 $this->isRunning =
false;
1442 $this->signalHandler->unregister();
1446 private function forceShutdownExit() : void{
1447 $this->forceShutdown();
1448 Process::kill(Process::pid());
1451 public function forceShutdown() : void{
1452 if($this->hasStopped){
1456 if($this->doTitleTick){
1460 if($this->isRunning){
1461 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1464 if(!$this->isRunning()){
1465 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1468 $this->hasStopped =
true;
1472 if(isset($this->pluginManager)){
1473 $this->logger->debug(
"Disabling all plugins");
1474 $this->pluginManager->disablePlugins();
1477 if(isset($this->network)){
1478 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE,
"Server closed"));
1481 if(isset($this->worldManager)){
1482 $this->logger->debug(
"Unloading all worlds");
1483 foreach($this->worldManager->getWorlds() as $world){
1484 $this->worldManager->unloadWorld($world,
true);
1488 $this->logger->debug(
"Removing event handlers");
1489 HandlerListManager::global()->unregisterAll();
1491 if(isset($this->asyncPool)){
1492 $this->logger->debug(
"Shutting down async task worker pool");
1493 $this->asyncPool->shutdown();
1496 if(isset($this->configGroup)){
1497 $this->logger->debug(
"Saving properties");
1498 $this->configGroup->save();
1501 if($this->console !==
null){
1502 $this->logger->debug(
"Closing console");
1503 $this->console->quit();
1506 if(isset($this->network)){
1507 $this->logger->debug(
"Stopping network interfaces");
1508 foreach($this->network->getInterfaces() as $interface){
1509 $this->logger->debug(
"Stopping network interface " . get_class($interface));
1510 $this->network->unregisterInterface($interface);
1513 }
catch(\Throwable $e){
1514 $this->logger->logException($e);
1515 $this->logger->emergency(
"Crashed while crashing, killing process");
1516 @Process::kill(Process::pid());
1521 public function getQueryInformation() : QueryInfo{
1522 return $this->queryInfo;
1530 while(@ob_end_flush()){}
1533 if($trace ===
null){
1534 $trace = $e->getTrace();
1540 $this->logger->logException($e, $trace);
1542 if($e instanceof ThreadCrashException){
1543 $info = $e->getCrashInfo();
1544 $type = $info->getType();
1545 $errstr = $info->getMessage();
1546 $errfile = $info->getFile();
1547 $errline = $info->getLine();
1548 $printableTrace = $info->getTrace();
1549 $thread = $info->getThreadName();
1551 $type = get_class($e);
1552 $errstr = $e->getMessage();
1553 $errfile = $e->getFile();
1554 $errline = $e->getLine();
1555 $printableTrace = Utils::printableTraceWithMetadata($trace);
1559 $errstr = preg_replace(
'/\s+/',
' ', trim($errstr));
1563 "message" => $errstr,
1564 "fullFile" => $errfile,
1565 "file" => Filesystem::cleanPath($errfile),
1567 "trace" => $printableTrace,
1571 global $lastExceptionError, $lastError;
1572 $lastExceptionError = $lastError;
1576 private function writeCrashDumpFile(CrashDump $dump) : string{
1577 $crashFolder = Path::join($this->dataPath,
"crashdumps");
1578 if(!is_dir($crashFolder)){
1579 mkdir($crashFolder);
1581 $crashDumpPath = Path::join($crashFolder, date(
"D_M_j-H.i.s-T_Y", (
int) $dump->getData()->time) .
".log");
1583 $fp = @fopen($crashDumpPath,
"wb");
1584 if(!is_resource($fp)){
1585 throw new \RuntimeException(
"Unable to open new file to generate crashdump");
1587 $writer =
new CrashDumpRenderer($fp, $dump->getData());
1588 $writer->renderHumanReadable();
1589 $dump->encodeData($writer);
1592 return $crashDumpPath;
1595 public function crashDump() : void{
1596 while(@ob_end_flush()){}
1597 if(!$this->isRunning){
1600 if($this->sendUsageTicker > 0){
1601 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1603 $this->hasStopped =
false;
1605 ini_set(
"error_reporting",
'0');
1606 ini_set(
"memory_limit",
'-1');
1608 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1609 $dump =
new CrashDump($this, $this->pluginManager ??
null);
1611 $crashDumpPath = $this->writeCrashDumpFile($dump);
1613 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1615 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED,
true)){
1618 $stamp = Path::join($this->dataPath,
"crashdumps",
".last_crash");
1619 $crashInterval = 120;
1620 if(($lastReportTime = @filemtime($stamp)) !==
false && $lastReportTime + $crashInterval >= time()){
1622 $this->logger->debug(
"Not sending crashdump due to last crash less than $crashInterval seconds ago");
1626 if($dump->getData()->error[
"type"] === \ParseError::class){
1630 if(strrpos(VersionInfo::GIT_HASH(),
"-dirty") !==
false || VersionInfo::GIT_HASH() === str_repeat(
"00", 20)){
1631 $this->logger->debug(
"Not sending crashdump due to locally modified");
1636 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS,
true) ?
"https" :
"http") .
"://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST,
"crash.pmmp.io") .
"/submit/api";
1637 $postUrlError =
"Unknown error";
1638 $reply = Internet::postURL($url, [
1640 "name" => $this->getName() .
" " . $this->getPocketMineVersion(),
1642 "reportPaste" => base64_encode($dump->getEncodedData())
1643 ], 10, [], $postUrlError);
1645 if($reply !==
null && is_object($data = json_decode($reply->getBody()))){
1646 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1647 $reportId = $data->crashId;
1648 $reportUrl = $data->crashUrl;
1649 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (
string) $reportId)));
1650 }elseif(isset($data->error) && is_string($data->error)){
1651 $this->logger->emergency(
"Automatic crash report submission failed: $data->error");
1653 $this->logger->emergency(
"Invalid JSON response received from crash archive: " . $reply->getBody());
1656 $this->logger->emergency(
"Failed to communicate with crash archive: $postUrlError");
1660 }
catch(\Throwable $e){
1661 $this->logger->logException($e);
1663 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1664 }
catch(\Throwable $e){}
1667 $this->forceShutdown();
1668 $this->isRunning =
false;
1671 $uptime = time() - ((int) $this->startTime);
1673 $spacing = $minUptime - $uptime;
1675 echo
"--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1678 @Process::kill(Process::pid());
1690 return $this->tickSleeper;
1693 private function tickProcessor() : void{
1694 $this->nextTick = microtime(true);
1696 while($this->isRunning){
1700 $this->tickSleeper->sleepUntil($this->nextTick);
1704 public function addOnlinePlayer(Player $player) : bool{
1705 $ev = new PlayerLoginEvent($player,
"Plugin reason");
1707 if($ev->isCancelled() || !$player->isConnected()){
1708 $player->disconnect($ev->getKickMessage());
1713 $session = $player->getNetworkSession();
1714 $position = $player->getPosition();
1715 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1716 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1718 (
string) $session->getPort(),
1719 (
string) $player->getId(),
1720 $position->getWorld()->getDisplayName(),
1721 (
string) round($position->x, 4),
1722 (
string) round($position->y, 4),
1723 (
string) round($position->z, 4)
1726 foreach($this->playerList as $p){
1727 $p->getNetworkSession()->onPlayerAdded($player);
1729 $rawUUID = $player->getUniqueId()->getBytes();
1730 $this->playerList[$rawUUID] = $player;
1732 if($this->sendUsageTicker > 0){
1733 $this->uniquePlayers[$rawUUID] = $rawUUID;
1739 public function removeOnlinePlayer(Player $player) : void{
1740 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1741 unset($this->playerList[$rawUUID]);
1742 foreach($this->playerList as $p){
1743 $p->getNetworkSession()->onPlayerRemoved($player);
1748 public function sendUsage(
int $type = SendUsageTask::TYPE_STATUS) : void{
1749 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1750 $this->asyncPool->submitTask(
new SendUsageTask($this, $type, $this->uniquePlayers));
1752 $this->uniquePlayers = [];
1755 public function getLanguage() : Language{
1756 return $this->language;
1759 public function isLanguageForced() : bool{
1760 return $this->forceLanguage;
1763 public function getNetwork() : Network{
1764 return $this->network;
1767 public function getMemoryManager() : MemoryManager{
1768 return $this->memoryManager;
1771 private function titleTick() : void{
1772 Timings::$titleTick->startTiming();
1774 $u = Process::getAdvancedMemoryUsage();
1775 $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());
1777 $online = count($this->playerList);
1778 $connecting = $this->network->getConnectionCount() - $online;
1779 $bandwidthStats = $this->network->getBandwidthTracker();
1781 echo
"\x1b]0;" . $this->getName() .
" " .
1782 $this->getPocketMineVersion() .
1783 " | Online $online/" . $this->maxPlayers .
1784 ($connecting > 0 ?
" (+$connecting connecting)" :
"") .
1785 " | Memory " . $usage .
1786 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1787 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1788 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1789 " | Load " . $this->getTickUsageAverage() .
"%\x07";
1791 Timings::$titleTick->stopTiming();
1797 private function tick() : void{
1798 $tickTime = microtime(true);
1799 if(($tickTime - $this->nextTick) < -0.025){
1803 Timings::$serverTick->startTiming();
1805 ++$this->tickCounter;
1807 Timings::$scheduler->startTiming();
1808 $this->pluginManager->tickSchedulers($this->tickCounter);
1809 Timings::$scheduler->stopTiming();
1811 Timings::$schedulerAsync->startTiming();
1812 $this->asyncPool->collectTasks();
1813 Timings::$schedulerAsync->stopTiming();
1815 $this->worldManager->tick($this->tickCounter);
1817 Timings::$connection->startTiming();
1818 $this->network->tick();
1819 Timings::$connection->stopTiming();
1821 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1822 if($this->doTitleTick){
1825 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1826 $this->currentUse = 0;
1828 $queryRegenerateEvent =
new QueryRegenerateEvent(
new QueryInfo($this));
1829 $queryRegenerateEvent->call();
1830 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1832 $this->network->updateName();
1833 $this->network->getBandwidthTracker()->rotateAverageHistory();
1836 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1837 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1838 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1841 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1842 foreach($this->worldManager->getWorlds() as $world){
1843 $world->clearCache();
1847 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1848 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1851 $this->memoryManager->check();
1853 if($this->console !==
null){
1854 Timings::$serverCommand->startTiming();
1855 while(($line = $this->console->readLine()) !==
null){
1856 $this->consoleSender ??=
new ConsoleCommandSender($this, $this->language);
1857 $this->dispatchCommand($this->consoleSender, $line);
1859 Timings::$serverCommand->stopTiming();
1862 Timings::$serverTick->stopTiming();
1864 $now = microtime(
true);
1865 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1866 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1867 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1869 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1871 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1872 $this->tickAverage[$idx] = $this->currentTPS;
1873 $this->useAverage[$idx] = $this->currentUse;
1874 $this->tickSleeper->resetNotificationProcessingTime();
1876 if(($this->nextTick - $tickTime) < -1){
1877 $this->nextTick = $tickTime;
1879 $this->nextTick += self::TARGET_SECONDS_PER_TICK;