188 public const BROADCAST_CHANNEL_ADMINISTRATIVE =
"pocketmine.broadcast.admin";
189 public const BROADCAST_CHANNEL_USERS =
"pocketmine.broadcast.user";
191 public const DEFAULT_SERVER_NAME = VersionInfo::NAME .
" Server";
192 public const DEFAULT_MAX_PLAYERS = 20;
193 public const DEFAULT_PORT_IPV4 = 19132;
194 public const DEFAULT_PORT_IPV6 = 19133;
195 public const DEFAULT_MAX_VIEW_DISTANCE = 16;
202 public const TARGET_TICKS_PER_SECOND = 20;
206 public const TARGET_SECONDS_PER_TICK = 1 / self::TARGET_TICKS_PER_SECOND;
207 public const TARGET_NANOSECONDS_PER_TICK = 1_000_000_000 / self::TARGET_TICKS_PER_SECOND;
212 private const TPS_OVERLOAD_WARNING_THRESHOLD = self::TARGET_TICKS_PER_SECOND * 0.6;
214 private const TICKS_PER_WORLD_CACHE_CLEAR = 5 * self::TARGET_TICKS_PER_SECOND;
215 private const TICKS_PER_TPS_OVERLOAD_WARNING = 5 * self::TARGET_TICKS_PER_SECOND;
216 private const TICKS_PER_STATS_REPORT = 300 * self::TARGET_TICKS_PER_SECOND;
218 private const DEFAULT_ASYNC_COMPRESSION_THRESHOLD = 10_000;
220 private static ?
Server $instance =
null;
228 private Config $operators;
230 private Config $whitelist;
232 private bool $isRunning =
true;
234 private bool $hasStopped =
false;
238 private float $profilingTickRate = self::TARGET_TICKS_PER_SECOND;
245 private int $tickCounter = 0;
246 private float $nextTick = 0;
248 private array $tickAverage;
250 private array $useAverage;
251 private float $currentTPS = self::TARGET_TICKS_PER_SECOND;
252 private float $currentUse = 0;
253 private float $startTime;
255 private bool $doTitleTick =
true;
257 private int $sendUsageTicker = 0;
272 private int $maxPlayers;
274 private bool $onlineMode =
true;
278 private bool $networkCompressionAsync =
true;
279 private int $networkCompressionAsyncThreshold = self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD;
282 private bool $forceLanguage =
false;
284 private UuidInterface $serverID;
286 private string $dataPath;
287 private string $pluginPath;
295 private array $uniquePlayers = [];
302 private array $playerList = [];
310 private array $broadcastSubscribers = [];
312 public function getName() : string{
316 public function isRunning() : bool{
317 return $this->isRunning;
320 public function getPocketMineVersion() : string{
321 return VersionInfo::VERSION()->getFullVersion(true);
324 public function getVersion() : string{
325 return ProtocolInfo::MINECRAFT_VERSION;
328 public function getApiVersion() : string{
329 return VersionInfo::BASE_VERSION;
332 public function getFilePath() : string{
336 public function getResourcePath() : string{
340 public function getDataPath() : string{
341 return $this->dataPath;
344 public function getPluginPath() : string{
345 return $this->pluginPath;
348 public function getMaxPlayers() : int{
349 return $this->maxPlayers;
352 public function setMaxPlayers(
int $maxPlayers) : void{
353 $this->maxPlayers = $maxPlayers;
361 return $this->onlineMode;
368 return $this->getOnlineMode();
371 public function getPort() : int{
372 return $this->configGroup->getConfigInt(
ServerProperties::SERVER_PORT_IPV4, self::DEFAULT_PORT_IPV4);
375 public function getPortV6() : int{
376 return $this->configGroup->getConfigInt(ServerProperties::SERVER_PORT_IPV6, self::DEFAULT_PORT_IPV6);
379 public function getViewDistance() : int{
380 return max(2, $this->configGroup->getConfigInt(ServerProperties::VIEW_DISTANCE, self::DEFAULT_MAX_VIEW_DISTANCE));
387 return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance())));
390 public function getIp() : string{
392 return $str !==
"" ? $str :
"0.0.0.0";
395 public function getIpV6() : string{
396 $str = $this->configGroup->getConfigString(ServerProperties::SERVER_IPV6);
397 return $str !==
"" ? $str :
"::";
400 public function getServerUniqueId() : UuidInterface{
401 return $this->serverID;
404 public function getGamemode() : GameMode{
405 return GameMode::fromString($this->configGroup->getConfigString(ServerProperties::GAME_MODE)) ?? GameMode::SURVIVAL;
408 public function getForceGamemode() : bool{
409 return $this->configGroup->getConfigBool(ServerProperties::FORCE_GAME_MODE, false);
419 public function hasWhitelist() : bool{
420 return $this->configGroup->getConfigBool(
ServerProperties::WHITELIST, false);
423 public function isHardcore() : bool{
424 return $this->configGroup->getConfigBool(ServerProperties::HARDCORE, false);
427 public function getMotd() : string{
428 return $this->configGroup->getConfigString(ServerProperties::MOTD, self::DEFAULT_SERVER_NAME);
431 public function getLoader() : ThreadSafeClassLoader{
432 return $this->autoloader;
435 public function getLogger() : AttachableThreadSafeLogger{
436 return $this->logger;
439 public function getUpdater() : UpdateChecker{
440 return $this->updater;
443 public function getPluginManager() : PluginManager{
444 return $this->pluginManager;
447 public function getCraftingManager() : CraftingManager{
448 return $this->craftingManager;
451 public function getResourcePackManager() : ResourcePackManager{
452 return $this->resourceManager;
455 public function getWorldManager() : WorldManager{
456 return $this->worldManager;
459 public function getAsyncPool() : AsyncPool{
460 return $this->asyncPool;
463 public function getTick() : int{
464 return $this->tickCounter;
471 return round($this->currentTPS, 2);
478 return round(array_sum($this->tickAverage) / count($this->tickAverage), 2);
485 return round($this->currentUse * 100, 2);
492 return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2);
495 public function getStartTime() : float{
496 return $this->startTime;
499 public function getCommandMap() : SimpleCommandMap{
500 return $this->commandMap;
507 return $this->playerList;
510 public function shouldSavePlayerData() : bool{
511 return $this->configGroup->getPropertyBool(Yml::PLAYER_SAVE_PLAYER_DATA, true);
514 public function getOfflinePlayer(
string $name) : Player|OfflinePlayer|null{
515 $name = strtolower($name);
516 $result = $this->getPlayerExact($name);
518 if($result ===
null){
519 $result =
new OfflinePlayer($name, $this->getOfflinePlayerData($name));
529 return $this->playerDataProvider->hasData($name);
532 public function getOfflinePlayerData(
string $name) : ?
CompoundTag{
535 return $this->playerDataProvider->loadData($name);
536 }
catch(PlayerDataLoadException $e){
537 $this->logger->debug(
"Failed to load player data for $name: " . $e->getMessage());
538 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_data_playerCorrupted($name)));
544 public function saveOfflinePlayerData(
string $name, CompoundTag $nbtTag) : void{
545 $ev = new PlayerDataSaveEvent($nbtTag, $name, $this->getPlayerExact($name));
546 if(!$this->shouldSavePlayerData()){
552 if(!$ev->isCancelled()){
553 Timings::$syncPlayerDataSave->time(function() use ($name, $ev) : void{
555 $this->playerDataProvider->saveData($name, $ev->getSaveData());
556 }catch(PlayerDataSaveException $e){
557 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_data_saveError($name, $e->getMessage())));
558 $this->logger->logException($e);
570 $class = $ev->getPlayerClass();
572 if($offlinePlayerData !==
null && ($world = $this->worldManager->getWorldByName($offlinePlayerData->getString(Player::TAG_LEVEL,
""))) !==
null){
573 $playerPos = EntityDataHelper::parseLocation($offlinePlayerData, $world);
575 $world = $this->worldManager->getDefaultWorld();
577 throw new AssumptionFailedError(
"Default world should always be loaded");
584 $createPlayer =
function(
Location $location) use ($playerPromiseResolver, $class, $session, $playerInfo, $authenticated, $offlinePlayerData) :
void{
586 $player =
new $class($this, $session, $playerInfo, $authenticated, $location, $offlinePlayerData);
587 if(!$player->hasPlayedBefore()){
588 $player->onGround =
true;
590 $playerPromiseResolver->resolve($player);
593 if($playerPos ===
null){
594 $world->requestSafeSpawn()->onCompletion(
595 function(Position $spawn) use ($createPlayer, $playerPromiseResolver, $session, $world) :
void{
596 if(!$session->isConnected()){
597 $playerPromiseResolver->reject();
600 $createPlayer(Location::fromObject($spawn, $world));
602 function() use ($playerPromiseResolver, $session) : void{
603 if($session->isConnected()){
604 $session->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
606 $playerPromiseResolver->reject();
610 $createPlayer($playerPos);
613 return $playerPromiseResolver->getPromise();
628 $name = strtolower($name);
629 $delta = PHP_INT_MAX;
630 foreach($this->getOnlinePlayers() as $player){
631 if(stripos($player->getName(), $name) === 0){
632 $curDelta = strlen($player->getName()) - strlen($name);
633 if($curDelta < $delta){
650 $name = strtolower($name);
651 foreach($this->getOnlinePlayers() as $player){
652 if(strtolower($player->getName()) === $name){
664 return $this->playerList[$rawUUID] ?? null;
671 return $this->getPlayerByRawUUID($uuid->getBytes());
675 return $this->configGroup;
683 if(($command = $this->commandMap->getCommand($name)) instanceof
PluginOwned){
690 public function getNameBans() :
BanList{
691 return $this->banByName;
694 public function getIPBans() : BanList{
695 return $this->banByIP;
698 public function addOp(
string $name) : void{
699 $this->operators->set(strtolower($name), true);
701 if(($player = $this->getPlayerExact($name)) !==
null){
702 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR,
true);
704 $this->operators->save();
707 public function removeOp(
string $name) : void{
708 $lowercaseName = strtolower($name);
709 foreach(Utils::promoteKeys($this->operators->getAll()) as $operatorName => $_){
710 $operatorName = (string) $operatorName;
711 if($lowercaseName === strtolower($operatorName)){
712 $this->operators->remove($operatorName);
716 if(($player = $this->getPlayerExact($name)) !==
null){
717 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
719 $this->operators->save();
722 public function addWhitelist(
string $name) : void{
723 $this->whitelist->set(strtolower($name), true);
724 $this->whitelist->save();
727 public function removeWhitelist(
string $name) : void{
728 $this->whitelist->remove(strtolower($name));
729 $this->whitelist->save();
732 public function isWhitelisted(
string $name) : bool{
733 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
736 public function isOp(
string $name) : bool{
737 return $this->operators->exists($name, true);
740 public function getWhitelisted() : Config{
741 return $this->whitelist;
744 public function getOps() : Config{
745 return $this->operators;
753 $section = $this->configGroup->getProperty(Yml::ALIASES);
755 if(is_array($section)){
756 foreach(Utils::promoteKeys($section) as $key => $value){
760 if(is_array($value)){
763 $commands[] = (string) $value;
766 $result[(string) $key] = $commands;
773 public static function getInstance() : Server{
774 if(self::$instance === null){
775 throw new \RuntimeException(
"Attempt to retrieve Server instance outside server thread");
777 return self::$instance;
780 public function __construct(
781 private ThreadSafeClassLoader $autoloader,
782 private AttachableThreadSafeLogger $logger,
786 if(self::$instance !==
null){
787 throw new \LogicException(
"Only one server instance can exist at once");
789 self::$instance = $this;
790 $this->startTime = microtime(
true);
791 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
792 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
795 $this->tickSleeper =
new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
797 $this->signalHandler =
new SignalHandler(
function() :
void{
798 $this->logger->info(
"Received signal interrupt, stopping the server");
806 Path::join($dataPath,
"worlds"),
807 Path::join($dataPath,
"players")
809 if(!file_exists($neededPath)){
810 mkdir($neededPath, 0777);
814 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
815 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
817 $this->logger->info(
"Loading server configuration");
818 $pocketmineYmlPath = Path::join($this->dataPath,
"pocketmine.yml");
819 if(!file_exists($pocketmineYmlPath)){
820 $content = Filesystem::fileGetContents(Path::join(\
pocketmine\RESOURCE_PATH,
"pocketmine.yml"));
821 if(VersionInfo::IS_DEVELOPMENT_BUILD){
822 $content = str_replace(
"preferred-channel: stable",
"preferred-channel: beta", $content);
824 @file_put_contents($pocketmineYmlPath, $content);
827 $this->configGroup =
new ServerConfigGroup(
828 new Config($pocketmineYmlPath, Config::YAML, []),
829 new Config(Path::join($this->dataPath,
"server.properties"), Config::PROPERTIES, [
830 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
831 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
832 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
833 ServerProperties::ENABLE_IPV6 =>
true,
834 ServerProperties::WHITELIST =>
false,
835 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
836 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name,
837 ServerProperties::FORCE_GAME_MODE =>
false,
838 ServerProperties::HARDCORE =>
false,
839 ServerProperties::PVP =>
true,
840 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
841 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS =>
"",
842 ServerProperties::DEFAULT_WORLD_NAME =>
"world",
843 ServerProperties::DEFAULT_WORLD_SEED =>
"",
844 ServerProperties::DEFAULT_WORLD_GENERATOR =>
"DEFAULT",
845 ServerProperties::ENABLE_QUERY =>
true,
846 ServerProperties::AUTO_SAVE =>
true,
847 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
848 ServerProperties::XBOX_AUTH =>
true,
849 ServerProperties::LANGUAGE =>
"eng"
853 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
854 if($this->logger instanceof MainLogger){
855 $this->logger->setLogDebug($debugLogLevel > 1);
858 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE,
false);
859 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString(
"settings.language", Language::FALLBACK_LANGUAGE));
861 $this->language =
new Language($selectedLang);
862 }
catch(LanguageNotFoundException $e){
863 $this->logger->error($e->getMessage());
865 $this->language =
new Language(Language::FALLBACK_LANGUAGE);
866 }
catch(LanguageNotFoundException $e){
867 $this->logger->emergency(
"Fallback language \"" . Language::FALLBACK_LANGUAGE .
"\" not found");
872 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
874 if(VersionInfo::IS_DEVELOPMENT_BUILD){
875 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS,
false)){
876 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
877 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
878 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
879 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
880 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5(
"https://github.com/pmmp/PocketMine-MP/releases")));
881 $this->forceShutdownExit();
886 $this->logger->warning(str_repeat(
"-", 40));
887 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
888 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
889 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
890 $this->logger->warning(str_repeat(
"-", 40));
893 $this->memoryManager =
new MemoryManager($this);
895 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
897 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS,
"auto")) ===
"auto"){
899 $processors = Utils::getCoreCount() - 2;
902 $poolSize = max(1, $processors);
905 $poolSize = max(1, (
int) $poolSize);
908 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING,
false));
909 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
911 $this->asyncPool =
new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
912 $this->asyncPool->addWorkerStartHook(
function(
int $i) :
void{
913 if(TimingsHandler::isEnabled()){
914 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled(
true), $i);
917 TimingsHandler::getToggleCallbacks()->add(
function(
bool $enable) :
void{
918 foreach($this->asyncPool->getRunningWorkers() as $workerId){
919 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled($enable), $workerId);
922 TimingsHandler::getReloadCallbacks()->add(
function() :
void{
923 foreach($this->asyncPool->getRunningWorkers() as $workerId){
924 $this->asyncPool->submitTaskToWorker(TimingsControlTask::reload(), $workerId);
927 TimingsHandler::getCollectCallbacks()->add(
function() : array{
929 foreach($this->asyncPool->getRunningWorkers() as $workerId){
931 $resolver =
new PromiseResolver();
932 $this->asyncPool->submitTaskToWorker(
new TimingsCollectionTask($resolver), $workerId);
934 $promises[] = $resolver->getPromise();
940 $netCompressionThreshold = -1;
941 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
942 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
944 if($netCompressionThreshold < 0){
945 $netCompressionThreshold =
null;
948 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
949 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
950 $this->logger->warning(
"Invalid network compression level $netCompressionLevel set, setting to default 6");
951 $netCompressionLevel = 6;
953 ZlibCompressor::setInstance(
new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
955 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION,
true);
956 $this->networkCompressionAsyncThreshold = max(
957 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
958 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
961 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION,
true);
963 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK,
true) && Terminal::hasFormattingCodes();
965 $this->operators =
new Config(Path::join($this->dataPath,
"ops.txt"), Config::ENUM);
966 $this->whitelist =
new Config(Path::join($this->dataPath,
"white-list.txt"), Config::ENUM);
968 $bannedTxt = Path::join($this->dataPath,
"banned.txt");
969 $bannedPlayersTxt = Path::join($this->dataPath,
"banned-players.txt");
970 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
971 @rename($bannedTxt, $bannedPlayersTxt);
973 @touch($bannedPlayersTxt);
974 $this->banByName =
new BanList($bannedPlayersTxt);
975 $this->banByName->load();
976 $bannedIpsTxt = Path::join($this->dataPath,
"banned-ips.txt");
977 @touch($bannedIpsTxt);
978 $this->banByIP =
new BanList($bannedIpsTxt);
979 $this->banByIP->load();
981 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
983 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH,
true);
984 if($this->onlineMode){
985 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
987 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
988 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
989 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
992 $this->authKeyProvider =
new AuthKeyProvider(
new \
PrefixedLogger($this->logger,
"Minecraft Auth Key Provider"), $this->asyncPool);
994 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE,
false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
995 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
998 @cli_set_process_title($this->getName() .
" " . $this->getPocketMineVersion());
1000 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
1002 $this->logger->debug(
"Server unique id: " . $this->getServerUniqueId());
1003 $this->logger->debug(
"Machine unique id: " . Utils::getMachineUniqueId());
1005 $this->network =
new Network($this->logger);
1006 $this->network->setName($this->getMotd());
1008 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
1010 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW :
"") . $this->getPocketMineVersion() . TextFormat::RESET
1012 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
1014 DefaultPermissions::registerCorePermissions();
1016 $this->commandMap =
new SimpleCommandMap($this);
1018 $this->craftingManager = CraftingManagerFromDataHelper::make(BedrockDataFiles::RECIPES);
1020 $this->resourceManager =
new ResourcePackManager(Path::join($this->dataPath,
"resource_packs"), $this->logger);
1022 $pluginGraylist =
null;
1023 $graylistFile = Path::join($this->dataPath,
"plugin_list.yml");
1024 if(!file_exists($graylistFile)){
1025 copy(Path::join(\
pocketmine\RESOURCE_PATH,
'plugin_list.yml'), $graylistFile);
1028 $array = yaml_parse(Filesystem::fileGetContents($graylistFile));
1029 if(!is_array($array)){
1030 throw new \InvalidArgumentException(
"Expected array for root, but have " . gettype($array));
1032 $pluginGraylist = PluginGraylist::fromArray($array);
1033 }
catch(\InvalidArgumentException $e){
1034 $this->logger->emergency(
"Failed to load $graylistFile: " . $e->getMessage());
1035 $this->forceShutdownExit();
1038 $this->pluginManager =
new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR,
true) ?
null : Path::join($this->dataPath,
"plugin_data"), $pluginGraylist);
1039 $this->pluginManager->registerInterface(
new PharPluginLoader($this->autoloader));
1040 $this->pluginManager->registerInterface(
new ScriptPluginLoader());
1041 $this->pluginManager->registerInterface(
new FolderPluginLoader($this->autoloader));
1043 $providerManager =
new WorldProviderManager();
1045 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT,
""))) !==
null &&
1046 $format instanceof WritableWorldProviderManagerEntry
1048 $providerManager->setDefault($format);
1049 }elseif($formatName !==
""){
1050 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1053 $this->worldManager =
new WorldManager($this, Path::join($this->dataPath,
"worlds"), $providerManager);
1054 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1055 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1057 $this->updater =
new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST,
"update.pmmp.io"));
1059 $this->queryInfo =
new QueryInfo($this);
1061 $this->playerDataProvider =
new DatFilePlayerDataProvider(Path::join($this->dataPath,
"players"));
1063 register_shutdown_function($this->crashDump(...));
1065 $loadErrorCount = 0;
1066 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1067 if($loadErrorCount > 0){
1068 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1069 $this->forceShutdownExit();
1072 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1073 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1074 $this->forceShutdownExit();
1078 if(!$this->startupPrepareWorlds()){
1079 $this->forceShutdownExit();
1083 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1084 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1085 $this->forceShutdownExit();
1089 if(!$this->startupPrepareNetworkInterfaces()){
1090 $this->forceShutdownExit();
1094 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED,
true)){
1095 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1096 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1099 $this->configGroup->save();
1101 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1102 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_donate(TextFormat::AQUA .
"https://patreon.com/pocketminemp" . TextFormat::RESET)));
1103 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(
true) - $this->startTime, 3)))));
1105 $forwarder =
new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1106 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1107 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1110 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT,
true)){
1111 $this->console =
new ConsoleReaderChildProcessDaemon($this->logger);
1114 $this->tickProcessor();
1115 $this->forceShutdown();
1116 }
catch(\Throwable $e){
1117 $this->exceptionHandler($e);
1121 private function startupPrepareWorlds() : bool{
1122 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1123 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1124 if($generatorEntry ===
null){
1125 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1127 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1132 $generatorEntry->validateGeneratorOptions($generatorOptions);
1133 }
catch(InvalidGeneratorOptionsException $e){
1134 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1136 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1140 return $generatorEntry->getGeneratorClass();
1143 $anyWorldFailedToLoad =
false;
1145 foreach(Utils::promoteKeys((array) $this->configGroup->getProperty(Yml::WORLDS, [])) as $name => $options){
1146 if(!is_string($name)){
1150 if($options ===
null){
1152 }elseif(!is_array($options)){
1156 if(!$this->worldManager->loadWorld($name,
true)){
1157 if($this->worldManager->isWorldGenerated($name)){
1159 $anyWorldFailedToLoad = true;
1162 $creationOptions = WorldCreationOptions::create();
1165 $generatorName = $options[
"generator"] ??
"default";
1166 $generatorOptions = isset($options[
"preset"]) && is_string($options[
"preset"]) ? $options[
"preset"] :
"";
1168 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1169 if($generatorClass ===
null){
1170 $anyWorldFailedToLoad =
true;
1173 $creationOptions->setGeneratorClass($generatorClass);
1174 $creationOptions->setGeneratorOptions($generatorOptions);
1176 $creationOptions->setDifficulty($this->getDifficulty());
1177 if(isset($options[
"difficulty"]) && is_string($options[
"difficulty"])){
1178 $creationOptions->setDifficulty(World::getDifficultyFromString($options[
"difficulty"]));
1181 if(isset($options[
"seed"])){
1182 $convertedSeed = Generator::convertSeed((
string) ($options[
"seed"] ??
""));
1183 if($convertedSeed !==
null){
1184 $creationOptions->setSeed($convertedSeed);
1188 $this->worldManager->generateWorld($name, $creationOptions);
1192 if($this->worldManager->getDefaultWorld() ===
null){
1193 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1194 if(trim($default) ===
""){
1195 $this->logger->warning(
"level-name cannot be null, using default");
1197 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1199 if(!$this->worldManager->loadWorld($default,
true)){
1200 if($this->worldManager->isWorldGenerated($default)){
1201 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1205 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1206 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1207 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1209 if($generatorClass ===
null){
1210 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1213 $creationOptions = WorldCreationOptions::create()
1214 ->setGeneratorClass($generatorClass)
1215 ->setGeneratorOptions($generatorOptions);
1216 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1217 if($convertedSeed !==
null){
1218 $creationOptions->setSeed($convertedSeed);
1220 $creationOptions->setDifficulty($this->getDifficulty());
1221 $this->worldManager->generateWorld($default, $creationOptions);
1224 $world = $this->worldManager->getWorldByName($default);
1225 if($world ===
null){
1226 throw new AssumptionFailedError(
"We just loaded/generated the default world, so it must exist");
1228 $this->worldManager->setDefaultWorld($world);
1231 return !$anyWorldFailedToLoad;
1234 private function startupPrepareConnectableNetworkInterfaces(
1239 PacketBroadcaster $packetBroadcaster,
1240 EntityEventBroadcaster $entityEventBroadcaster,
1241 TypeConverter $typeConverter
1243 $prettyIp = $ipV6 ?
"[$ip]" : $ip;
1245 $rakLibRegistered = $this->network->registerInterface(
new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1246 }
catch(NetworkInterfaceStartException $e){
1247 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1254 if($rakLibRegistered){
1255 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (
string) $port)));
1258 if(!$rakLibRegistered){
1261 $this->network->registerInterface(
new DedicatedQueryNetworkInterface($ip, $port, $ipV6,
new \
PrefixedLogger($this->logger,
"Dedicated Query Interface")));
1263 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (
string) $port)));
1268 private function startupPrepareNetworkInterfaces() : bool{
1269 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1271 $typeConverter = TypeConverter::getInstance();
1272 $packetBroadcaster =
new StandardPacketBroadcaster($this);
1273 $entityEventBroadcaster =
new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1276 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(),
false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1278 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6,
true) &&
1279 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(),
true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1286 $this->network->registerRawPacketHandler(
new QueryHandler($this));
1289 foreach($this->getIPBans()->getEntries() as $entry){
1290 $this->network->blockAddress($entry->getName(), -1);
1293 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING,
false)){
1294 $this->network->registerInterface(
new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1305 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1312 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1313 if(count($this->broadcastSubscribers[$channelId]) === 1){
1314 unset($this->broadcastSubscribers[$channelId]);
1316 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1325 foreach(
Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1326 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1337 return $this->broadcastSubscribers[$channelId] ?? [];
1344 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1346 foreach($recipients as $recipient){
1347 $recipient->sendMessage($message);
1350 return count($recipients);
1356 private function getPlayerBroadcastSubscribers(
string $channelId) : array{
1359 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1360 if($subscriber instanceof Player){
1361 $players[spl_object_id($subscriber)] = $subscriber;
1370 public function broadcastTip(
string $tip, ?array $recipients =
null) : int{
1371 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1373 foreach($recipients as $recipient){
1374 $recipient->sendTip($tip);
1377 return count($recipients);
1384 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1386 foreach($recipients as $recipient){
1387 $recipient->sendPopup($popup);
1390 return count($recipients);
1399 public function broadcastTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1, ?array $recipients =
null) : int{
1400 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1402 foreach($recipients as $recipient){
1403 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1406 return count($recipients);
1422 public function prepareBatch(
string $buffer, Compressor $compressor, ?
bool $sync =
null, ?TimingsHandler $timings =
null) : CompressBatchPromise|string{
1423 $timings ??= Timings::$playerNetworkSendCompress;
1425 $timings->startTiming();
1427 $threshold = $compressor->getCompressionThreshold();
1428 if($threshold ===
null || strlen($buffer) < $compressor->getCompressionThreshold()){
1429 $compressionType = CompressionAlgorithm::NONE;
1430 $compressed = $buffer;
1433 $sync ??= !$this->networkCompressionAsync;
1435 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1436 $promise =
new CompressBatchPromise();
1437 $task =
new CompressBatchTask($buffer, $promise, $compressor);
1438 $this->asyncPool->submitTask($task);
1442 $compressionType = $compressor->getNetworkId();
1443 $compressed = $compressor->compress($buffer);
1446 return chr($compressionType) . $compressed;
1448 $timings->stopTiming();
1452 public function enablePlugins(PluginEnableOrder $type) : bool{
1454 foreach($this->pluginManager->getPlugins() as $plugin){
1455 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1456 if(!$this->pluginManager->enablePlugin($plugin)){
1457 $allSuccess =
false;
1462 if($type === PluginEnableOrder::POSTWORLD){
1463 $this->commandMap->registerServerAliases();
1476 if($ev->isCancelled()){
1480 $commandLine = $ev->getCommand();
1483 return $this->commandMap->dispatch($sender, $commandLine);
1490 if($this->isRunning){
1491 $this->isRunning =
false;
1492 $this->signalHandler->unregister();
1496 private function forceShutdownExit() : void{
1497 $this->forceShutdown();
1498 Process::kill(Process::pid());
1501 public function forceShutdown() : void{
1502 if($this->hasStopped){
1506 if($this->doTitleTick){
1510 if($this->isRunning){
1511 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1514 if(!$this->isRunning()){
1515 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1518 $this->hasStopped =
true;
1522 if(isset($this->pluginManager)){
1523 $this->logger->debug(
"Disabling all plugins");
1524 $this->pluginManager->disablePlugins();
1527 if(isset($this->network)){
1528 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE,
"Server closed"));
1531 if(isset($this->worldManager)){
1532 $this->logger->debug(
"Unloading all worlds");
1533 foreach($this->worldManager->getWorlds() as $world){
1534 $this->worldManager->unloadWorld($world,
true);
1538 $this->logger->debug(
"Removing event handlers");
1539 HandlerListManager::global()->unregisterAll();
1541 if(isset($this->asyncPool)){
1542 $this->logger->debug(
"Shutting down async task worker pool");
1543 $this->asyncPool->shutdown();
1546 if(isset($this->configGroup)){
1547 $this->logger->debug(
"Saving properties");
1548 $this->configGroup->save();
1551 if($this->console !==
null){
1552 $this->logger->debug(
"Closing console");
1553 $this->console->quit();
1556 if(isset($this->network)){
1557 $this->logger->debug(
"Stopping network interfaces");
1558 foreach($this->network->getInterfaces() as $interface){
1559 $this->logger->debug(
"Stopping network interface " . get_class($interface));
1560 $this->network->unregisterInterface($interface);
1563 }
catch(\Throwable $e){
1564 $this->logger->logException($e);
1565 $this->logger->emergency(
"Crashed while crashing, killing process");
1566 @Process::kill(Process::pid());
1571 public function getQueryInformation() : QueryInfo{
1572 return $this->queryInfo;
1580 while(@ob_end_flush()){}
1583 if($trace ===
null){
1584 $trace = $e->getTrace();
1590 $this->logger->logException($e, $trace);
1592 if($e instanceof ThreadCrashException){
1593 $info = $e->getCrashInfo();
1594 $type = $info->getType();
1595 $errstr = $info->getMessage();
1596 $errfile = $info->getFile();
1597 $errline = $info->getLine();
1598 $printableTrace = $info->getTrace();
1599 $thread = $info->getThreadName();
1601 $type = get_class($e);
1602 $errstr = $e->getMessage();
1603 $errfile = $e->getFile();
1604 $errline = $e->getLine();
1605 $printableTrace = Utils::printableTraceWithMetadata($trace);
1609 $errstr = preg_replace(
'/\s+/',
' ', trim($errstr));
1613 "message" => $errstr,
1614 "fullFile" => $errfile,
1615 "file" => Filesystem::cleanPath($errfile),
1617 "trace" => $printableTrace,
1621 global $lastExceptionError, $lastError;
1622 $lastExceptionError = $lastError;
1626 private function writeCrashDumpFile(CrashDump $dump) : string{
1627 $crashFolder = Path::join($this->dataPath,
"crashdumps");
1628 if(!is_dir($crashFolder)){
1629 mkdir($crashFolder);
1631 $crashDumpPath = Path::join($crashFolder, date(
"Y-m-d_H.i.s_T", (
int) $dump->getData()->time) .
".log");
1633 $fp = @fopen($crashDumpPath,
"wb");
1634 if(!is_resource($fp)){
1635 throw new \RuntimeException(
"Unable to open new file to generate crashdump");
1637 $writer =
new CrashDumpRenderer($fp, $dump->getData());
1638 $writer->renderHumanReadable();
1639 $dump->encodeData($writer);
1642 return $crashDumpPath;
1645 public function crashDump() : void{
1646 while(@ob_end_flush()){}
1647 if(!$this->isRunning){
1650 if($this->sendUsageTicker > 0){
1651 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1653 $this->hasStopped =
false;
1655 ini_set(
"error_reporting",
'0');
1656 ini_set(
"memory_limit",
'-1');
1658 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1659 $dump =
new CrashDump($this, $this->pluginManager ??
null);
1661 $crashDumpPath = $this->writeCrashDumpFile($dump);
1663 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1665 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED,
true)){
1668 $stamp = Path::join($this->dataPath,
"crashdumps",
".last_crash");
1669 $crashInterval = 120;
1670 if(($lastReportTime = @filemtime($stamp)) !==
false && $lastReportTime + $crashInterval >= time()){
1672 $this->logger->debug(
"Not sending crashdump due to last crash less than $crashInterval seconds ago");
1676 if($dump->getData()->error[
"type"] === \ParseError::class){
1680 if(strrpos(VersionInfo::GIT_HASH(),
"-dirty") !==
false || VersionInfo::GIT_HASH() === str_repeat(
"00", 20)){
1681 $this->logger->debug(
"Not sending crashdump due to locally modified");
1686 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS,
true) ?
"https" :
"http") .
"://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST,
"crash.pmmp.io") .
"/submit/api";
1687 $postUrlError =
"Unknown error";
1688 $reply = Internet::postURL($url, [
1690 "name" => $this->getName() .
" " . $this->getPocketMineVersion(),
1692 "reportPaste" => base64_encode($dump->getEncodedData())
1693 ], 10, [], $postUrlError);
1695 if($reply !==
null && is_object($data = json_decode($reply->getBody()))){
1696 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1697 $reportId = $data->crashId;
1698 $reportUrl = $data->crashUrl;
1699 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (
string) $reportId)));
1700 }elseif(isset($data->error) && is_string($data->error)){
1701 $this->logger->emergency(
"Automatic crash report submission failed: $data->error");
1703 $this->logger->emergency(
"Invalid JSON response received from crash archive: " . $reply->getBody());
1706 $this->logger->emergency(
"Failed to communicate with crash archive: $postUrlError");
1710 }
catch(\Throwable $e){
1711 $this->logger->logException($e);
1713 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1714 }
catch(\Throwable $e){}
1717 $this->forceShutdown();
1718 $this->isRunning =
false;
1721 $uptime = time() - ((int) $this->startTime);
1723 $spacing = $minUptime - $uptime;
1725 echo
"--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1728 @Process::kill(Process::pid());
1740 return $this->tickSleeper;
1743 private function tickProcessor() : void{
1744 $this->nextTick = microtime(true);
1746 while($this->isRunning){
1750 $this->tickSleeper->sleepUntil($this->nextTick);
1754 public function addOnlinePlayer(Player $player) : bool{
1755 $ev = new PlayerLoginEvent($player,
"Plugin reason");
1757 if($ev->isCancelled() || !$player->isConnected()){
1758 $player->disconnect($ev->getKickMessage());
1763 $session = $player->getNetworkSession();
1764 $position = $player->getPosition();
1765 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1766 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1768 (
string) $session->getPort(),
1769 (
string) $player->getId(),
1770 $position->getWorld()->getDisplayName(),
1771 (
string) round($position->x, 4),
1772 (
string) round($position->y, 4),
1773 (
string) round($position->z, 4)
1776 foreach($this->playerList as $p){
1777 $p->getNetworkSession()->onPlayerAdded($player);
1779 $rawUUID = $player->getUniqueId()->getBytes();
1780 $this->playerList[$rawUUID] = $player;
1782 if($this->sendUsageTicker > 0){
1783 $this->uniquePlayers[$rawUUID] = $rawUUID;
1789 public function removeOnlinePlayer(Player $player) : void{
1790 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1791 unset($this->playerList[$rawUUID]);
1792 foreach($this->playerList as $p){
1793 $p->getNetworkSession()->onPlayerRemoved($player);
1798 public function sendUsage(
int $type = SendUsageTask::TYPE_STATUS) : void{
1799 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1800 $this->asyncPool->submitTask(
new SendUsageTask($this, $type, $this->uniquePlayers));
1802 $this->uniquePlayers = [];
1805 public function getLanguage() : Language{
1806 return $this->language;
1809 public function isLanguageForced() : bool{
1810 return $this->forceLanguage;
1816 public function getAuthKeyProvider() : AuthKeyProvider{
1817 return $this->authKeyProvider;
1820 public function getNetwork() : Network{
1821 return $this->network;
1824 public function getMemoryManager() : MemoryManager{
1825 return $this->memoryManager;
1828 private function titleTick() : void{
1829 Timings::$titleTick->startTiming();
1831 $u = Process::getAdvancedMemoryUsage();
1832 $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());
1834 $online = count($this->playerList);
1835 $connecting = $this->network->getConnectionCount() - $online;
1836 $bandwidthStats = $this->network->getBandwidthTracker();
1838 echo
"\x1b]0;" . $this->getName() .
" " .
1839 $this->getPocketMineVersion() .
1840 " | Online $online/" . $this->maxPlayers .
1841 ($connecting > 0 ?
" (+$connecting connecting)" :
"") .
1842 " | Memory " . $usage .
1843 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1844 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1845 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1846 " | Load " . $this->getTickUsageAverage() .
"%\x07";
1848 Timings::$titleTick->stopTiming();
1854 private function tick() : void{
1855 $tickTime = microtime(true);
1856 if(($tickTime - $this->nextTick) < -0.025){
1860 Timings::$serverTick->startTiming();
1862 ++$this->tickCounter;
1864 Timings::$scheduler->startTiming();
1865 $this->pluginManager->tickSchedulers($this->tickCounter);
1866 Timings::$scheduler->stopTiming();
1868 Timings::$schedulerAsync->startTiming();
1869 $this->asyncPool->collectTasks();
1870 Timings::$schedulerAsync->stopTiming();
1872 $this->worldManager->tick($this->tickCounter);
1874 Timings::$connection->startTiming();
1875 $this->network->tick();
1876 Timings::$connection->stopTiming();
1878 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1879 if($this->doTitleTick){
1882 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1883 $this->currentUse = 0;
1885 $queryRegenerateEvent =
new QueryRegenerateEvent(
new QueryInfo($this));
1886 $queryRegenerateEvent->call();
1887 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1889 $this->network->updateName();
1890 $this->network->getBandwidthTracker()->rotateAverageHistory();
1893 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1894 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1895 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1898 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1899 foreach($this->worldManager->getWorlds() as $world){
1900 $world->clearCache();
1904 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1905 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1908 $this->memoryManager->check();
1910 if($this->console !==
null){
1911 Timings::$serverCommand->startTiming();
1912 while(($line = $this->console->readLine()) !==
null){
1913 $this->consoleSender ??=
new ConsoleCommandSender($this, $this->language);
1914 $this->dispatchCommand($this->consoleSender, $line);
1916 Timings::$serverCommand->stopTiming();
1919 Timings::$serverTick->stopTiming();
1921 $now = microtime(
true);
1922 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1923 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1924 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1926 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1928 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1929 $this->tickAverage[$idx] = $this->currentTPS;
1930 $this->useAverage[$idx] = $this->currentUse;
1931 $this->tickSleeper->resetNotificationProcessingTime();
1933 if(($this->nextTick - $tickTime) < -1){
1934 $this->nextTick = $tickTime;
1936 $this->nextTick += self::TARGET_SECONDS_PER_TICK;