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 $command = $this->commandMap->getCommand($name);
684 return $command instanceof
PluginOwned ? $command :
null;
687 public function getNameBans() :
BanList{
688 return $this->banByName;
691 public function getIPBans() : BanList{
692 return $this->banByIP;
695 public function addOp(
string $name) : void{
696 $this->operators->set(strtolower($name), true);
698 if(($player = $this->getPlayerExact($name)) !==
null){
699 $player->setBasePermission(DefaultPermissions::ROOT_OPERATOR,
true);
701 $this->operators->save();
704 public function removeOp(
string $name) : void{
705 $lowercaseName = strtolower($name);
706 foreach(Utils::promoteKeys($this->operators->getAll()) as $operatorName => $_){
707 $operatorName = (string) $operatorName;
708 if($lowercaseName === strtolower($operatorName)){
709 $this->operators->remove($operatorName);
713 if(($player = $this->getPlayerExact($name)) !==
null){
714 $player->unsetBasePermission(DefaultPermissions::ROOT_OPERATOR);
716 $this->operators->save();
719 public function addWhitelist(
string $name) : void{
720 $this->whitelist->set(strtolower($name), true);
721 $this->whitelist->save();
724 public function removeWhitelist(
string $name) : void{
725 $this->whitelist->remove(strtolower($name));
726 $this->whitelist->save();
729 public function isWhitelisted(
string $name) : bool{
730 return !$this->hasWhitelist() || $this->operators->exists($name, true) || $this->whitelist->exists($name, true);
733 public function isOp(
string $name) : bool{
734 return $this->operators->exists($name, true);
737 public function getWhitelisted() : Config{
738 return $this->whitelist;
741 public function getOps() : Config{
742 return $this->operators;
750 $section = $this->configGroup->getProperty(Yml::ALIASES);
752 if(is_array($section)){
753 foreach(Utils::promoteKeys($section) as $key => $value){
757 if(is_array($value)){
760 $commands[] = (string) $value;
763 $result[(string) $key] = $commands;
770 public static function getInstance() : Server{
771 if(self::$instance === null){
772 throw new \RuntimeException(
"Attempt to retrieve Server instance outside server thread");
774 return self::$instance;
777 public function __construct(
778 private ThreadSafeClassLoader $autoloader,
779 private AttachableThreadSafeLogger $logger,
783 if(self::$instance !==
null){
784 throw new \LogicException(
"Only one server instance can exist at once");
786 self::$instance = $this;
787 $this->startTime = microtime(
true);
788 $this->tickAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, self::TARGET_TICKS_PER_SECOND);
789 $this->useAverage = array_fill(0, self::TARGET_TICKS_PER_SECOND, 0);
792 $this->tickSleeper =
new TimeTrackingSleeperHandler(Timings::$serverInterrupts);
794 $this->signalHandler =
new SignalHandler(
function() :
void{
795 $this->logger->info(
"Received signal interrupt, stopping the server");
803 Path::join($dataPath,
"worlds"),
804 Path::join($dataPath,
"players")
806 if(!file_exists($neededPath)){
807 mkdir($neededPath, 0777);
811 $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
812 $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
814 $this->logger->info(
"Loading server configuration");
815 $pocketmineYmlPath = Path::join($this->dataPath,
"pocketmine.yml");
816 if(!file_exists($pocketmineYmlPath)){
817 $content = Filesystem::fileGetContents(Path::join(\
pocketmine\RESOURCE_PATH,
"pocketmine.yml"));
818 if(VersionInfo::IS_DEVELOPMENT_BUILD){
819 $content = str_replace(
"preferred-channel: stable",
"preferred-channel: beta", $content);
821 @file_put_contents($pocketmineYmlPath, $content);
824 $this->configGroup =
new ServerConfigGroup(
825 new Config($pocketmineYmlPath, Config::YAML, []),
826 new Config(Path::join($this->dataPath,
"server.properties"), Config::PROPERTIES, [
827 ServerProperties::MOTD => self::DEFAULT_SERVER_NAME,
828 ServerProperties::SERVER_PORT_IPV4 => self::DEFAULT_PORT_IPV4,
829 ServerProperties::SERVER_PORT_IPV6 => self::DEFAULT_PORT_IPV6,
830 ServerProperties::ENABLE_IPV6 =>
true,
831 ServerProperties::WHITELIST =>
false,
832 ServerProperties::MAX_PLAYERS => self::DEFAULT_MAX_PLAYERS,
833 ServerProperties::GAME_MODE => GameMode::SURVIVAL->name,
834 ServerProperties::FORCE_GAME_MODE =>
false,
835 ServerProperties::HARDCORE =>
false,
836 ServerProperties::PVP =>
true,
837 ServerProperties::DIFFICULTY => World::DIFFICULTY_NORMAL,
838 ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS =>
"",
839 ServerProperties::DEFAULT_WORLD_NAME =>
"world",
840 ServerProperties::DEFAULT_WORLD_SEED =>
"",
841 ServerProperties::DEFAULT_WORLD_GENERATOR =>
"DEFAULT",
842 ServerProperties::ENABLE_QUERY =>
true,
843 ServerProperties::AUTO_SAVE =>
true,
844 ServerProperties::VIEW_DISTANCE => self::DEFAULT_MAX_VIEW_DISTANCE,
845 ServerProperties::XBOX_AUTH =>
true,
846 ServerProperties::LANGUAGE =>
"eng"
850 $debugLogLevel = $this->configGroup->getPropertyInt(Yml::DEBUG_LEVEL, 1);
851 if($this->logger instanceof MainLogger){
852 $this->logger->setLogDebug($debugLogLevel > 1);
855 $this->forceLanguage = $this->configGroup->getPropertyBool(Yml::SETTINGS_FORCE_LANGUAGE,
false);
856 $selectedLang = $this->configGroup->getConfigString(ServerProperties::LANGUAGE, $this->configGroup->getPropertyString(
"settings.language", Language::FALLBACK_LANGUAGE));
858 $this->language =
new Language($selectedLang);
859 }
catch(LanguageNotFoundException $e){
860 $this->logger->error($e->getMessage());
862 $this->language =
new Language(Language::FALLBACK_LANGUAGE);
863 }
catch(LanguageNotFoundException $e){
864 $this->logger->emergency(
"Fallback language \"" . Language::FALLBACK_LANGUAGE .
"\" not found");
869 $this->logger->info($this->language->translate(KnownTranslationFactory::language_selected($this->language->getName(), $this->language->getLang())));
871 if(VersionInfo::IS_DEVELOPMENT_BUILD){
872 if(!$this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_DEV_BUILDS,
false)){
873 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error1(VersionInfo::NAME)));
874 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error2()));
875 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error3()));
876 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error4(Yml::SETTINGS_ENABLE_DEV_BUILDS)));
877 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_error5(VersionInfo::GITHUB_URL .
"/releases")));
878 $this->forceShutdownExit();
883 $this->logger->warning(str_repeat(
"-", 40));
884 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning1(VersionInfo::NAME)));
885 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning2()));
886 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_devBuild_warning3()));
887 $this->logger->warning(str_repeat(
"-", 40));
890 $this->memoryManager =
new MemoryManager($this);
892 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_start(TextFormat::AQUA . $this->getVersion() . TextFormat::RESET)));
894 if(($poolSize = $this->configGroup->getPropertyString(Yml::SETTINGS_ASYNC_WORKERS,
"auto")) ===
"auto"){
896 $processors = Utils::getCoreCount() - 2;
899 $poolSize = max(1, $processors);
902 $poolSize = max(1, (
int) $poolSize);
905 TimingsHandler::setEnabled($this->configGroup->getPropertyBool(Yml::SETTINGS_ENABLE_PROFILING,
false));
906 $this->profilingTickRate = $this->configGroup->getPropertyInt(Yml::SETTINGS_PROFILE_REPORT_TRIGGER, self::TARGET_TICKS_PER_SECOND);
908 $this->asyncPool =
new AsyncPool($poolSize, max(-1, $this->configGroup->getPropertyInt(Yml::MEMORY_ASYNC_WORKER_HARD_LIMIT, 256)), $this->autoloader, $this->logger, $this->tickSleeper);
909 $this->asyncPool->addWorkerStartHook(
function(
int $i) :
void{
910 if(TimingsHandler::isEnabled()){
911 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled(
true), $i);
914 TimingsHandler::getToggleCallbacks()->add(
function(
bool $enable) :
void{
915 foreach($this->asyncPool->getRunningWorkers() as $workerId){
916 $this->asyncPool->submitTaskToWorker(TimingsControlTask::setEnabled($enable), $workerId);
919 TimingsHandler::getReloadCallbacks()->add(
function() :
void{
920 foreach($this->asyncPool->getRunningWorkers() as $workerId){
921 $this->asyncPool->submitTaskToWorker(TimingsControlTask::reload(), $workerId);
924 TimingsHandler::getCollectCallbacks()->add(
function() : array{
926 foreach($this->asyncPool->getRunningWorkers() as $workerId){
928 $resolver =
new PromiseResolver();
929 $this->asyncPool->submitTaskToWorker(
new TimingsCollectionTask($resolver), $workerId);
931 $promises[] = $resolver->getPromise();
937 $netCompressionThreshold = -1;
938 if($this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256) >= 0){
939 $netCompressionThreshold = $this->configGroup->getPropertyInt(Yml::NETWORK_BATCH_THRESHOLD, 256);
941 if($netCompressionThreshold < 0){
942 $netCompressionThreshold =
null;
945 $netCompressionLevel = $this->configGroup->getPropertyInt(Yml::NETWORK_COMPRESSION_LEVEL, 6);
946 if($netCompressionLevel < 1 || $netCompressionLevel > 9){
947 $this->logger->warning(
"Invalid network compression level $netCompressionLevel set, setting to default 6");
948 $netCompressionLevel = 6;
950 ZlibCompressor::setInstance(
new ZlibCompressor($netCompressionLevel, $netCompressionThreshold, ZlibCompressor::DEFAULT_MAX_DECOMPRESSION_SIZE));
952 $this->networkCompressionAsync = $this->configGroup->getPropertyBool(Yml::NETWORK_ASYNC_COMPRESSION,
true);
953 $this->networkCompressionAsyncThreshold = max(
954 $this->configGroup->getPropertyInt(Yml::NETWORK_ASYNC_COMPRESSION_THRESHOLD, self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD),
955 $netCompressionThreshold ?? self::DEFAULT_ASYNC_COMPRESSION_THRESHOLD
958 EncryptionContext::$ENABLED = $this->configGroup->getPropertyBool(Yml::NETWORK_ENABLE_ENCRYPTION,
true);
960 $this->doTitleTick = $this->configGroup->getPropertyBool(Yml::CONSOLE_TITLE_TICK,
true) && Terminal::hasFormattingCodes();
962 $this->operators =
new Config(Path::join($this->dataPath,
"ops.txt"), Config::ENUM);
963 $this->whitelist =
new Config(Path::join($this->dataPath,
"white-list.txt"), Config::ENUM);
965 $bannedTxt = Path::join($this->dataPath,
"banned.txt");
966 $bannedPlayersTxt = Path::join($this->dataPath,
"banned-players.txt");
967 if(file_exists($bannedTxt) && !file_exists($bannedPlayersTxt)){
968 @rename($bannedTxt, $bannedPlayersTxt);
970 @touch($bannedPlayersTxt);
971 $this->banByName =
new BanList($bannedPlayersTxt);
972 $this->banByName->load();
973 $bannedIpsTxt = Path::join($this->dataPath,
"banned-ips.txt");
974 @touch($bannedIpsTxt);
975 $this->banByIP =
new BanList($bannedIpsTxt);
976 $this->banByIP->load();
978 $this->maxPlayers = $this->configGroup->getConfigInt(ServerProperties::MAX_PLAYERS, self::DEFAULT_MAX_PLAYERS);
980 $this->onlineMode = $this->configGroup->getConfigBool(ServerProperties::XBOX_AUTH,
true);
981 if($this->onlineMode){
982 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_enabled()));
984 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_auth_disabled()));
985 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authWarning()));
986 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_authProperty_disabled()));
989 $this->authKeyProvider =
new AuthKeyProvider(
new \
PrefixedLogger($this->logger,
"Minecraft Auth Key Provider"), $this->asyncPool);
991 if($this->configGroup->getConfigBool(ServerProperties::HARDCORE,
false) && $this->getDifficulty() < World::DIFFICULTY_HARD){
992 $this->configGroup->setConfigInt(ServerProperties::DIFFICULTY, World::DIFFICULTY_HARD);
995 @cli_set_process_title($this->getName() .
" " . $this->getPocketMineVersion());
997 $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
999 $this->logger->debug(
"Server unique id: " . $this->getServerUniqueId());
1000 $this->logger->debug(
"Machine unique id: " . Utils::getMachineUniqueId());
1002 $this->network =
new Network($this->logger);
1003 $this->network->setName($this->getMotd());
1005 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_info(
1007 (VersionInfo::IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW :
"") . $this->getPocketMineVersion() . TextFormat::RESET
1009 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_license($this->getName())));
1011 DefaultPermissions::registerCorePermissions();
1013 $this->commandMap =
new SimpleCommandMap($this);
1015 $this->craftingManager = CraftingManagerFromDataHelper::make(BedrockDataFiles::RECIPES);
1017 $this->resourceManager =
new ResourcePackManager(Path::join($this->dataPath,
"resource_packs"), $this->logger);
1019 $pluginGraylist =
null;
1020 $graylistFile = Path::join($this->dataPath,
"plugin_list.yml");
1021 if(!file_exists($graylistFile)){
1022 copy(Path::join(\
pocketmine\RESOURCE_PATH,
'plugin_list.yml'), $graylistFile);
1025 $array = yaml_parse(Filesystem::fileGetContents($graylistFile));
1026 if(!is_array($array)){
1027 throw new \InvalidArgumentException(
"Expected array for root, but have " . gettype($array));
1029 $pluginGraylist = PluginGraylist::fromArray($array);
1030 }
catch(\InvalidArgumentException $e){
1031 $this->logger->emergency(
"Failed to load $graylistFile: " . $e->getMessage());
1032 $this->forceShutdownExit();
1035 $this->pluginManager =
new PluginManager($this, $this->configGroup->getPropertyBool(Yml::PLUGINS_LEGACY_DATA_DIR,
true) ?
null : Path::join($this->dataPath,
"plugin_data"), $pluginGraylist);
1036 $this->pluginManager->registerInterface(
new PharPluginLoader($this->autoloader));
1037 $this->pluginManager->registerInterface(
new ScriptPluginLoader());
1038 $this->pluginManager->registerInterface(
new FolderPluginLoader($this->autoloader));
1040 $providerManager =
new WorldProviderManager();
1042 ($format = $providerManager->getProviderByName($formatName = $this->configGroup->getPropertyString(Yml::LEVEL_SETTINGS_DEFAULT_FORMAT,
""))) !==
null &&
1043 $format instanceof WritableWorldProviderManagerEntry
1045 $providerManager->setDefault($format);
1046 }elseif($formatName !==
""){
1047 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_level_badDefaultFormat($formatName)));
1050 $this->worldManager =
new WorldManager($this, Path::join($this->dataPath,
"worlds"), $providerManager);
1051 $this->worldManager->setAutoSave($this->configGroup->getConfigBool(ServerProperties::AUTO_SAVE, $this->worldManager->getAutoSave()));
1052 $this->worldManager->setAutoSaveInterval($this->configGroup->getPropertyInt(Yml::TICKS_PER_AUTOSAVE, $this->worldManager->getAutoSaveInterval()));
1054 $this->updater =
new UpdateChecker($this, $this->configGroup->getPropertyString(Yml::AUTO_UPDATER_HOST,
"update.pmmp.io"));
1056 $this->queryInfo =
new QueryInfo($this);
1058 $this->playerDataProvider =
new DatFilePlayerDataProvider(Path::join($this->dataPath,
"players"));
1060 register_shutdown_function($this->crashDump(...));
1062 $loadErrorCount = 0;
1063 $this->pluginManager->loadPlugins($this->pluginPath, $loadErrorCount);
1064 if($loadErrorCount > 0){
1065 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someLoadErrors()));
1066 $this->forceShutdownExit();
1069 if(!$this->enablePlugins(PluginEnableOrder::STARTUP)){
1070 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1071 $this->forceShutdownExit();
1075 if(!$this->startupPrepareWorlds()){
1076 $this->forceShutdownExit();
1080 if(!$this->enablePlugins(PluginEnableOrder::POSTWORLD)){
1081 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_plugin_someEnableErrors()));
1082 $this->forceShutdownExit();
1086 if(!$this->startupPrepareNetworkInterfaces()){
1087 $this->forceShutdownExit();
1091 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED,
true)){
1092 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1093 $this->sendUsage(SendUsageTask::TYPE_OPEN);
1096 $this->configGroup->save();
1098 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_defaultGameMode($this->getGamemode()->getTranslatableName())));
1099 $highlight = TextFormat::AQUA;
1100 $reset = TextFormat::RESET;
1101 $github = VersionInfo::GITHUB_URL;
1104 KnownTranslationFactory::pocketmine_server_url_discord(
"{$highlight}https://discord.pmmp.io{$reset}"),
1105 KnownTranslationFactory::pocketmine_server_url_docs(
"{$highlight}https://doc.pmmp.io{$reset}"),
1106 KnownTranslationFactory::pocketmine_server_url_sourceCode(
"{$highlight}{$github}{$reset}"),
1107 KnownTranslationFactory::pocketmine_server_url_freePlugins(
"{$highlight}https://poggit.pmmp.io/plugins{$reset}"),
1108 KnownTranslationFactory::pocketmine_server_url_donations(
"{$highlight}https://patreon.com/pocketminemp{$reset}"),
1109 KnownTranslationFactory::pocketmine_server_url_translations(
"{$highlight}https://translate.pocketmine.net{$reset}"),
1110 KnownTranslationFactory::pocketmine_server_url_bugReporting(
"{$highlight}{$github}/issues{$reset}")
1112 $splash .=
"- " . $this->language->translate($link) .
"\n";
1114 $this->logger->info($splash);
1116 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_startFinished(strval(round(microtime(
true) - $this->startTime, 3)))));
1118 $forwarder =
new BroadcastLoggerForwarder($this, $this->logger, $this->language);
1119 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_ADMINISTRATIVE, $forwarder);
1120 $this->subscribeToBroadcastChannel(self::BROADCAST_CHANNEL_USERS, $forwarder);
1123 if($this->configGroup->getPropertyBool(Yml::CONSOLE_ENABLE_INPUT,
true)){
1124 $this->console =
new ConsoleReaderChildProcessDaemon($this->logger);
1127 $this->tickProcessor();
1128 $this->forceShutdown();
1129 }
catch(\Throwable $e){
1130 $this->exceptionHandler($e);
1134 private function startupPrepareWorlds() : bool{
1135 $getGenerator = function(string $generatorName, string $generatorOptions, string $worldName) : ?string{
1136 $generatorEntry = GeneratorManager::getInstance()->getGenerator($generatorName);
1137 if($generatorEntry ===
null){
1138 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1140 KnownTranslationFactory::pocketmine_level_unknownGenerator($generatorName)
1145 $generatorEntry->validateGeneratorOptions($generatorOptions);
1146 }
catch(InvalidGeneratorOptionsException $e){
1147 $this->logger->error($this->language->translate(KnownTranslationFactory::pocketmine_level_generationError(
1149 KnownTranslationFactory::pocketmine_level_invalidGeneratorOptions($generatorOptions, $generatorName, $e->getMessage())
1153 return $generatorEntry->getGeneratorClass();
1156 $anyWorldFailedToLoad =
false;
1158 foreach(Utils::promoteKeys((array) $this->configGroup->getProperty(Yml::WORLDS, [])) as $name => $options){
1159 if(!is_string($name)){
1163 if($options ===
null){
1165 }elseif(!is_array($options)){
1169 if(!$this->worldManager->loadWorld($name,
true)){
1170 if($this->worldManager->isWorldGenerated($name)){
1172 $anyWorldFailedToLoad = true;
1175 $creationOptions = WorldCreationOptions::create();
1178 $generatorName = $options[
"generator"] ??
"default";
1179 $generatorOptions = isset($options[
"preset"]) && is_string($options[
"preset"]) ? $options[
"preset"] :
"";
1181 $generatorClass = $getGenerator($generatorName, $generatorOptions, $name);
1182 if($generatorClass ===
null){
1183 $anyWorldFailedToLoad =
true;
1186 $creationOptions->setGeneratorClass($generatorClass);
1187 $creationOptions->setGeneratorOptions($generatorOptions);
1189 $creationOptions->setDifficulty($this->getDifficulty());
1190 if(isset($options[
"difficulty"]) && is_string($options[
"difficulty"])){
1191 $creationOptions->setDifficulty(World::getDifficultyFromString($options[
"difficulty"]));
1194 if(isset($options[
"seed"])){
1195 $convertedSeed = Generator::convertSeed((
string) ($options[
"seed"] ??
""));
1196 if($convertedSeed !==
null){
1197 $creationOptions->setSeed($convertedSeed);
1201 $this->worldManager->generateWorld($name, $creationOptions);
1205 if($this->worldManager->getDefaultWorld() ===
null){
1206 $default = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1207 if(trim($default) ===
""){
1208 $this->logger->warning(
"level-name cannot be null, using default");
1210 $this->configGroup->setConfigString(ServerProperties::DEFAULT_WORLD_NAME,
"world");
1212 if(!$this->worldManager->loadWorld($default,
true)){
1213 if($this->worldManager->isWorldGenerated($default)){
1214 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1218 $generatorName = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR);
1219 $generatorOptions = $this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_GENERATOR_SETTINGS);
1220 $generatorClass = $getGenerator($generatorName, $generatorOptions, $default);
1222 if($generatorClass ===
null){
1223 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_level_defaultError()));
1226 $creationOptions = WorldCreationOptions::create()
1227 ->setGeneratorClass($generatorClass)
1228 ->setGeneratorOptions($generatorOptions);
1229 $convertedSeed = Generator::convertSeed($this->configGroup->getConfigString(ServerProperties::DEFAULT_WORLD_SEED));
1230 if($convertedSeed !==
null){
1231 $creationOptions->setSeed($convertedSeed);
1233 $creationOptions->setDifficulty($this->getDifficulty());
1234 $this->worldManager->generateWorld($default, $creationOptions);
1237 $world = $this->worldManager->getWorldByName($default);
1238 if($world ===
null){
1239 throw new AssumptionFailedError(
"We just loaded/generated the default world, so it must exist");
1241 $this->worldManager->setDefaultWorld($world);
1244 return !$anyWorldFailedToLoad;
1247 private function startupPrepareConnectableNetworkInterfaces(
1252 PacketBroadcaster $packetBroadcaster,
1253 EntityEventBroadcaster $entityEventBroadcaster,
1254 TypeConverter $typeConverter
1256 $prettyIp = $ipV6 ?
"[$ip]" : $ip;
1258 $rakLibRegistered = $this->network->registerInterface(
new RakLibInterface($this, $ip, $port, $ipV6, $packetBroadcaster, $entityEventBroadcaster, $typeConverter));
1259 }
catch(NetworkInterfaceStartException $e){
1260 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStartFailed(
1267 if($rakLibRegistered){
1268 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_networkStart($prettyIp, (
string) $port)));
1271 if(!$rakLibRegistered){
1274 $this->network->registerInterface(
new DedicatedQueryNetworkInterface($ip, $port, $ipV6,
new \
PrefixedLogger($this->logger,
"Dedicated Query Interface")));
1276 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_server_query_running($prettyIp, (
string) $port)));
1281 private function startupPrepareNetworkInterfaces() : bool{
1282 $useQuery = $this->configGroup->getConfigBool(ServerProperties::ENABLE_QUERY, true);
1284 $typeConverter = TypeConverter::getInstance();
1285 $packetBroadcaster =
new StandardPacketBroadcaster($this);
1286 $entityEventBroadcaster =
new StandardEntityEventBroadcaster($packetBroadcaster, $typeConverter);
1289 !$this->startupPrepareConnectableNetworkInterfaces($this->getIp(), $this->getPort(),
false, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter) ||
1291 $this->configGroup->getConfigBool(ServerProperties::ENABLE_IPV6,
true) &&
1292 !$this->startupPrepareConnectableNetworkInterfaces($this->getIpV6(), $this->getPortV6(),
true, $useQuery, $packetBroadcaster, $entityEventBroadcaster, $typeConverter)
1299 $this->network->registerRawPacketHandler(
new QueryHandler($this));
1302 foreach($this->getIPBans()->getEntries() as $entry){
1303 $this->network->blockAddress($entry->getName(), -1);
1306 if($this->configGroup->getPropertyBool(Yml::NETWORK_UPNP_FORWARDING,
false)){
1307 $this->network->registerInterface(
new UPnPNetworkInterface($this->logger, Internet::getInternalIP(), $this->getPort()));
1318 $this->broadcastSubscribers[$channelId][spl_object_id($subscriber)] = $subscriber;
1325 if(isset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)])){
1326 if(count($this->broadcastSubscribers[$channelId]) === 1){
1327 unset($this->broadcastSubscribers[$channelId]);
1329 unset($this->broadcastSubscribers[$channelId][spl_object_id($subscriber)]);
1338 foreach(
Utils::stringifyKeys($this->broadcastSubscribers) as $channelId => $recipients){
1339 $this->unsubscribeFromBroadcastChannel($channelId, $subscriber);
1350 return $this->broadcastSubscribers[$channelId] ?? [];
1357 $recipients = $recipients ?? $this->getBroadcastChannelSubscribers(self::BROADCAST_CHANNEL_USERS);
1359 foreach($recipients as $recipient){
1360 $recipient->sendMessage($message);
1363 return count($recipients);
1369 private function getPlayerBroadcastSubscribers(
string $channelId) : array{
1372 foreach($this->broadcastSubscribers[$channelId] as $subscriber){
1373 if($subscriber instanceof Player){
1374 $players[spl_object_id($subscriber)] = $subscriber;
1383 public function broadcastTip(
string $tip, ?array $recipients =
null) : int{
1384 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1386 foreach($recipients as $recipient){
1387 $recipient->sendTip($tip);
1390 return count($recipients);
1397 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1399 foreach($recipients as $recipient){
1400 $recipient->sendPopup($popup);
1403 return count($recipients);
1412 public function broadcastTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1, ?array $recipients =
null) : int{
1413 $recipients = $recipients ?? $this->getPlayerBroadcastSubscribers(self::BROADCAST_CHANNEL_USERS);
1415 foreach($recipients as $recipient){
1416 $recipient->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut);
1419 return count($recipients);
1435 public function prepareBatch(
string $buffer, Compressor $compressor, ?
bool $sync =
null, ?TimingsHandler $timings =
null) : CompressBatchPromise|string{
1436 $timings ??= Timings::$playerNetworkSendCompress;
1438 $timings->startTiming();
1440 $threshold = $compressor->getCompressionThreshold();
1441 if($threshold ===
null || strlen($buffer) < $compressor->getCompressionThreshold()){
1442 $compressionType = CompressionAlgorithm::NONE;
1443 $compressed = $buffer;
1446 $sync ??= !$this->networkCompressionAsync;
1448 if(!$sync && strlen($buffer) >= $this->networkCompressionAsyncThreshold){
1449 $promise =
new CompressBatchPromise();
1450 $task =
new CompressBatchTask($buffer, $promise, $compressor);
1451 $this->asyncPool->submitTask($task);
1455 $compressionType = $compressor->getNetworkId();
1456 $compressed = $compressor->compress($buffer);
1459 return chr($compressionType) . $compressed;
1461 $timings->stopTiming();
1465 public function enablePlugins(PluginEnableOrder $type) : bool{
1467 foreach($this->pluginManager->getPlugins() as $plugin){
1468 if(!$plugin->isEnabled() && $plugin->getDescription()->getOrder() === $type){
1469 if(!$this->pluginManager->enablePlugin($plugin)){
1470 $allSuccess =
false;
1475 if($type === PluginEnableOrder::POSTWORLD){
1476 $this->commandMap->registerServerAliases();
1489 if($ev->isCancelled()){
1493 $commandLine = $ev->getCommand();
1496 return $this->commandMap->dispatch($sender, $commandLine);
1503 if($this->isRunning){
1504 $this->isRunning =
false;
1505 $this->signalHandler->unregister();
1509 private function forceShutdownExit() : void{
1510 $this->forceShutdown();
1511 Process::kill(Process::pid());
1514 public function forceShutdown() : void{
1515 if($this->hasStopped){
1519 if($this->doTitleTick){
1523 if($this->isRunning){
1524 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_server_forcingShutdown()));
1527 if(!$this->isRunning()){
1528 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1531 $this->hasStopped =
true;
1535 if(isset($this->pluginManager)){
1536 $this->logger->debug(
"Disabling all plugins");
1537 $this->pluginManager->disablePlugins();
1540 if(isset($this->network)){
1541 $this->network->getSessionManager()->close($this->configGroup->getPropertyString(Yml::SETTINGS_SHUTDOWN_MESSAGE,
"Server closed"));
1544 if(isset($this->worldManager)){
1545 $this->logger->debug(
"Unloading all worlds");
1546 foreach($this->worldManager->getWorlds() as $world){
1547 $this->worldManager->unloadWorld($world,
true);
1551 $this->logger->debug(
"Removing event handlers");
1552 HandlerListManager::global()->unregisterAll();
1554 if(isset($this->asyncPool)){
1555 $this->logger->debug(
"Shutting down async task worker pool");
1556 $this->asyncPool->shutdown();
1559 if(isset($this->configGroup)){
1560 $this->logger->debug(
"Saving properties");
1561 $this->configGroup->save();
1564 if($this->console !==
null){
1565 $this->logger->debug(
"Closing console");
1566 $this->console->quit();
1569 if(isset($this->network)){
1570 $this->logger->debug(
"Stopping network interfaces");
1571 foreach($this->network->getInterfaces() as $interface){
1572 $this->logger->debug(
"Stopping network interface " . get_class($interface));
1573 $this->network->unregisterInterface($interface);
1576 }
catch(\Throwable $e){
1577 $this->logger->logException($e);
1578 $this->logger->emergency(
"Crashed while crashing, killing process");
1579 @Process::kill(Process::pid());
1584 public function getQueryInformation() : QueryInfo{
1585 return $this->queryInfo;
1593 while(@ob_end_flush()){}
1596 if($trace ===
null){
1597 $trace = $e->getTrace();
1603 $this->logger->logException($e, $trace);
1605 if($e instanceof ThreadCrashException){
1606 $info = $e->getCrashInfo();
1607 $type = $info->getType();
1608 $errstr = $info->getMessage();
1609 $errfile = $info->getFile();
1610 $errline = $info->getLine();
1611 $printableTrace = $info->getTrace();
1612 $thread = $info->getThreadName();
1614 $type = get_class($e);
1615 $errstr = $e->getMessage();
1616 $errfile = $e->getFile();
1617 $errline = $e->getLine();
1618 $printableTrace = Utils::printableTraceWithMetadata($trace);
1622 $errstr = preg_replace(
'/\s+/',
' ', trim($errstr));
1626 "message" => $errstr,
1627 "fullFile" => $errfile,
1628 "file" => Filesystem::cleanPath($errfile),
1630 "trace" => $printableTrace,
1634 global $lastExceptionError, $lastError;
1635 $lastExceptionError = $lastError;
1639 private function writeCrashDumpFile(CrashDump $dump) : string{
1640 $crashFolder = Path::join($this->dataPath,
"crashdumps");
1641 if(!is_dir($crashFolder)){
1642 mkdir($crashFolder);
1644 $crashDumpPath = Path::join($crashFolder, date(
"Y-m-d_H.i.s_T", (
int) $dump->getData()->time) .
".log");
1646 $fp = @fopen($crashDumpPath,
"wb");
1647 if(!is_resource($fp)){
1648 throw new \RuntimeException(
"Unable to open new file to generate crashdump");
1650 $writer =
new CrashDumpRenderer($fp, $dump->getData());
1651 $writer->renderHumanReadable();
1652 $dump->encodeData($writer);
1655 return $crashDumpPath;
1658 public function crashDump() : void{
1659 while(@ob_end_flush()){}
1660 if(!$this->isRunning){
1663 if($this->sendUsageTicker > 0){
1664 $this->sendUsage(SendUsageTask::TYPE_CLOSE);
1666 $this->hasStopped =
false;
1668 ini_set(
"error_reporting",
'0');
1669 ini_set(
"memory_limit",
'-1');
1671 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_create()));
1672 $dump =
new CrashDump($this, $this->pluginManager ??
null);
1674 $crashDumpPath = $this->writeCrashDumpFile($dump);
1676 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_submit($crashDumpPath)));
1678 if($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_ENABLED,
true)){
1681 $stamp = Path::join($this->dataPath,
"crashdumps",
".last_crash");
1682 $crashInterval = 120;
1683 if(($lastReportTime = @filemtime($stamp)) !==
false && $lastReportTime + $crashInterval >= time()){
1685 $this->logger->debug(
"Not sending crashdump due to last crash less than $crashInterval seconds ago");
1689 if($dump->getData()->error[
"type"] === \ParseError::class){
1693 if(strrpos(VersionInfo::GIT_HASH(),
"-dirty") !==
false || VersionInfo::GIT_HASH() === str_repeat(
"00", 20)){
1694 $this->logger->debug(
"Not sending crashdump due to locally modified");
1699 $url = ($this->configGroup->getPropertyBool(Yml::AUTO_REPORT_USE_HTTPS,
true) ?
"https" :
"http") .
"://" . $this->configGroup->getPropertyString(Yml::AUTO_REPORT_HOST,
"crash.pmmp.io") .
"/submit/api";
1700 $postUrlError =
"Unknown error";
1701 $reply = Internet::postURL($url, [
1703 "name" => $this->getName() .
" " . $this->getPocketMineVersion(),
1705 "reportPaste" => base64_encode($dump->getEncodedData())
1706 ], 10, [], $postUrlError);
1708 if($reply !==
null && is_object($data = json_decode($reply->getBody()))){
1709 if(isset($data->crashId) && is_int($data->crashId) && isset($data->crashUrl) && is_string($data->crashUrl)){
1710 $reportId = $data->crashId;
1711 $reportUrl = $data->crashUrl;
1712 $this->logger->emergency($this->language->translate(KnownTranslationFactory::pocketmine_crash_archive($reportUrl, (
string) $reportId)));
1713 }elseif(isset($data->error) && is_string($data->error)){
1714 $this->logger->emergency(
"Automatic crash report submission failed: $data->error");
1716 $this->logger->emergency(
"Invalid JSON response received from crash archive: " . $reply->getBody());
1719 $this->logger->emergency(
"Failed to communicate with crash archive: $postUrlError");
1723 }
catch(\Throwable $e){
1724 $this->logger->logException($e);
1726 $this->logger->critical($this->language->translate(KnownTranslationFactory::pocketmine_crash_error($e->getMessage())));
1727 }
catch(\Throwable $e){}
1730 $this->forceShutdown();
1731 $this->isRunning =
false;
1734 $uptime = time() - ((int) $this->startTime);
1736 $spacing = $minUptime - $uptime;
1738 echo
"--- Uptime {$uptime}s - waiting {$spacing}s to throttle automatic restart (you can kill the process safely now) ---" . PHP_EOL;
1741 @Process::kill(Process::pid());
1753 return $this->tickSleeper;
1756 private function tickProcessor() : void{
1757 $this->nextTick = microtime(true);
1759 while($this->isRunning){
1763 $this->tickSleeper->sleepUntil($this->nextTick);
1767 public function addOnlinePlayer(Player $player) : bool{
1768 $ev = new PlayerLoginEvent($player,
"Plugin reason");
1770 if($ev->isCancelled() || !$player->isConnected()){
1771 $player->disconnect($ev->getKickMessage());
1776 $session = $player->getNetworkSession();
1777 $position = $player->getPosition();
1778 $this->logger->info($this->language->translate(KnownTranslationFactory::pocketmine_player_logIn(
1779 TextFormat::AQUA . $player->getName() . TextFormat::RESET,
1781 (
string) $session->getPort(),
1782 (
string) $player->getId(),
1783 $position->getWorld()->getDisplayName(),
1784 (
string) round($position->x, 4),
1785 (
string) round($position->y, 4),
1786 (
string) round($position->z, 4)
1789 foreach($this->playerList as $p){
1790 $p->getNetworkSession()->onPlayerAdded($player);
1792 $rawUUID = $player->getUniqueId()->getBytes();
1793 $this->playerList[$rawUUID] = $player;
1795 if($this->sendUsageTicker > 0){
1796 $this->uniquePlayers[$rawUUID] = $rawUUID;
1802 public function removeOnlinePlayer(Player $player) : void{
1803 if(isset($this->playerList[$rawUUID = $player->getUniqueId()->getBytes()])){
1804 unset($this->playerList[$rawUUID]);
1805 foreach($this->playerList as $p){
1806 $p->getNetworkSession()->onPlayerRemoved($player);
1811 public function sendUsage(
int $type = SendUsageTask::TYPE_STATUS) : void{
1812 if($this->configGroup->getPropertyBool(Yml::ANONYMOUS_STATISTICS_ENABLED, true)){
1813 $this->asyncPool->submitTask(
new SendUsageTask($this, $type, $this->uniquePlayers));
1815 $this->uniquePlayers = [];
1818 public function getLanguage() : Language{
1819 return $this->language;
1822 public function isLanguageForced() : bool{
1823 return $this->forceLanguage;
1829 public function getAuthKeyProvider() : AuthKeyProvider{
1830 return $this->authKeyProvider;
1833 public function getNetwork() : Network{
1834 return $this->network;
1837 public function getMemoryManager() : MemoryManager{
1838 return $this->memoryManager;
1841 private function titleTick() : void{
1842 Timings::$titleTick->startTiming();
1844 $u = Process::getAdvancedMemoryUsage();
1845 $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());
1847 $online = count($this->playerList);
1848 $connecting = $this->network->getConnectionCount() - $online;
1849 $bandwidthStats = $this->network->getBandwidthTracker();
1851 echo
"\x1b]0;" . $this->getName() .
" " .
1852 $this->getPocketMineVersion() .
1853 " | Online $online/" . $this->maxPlayers .
1854 ($connecting > 0 ?
" (+$connecting connecting)" :
"") .
1855 " | Memory " . $usage .
1856 " | U " . round($bandwidthStats->getSend()->getAverageBytes() / 1024, 2) .
1857 " D " . round($bandwidthStats->getReceive()->getAverageBytes() / 1024, 2) .
1858 " kB/s | TPS " . $this->getTicksPerSecondAverage() .
1859 " | Load " . $this->getTickUsageAverage() .
"%\x07";
1861 Timings::$titleTick->stopTiming();
1867 private function tick() : void{
1868 $tickTime = microtime(true);
1869 if(($tickTime - $this->nextTick) < -0.025){
1873 Timings::$serverTick->startTiming();
1875 ++$this->tickCounter;
1877 Timings::$scheduler->startTiming();
1878 $this->pluginManager->tickSchedulers($this->tickCounter);
1879 Timings::$scheduler->stopTiming();
1881 Timings::$schedulerAsync->startTiming();
1882 $this->asyncPool->collectTasks();
1883 Timings::$schedulerAsync->stopTiming();
1885 $this->worldManager->tick($this->tickCounter);
1887 Timings::$connection->startTiming();
1888 $this->network->tick();
1889 Timings::$connection->stopTiming();
1891 if(($this->tickCounter % self::TARGET_TICKS_PER_SECOND) === 0){
1892 if($this->doTitleTick){
1895 $this->currentTPS = self::TARGET_TICKS_PER_SECOND;
1896 $this->currentUse = 0;
1898 $queryRegenerateEvent =
new QueryRegenerateEvent(
new QueryInfo($this));
1899 $queryRegenerateEvent->call();
1900 $this->queryInfo = $queryRegenerateEvent->getQueryInfo();
1902 $this->network->updateName();
1903 $this->network->getBandwidthTracker()->rotateAverageHistory();
1906 if($this->sendUsageTicker > 0 && --$this->sendUsageTicker === 0){
1907 $this->sendUsageTicker = self::TICKS_PER_STATS_REPORT;
1908 $this->sendUsage(SendUsageTask::TYPE_STATUS);
1911 if(($this->tickCounter % self::TICKS_PER_WORLD_CACHE_CLEAR) === 0){
1912 foreach($this->worldManager->getWorlds() as $world){
1913 $world->clearCache();
1917 if(($this->tickCounter % self::TICKS_PER_TPS_OVERLOAD_WARNING) === 0 && $this->getTicksPerSecondAverage() < self::TPS_OVERLOAD_WARNING_THRESHOLD){
1918 $this->logger->warning($this->language->translate(KnownTranslationFactory::pocketmine_server_tickOverload()));
1921 $this->memoryManager->check();
1923 if($this->console !==
null){
1924 Timings::$serverCommand->startTiming();
1925 while(($line = $this->console->readLine()) !==
null){
1926 $this->consoleSender ??=
new ConsoleCommandSender($this, $this->language);
1927 $this->dispatchCommand($this->consoleSender, $line);
1929 Timings::$serverCommand->stopTiming();
1932 Timings::$serverTick->stopTiming();
1934 $now = microtime(
true);
1935 $totalTickTimeSeconds = $now - $tickTime + ($this->tickSleeper->getNotificationProcessingTime() / 1_000_000_000);
1936 $this->currentTPS = min(self::TARGET_TICKS_PER_SECOND, 1 / max(0.001, $totalTickTimeSeconds));
1937 $this->currentUse = min(1, $totalTickTimeSeconds / self::TARGET_SECONDS_PER_TICK);
1939 TimingsHandler::tick($this->currentTPS <= $this->profilingTickRate);
1941 $idx = $this->tickCounter % self::TARGET_TICKS_PER_SECOND;
1942 $this->tickAverage[$idx] = $this->currentTPS;
1943 $this->useAverage[$idx] = $this->currentUse;
1944 $this->tickSleeper->resetNotificationProcessingTime();
1946 if(($this->nextTick - $tickTime) < -1){
1947 $this->nextTick = $tickTime;
1949 $this->nextTick += self::TARGET_SECONDS_PER_TICK;