3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #ifndef SERVER // Dedicated server isn't linked with Irrlicht
22 #pragma comment(lib, "Irrlicht.lib")
23 // This would get rid of the console window
24 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
26 #pragma comment(lib, "zlibwapi.lib")
27 #pragma comment(lib, "Shell32.lib")
30 #include "irrlicht.h" // createDevice
33 #include "mainmenumanager.h"
34 #include "irrlichttypes_extrabloated.h"
40 #include "guiMainMenu.h"
42 #include "defaultsettings.h"
46 #include "quicktune.h"
47 #include "httpfetch.h"
48 #include "guiEngine.h"
50 #include "mapsector.h"
51 #include "fontengine.h"
52 #include "gameparams.h"
55 #include "client/clientlauncher.h"
58 #ifdef HAVE_TOUCHSCREENGUI
59 #include "touchscreengui.h"
64 These are loaded from the config file.
66 static Settings main_settings;
67 Settings *g_settings = &main_settings;
68 std::string g_settings_path;
71 Profiler main_profiler;
72 Profiler *g_profiler = &main_profiler;
74 // Menu clouds are created later
75 Clouds *g_menuclouds = 0;
76 irr::scene::ISceneManager *g_menucloudsmgr = 0;
83 std::ostream *dout_con_ptr = &dummyout;
84 std::ostream *derr_con_ptr = &verbosestream;
87 std::ostream *dout_server_ptr = &infostream;
88 std::ostream *derr_server_ptr = &errorstream;
91 std::ostream *dout_client_ptr = &infostream;
92 std::ostream *derr_client_ptr = &errorstream;
94 #define DEBUGFILE "debug.txt"
95 #define DEFAULT_SERVER_PORT 30000
97 typedef std::map<std::string, ValueSpec> OptionList;
99 /**********************************************************************
101 **********************************************************************/
103 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
104 static void set_allowed_options(OptionList *allowed_options);
106 static void print_help(const OptionList &allowed_options);
107 static void print_allowed_options(const OptionList &allowed_options);
108 static void print_version();
109 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
111 static void print_modified_quicktune_values();
113 static void list_game_ids();
114 static void list_worlds();
115 static void setup_log_params(const Settings &cmd_args);
116 static bool create_userdata_path();
117 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
118 static void startup_message();
119 static bool read_config_file(const Settings &cmd_args);
120 static void init_debug_streams(int *log_level, const Settings &cmd_args);
122 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
123 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
125 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
126 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
127 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
128 static bool auto_select_world(GameParams *game_params);
129 static std::string get_clean_world_path(const std::string &path);
131 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
132 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
133 static bool determine_subgame(GameParams *game_params);
135 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
136 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args);
138 /**********************************************************************/
145 /* mainmenumanager.h */
147 gui::IGUIEnvironment* guienv = NULL;
148 gui::IGUIStaticText *guiroot = NULL;
149 MainMenuManager g_menumgr;
153 return (g_menumgr.menuCount() == 0);
156 // Passed to menus to allow disconnecting and exiting
157 MainGameCallback *g_gamecallback = NULL;
161 gettime.h implementation
168 /* Use imprecise system calls directly (from porting.h) */
169 return porting::getTime(PRECISION_MILLI);
172 u32 getTime(TimePrecision prec)
174 return porting::getTime(prec);
179 class StderrLogOutput: public ILogOutput
182 /* line: Full line with timestamp, level and thread */
183 void printLog(const std::string &line)
185 std::cerr << line << std::endl;
187 } main_stderr_log_out;
189 class DstreamNoStderrLogOutput: public ILogOutput
192 /* line: Full line with timestamp, level and thread */
193 void printLog(const std::string &line)
195 dstream_no_stderr << line << std::endl;
197 } main_dstream_no_stderr_log_out;
199 static OptionList allowed_options;
201 int main(int argc, char *argv[])
205 debug_set_exception_handler();
207 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
208 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
210 log_register_thread("main");
213 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
215 || cmd_args.getFlag("help")
216 || cmd_args.exists("nonopt1")) {
217 print_help(allowed_options);
218 return cmd_args_ok ? 0 : 1;
221 if (cmd_args.getFlag("version")) {
226 setup_log_params(cmd_args);
228 porting::signal_handler_init();
229 porting::initializePaths();
231 if (!create_userdata_path()) {
232 errorstream << "Cannot create user data directory" << std::endl;
236 // Initialize debug stacks
238 DSTACK(__FUNCTION_NAME);
241 BEGIN_DEBUG_EXCEPTION_HANDLER
243 // List gameids if requested
244 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
249 // List worlds if requested
250 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
255 GameParams game_params;
256 if (!init_common(&game_params.log_level, cmd_args, argc, argv))
261 if (cmd_args.getFlag("run-unittests")) {
268 game_params.is_dedicated_server = true;
270 game_params.is_dedicated_server = cmd_args.getFlag("server");
273 if (!game_configure(&game_params, cmd_args))
276 sanity_check(game_params.world_path != "");
278 infostream << "Using commanded world path ["
279 << game_params.world_path << "]" << std::endl;
281 //Run dedicated server if asked to or no other option
282 g_settings->set("server_dedicated",
283 game_params.is_dedicated_server ? "true" : "false");
285 if (game_params.is_dedicated_server)
286 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
289 ClientLauncher launcher;
290 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
295 // Update configuration file
296 if (g_settings_path != "")
297 g_settings->updateConfigFile(g_settings_path.c_str());
299 print_modified_quicktune_values();
301 // Stop httpfetch thread (if started)
304 END_DEBUG_EXCEPTION_HANDLER(errorstream)
310 /*****************************************************************************
312 *****************************************************************************/
315 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
317 set_allowed_options(&allowed_options);
319 return cmd_args->parseCommandLine(argc, argv, allowed_options);
322 static void set_allowed_options(OptionList *allowed_options)
324 allowed_options->clear();
326 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
327 _("Show allowed options"))));
328 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
329 _("Show version information"))));
330 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
331 _("Load configuration from specified file"))));
332 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
333 _("Set network port (UDP)"))));
334 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
335 _("Run the unit tests and exit"))));
336 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
337 _("Same as --world (deprecated)"))));
338 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
339 _("Set world path (implies local game) ('list' lists all)"))));
340 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
341 _("Set world by name (implies local game)"))));
342 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
343 _("Print to console errors only"))));
344 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
345 _("Print more information to console"))));
346 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
347 _("Print even more information to console"))));
348 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
349 _("Print enormous amounts of information to log and console"))));
350 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
351 _("Set logfile path ('' = no logging)"))));
352 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
353 _("Set gameid (\"--gameid list\" prints available ones)"))));
354 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
355 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
357 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
358 _("Show available video modes"))));
359 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
360 _("Run speed tests"))));
361 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
362 _("Address to connect to. ('' = local game)"))));
363 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
364 _("Enable random user input, for testing"))));
365 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
366 _("Run dedicated server"))));
367 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
368 _("Set player name"))));
369 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
370 _("Set password"))));
371 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
372 _("Disable main menu"))));
377 static void print_help(const OptionList &allowed_options)
379 dstream << _("Allowed options:") << std::endl;
380 print_allowed_options(allowed_options);
383 static void print_allowed_options(const OptionList &allowed_options)
385 for (OptionList::const_iterator i = allowed_options.begin();
386 i != allowed_options.end(); ++i) {
387 std::ostringstream os1(std::ios::binary);
388 os1 << " --" << i->first;
389 if (i->second.type != VALUETYPE_FLAG)
390 os1 << _(" <value>");
392 dstream << padStringRight(os1.str(), 24);
394 if (i->second.help != NULL)
395 dstream << i->second.help;
397 dstream << std::endl;
401 static void print_version()
404 dstream << "minetestserver " << minetest_version_hash << std::endl;
406 dstream << "Minetest " << minetest_version_hash << std::endl;
407 dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
409 dstream << "Build info: " << minetest_build_info << std::endl;
412 static void list_game_ids()
414 std::set<std::string> gameids = getAvailableGameIds();
415 for (std::set<std::string>::const_iterator i = gameids.begin();
416 i != gameids.end(); i++)
417 dstream << (*i) <<std::endl;
420 static void list_worlds()
422 dstream << _("Available worlds:") << std::endl;
423 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
424 print_worldspecs(worldspecs, dstream);
427 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
430 for (size_t i = 0; i < worldspecs.size(); i++) {
431 std::string name = worldspecs[i].name;
432 std::string path = worldspecs[i].path;
433 if (name.find(" ") != std::string::npos)
434 name = std::string("'") + name + "'";
435 path = std::string("'") + path + "'";
436 name = padStringRight(name, 14);
437 os << " " << name << " " << path << std::endl;
441 static void print_modified_quicktune_values()
443 bool header_printed = false;
444 std::vector<std::string> names = getQuicktuneNames();
446 for (u32 i = 0; i < names.size(); i++) {
447 QuicktuneValue val = getQuicktuneValue(names[i]);
450 if (!header_printed) {
451 dstream << "Modified quicktune values:" << std::endl;
452 header_printed = true;
454 dstream << names[i] << " = " << val.getString() << std::endl;
458 static void setup_log_params(const Settings &cmd_args)
460 // Quiet mode, print errors only
461 if (cmd_args.getFlag("quiet")) {
462 log_remove_output(&main_stderr_log_out);
463 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
466 // If trace is enabled, enable logging of certain things
467 if (cmd_args.getFlag("trace")) {
468 dstream << _("Enabling trace level debug output") << std::endl;
469 log_trace_level_enabled = true;
470 dout_con_ptr = &verbosestream; // this is somewhat old crap
471 socket_enable_debug_output = true; // socket doesn't use log.h
474 // In certain cases, output info level on stderr
475 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
476 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
477 log_add_output(&main_stderr_log_out, LMT_INFO);
479 // In certain cases, output verbose level on stderr
480 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
481 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
484 static bool create_userdata_path()
489 porting::initAndroid();
491 porting::setExternalStorageDir(porting::jnienv);
492 if (!fs::PathExists(porting::path_user)) {
493 success = fs::CreateDir(porting::path_user);
497 porting::copyAssets();
499 // Create user data directory
500 success = fs::CreateDir(porting::path_user);
503 infostream << "path_share = " << porting::path_share << std::endl;
504 infostream << "path_user = " << porting::path_user << std::endl;
509 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[])
512 set_default_settings(g_settings);
514 // Initialize sockets
516 atexit(sockets_cleanup);
518 if (!read_config_file(cmd_args))
521 init_debug_streams(log_level, cmd_args);
523 // Initialize random seed
527 // Initialize HTTP fetcher
528 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
531 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
532 g_settings->get("language"), argc, argv);
534 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
535 g_settings->get("language"));
541 static void startup_message()
543 infostream << PROJECT_NAME << " " << _("with")
544 << " SER_FMT_VER_HIGHEST_READ="
545 << (int)SER_FMT_VER_HIGHEST_READ << ", "
546 << minetest_build_info << std::endl;
549 static bool read_config_file(const Settings &cmd_args)
551 // Path of configuration file in use
552 sanity_check(g_settings_path == ""); // Sanity check
554 if (cmd_args.exists("config")) {
555 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
557 errorstream << "Could not read configuration from \""
558 << cmd_args.get("config") << "\"" << std::endl;
561 g_settings_path = cmd_args.get("config");
563 std::vector<std::string> filenames;
564 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
565 // Legacy configuration file location
566 filenames.push_back(porting::path_user +
567 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
570 // Try also from a lower level (to aid having the same configuration
571 // for many RUN_IN_PLACE installs)
572 filenames.push_back(porting::path_user +
573 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
576 for (size_t i = 0; i < filenames.size(); i++) {
577 bool r = g_settings->readConfigFile(filenames[i].c_str());
579 g_settings_path = filenames[i];
584 // If no path found, use the first one (menu creates the file)
585 if (g_settings_path == "")
586 g_settings_path = filenames[0];
592 static void init_debug_streams(int *log_level, const Settings &cmd_args)
595 std::string logfile = DEBUGFILE;
597 std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
599 if (cmd_args.exists("logfile"))
600 logfile = cmd_args.get("logfile");
602 log_remove_output(&main_dstream_no_stderr_log_out);
603 *log_level = g_settings->getS32("debug_log_level");
605 if (*log_level == 0) //no logging
607 if (*log_level < 0) {
608 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
610 } else if (*log_level > LMT_NUM_VALUES) {
611 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
612 << "; Using " << LMT_NUM_VALUES << std::endl;
613 *log_level = LMT_NUM_VALUES;
616 log_add_output_maxlev(&main_dstream_no_stderr_log_out,
617 (LogMessageLevel)(*log_level - 1));
619 debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
621 infostream << "logfile = " << logfile << std::endl;
623 atexit(debugstreams_deinit);
626 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
628 game_configure_port(game_params, cmd_args);
630 if (!game_configure_world(game_params, cmd_args)) {
631 errorstream << "No world path specified or found." << std::endl;
635 game_configure_subgame(game_params, cmd_args);
640 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
642 if (cmd_args.exists("port"))
643 game_params->socket_port = cmd_args.getU16("port");
645 game_params->socket_port = g_settings->getU16("port");
647 if (game_params->socket_port == 0)
648 game_params->socket_port = DEFAULT_SERVER_PORT;
651 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
653 if (get_world_from_cmdline(game_params, cmd_args))
655 if (get_world_from_config(game_params, cmd_args))
658 return auto_select_world(game_params);
661 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
663 std::string commanded_world = "";
666 std::string commanded_worldname = "";
667 if (cmd_args.exists("worldname"))
668 commanded_worldname = cmd_args.get("worldname");
670 // If a world name was specified, convert it to a path
671 if (commanded_worldname != "") {
672 // Get information about available worlds
673 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
675 for (u32 i = 0; i < worldspecs.size(); i++) {
676 std::string name = worldspecs[i].name;
677 if (name == commanded_worldname) {
678 dstream << _("Using world specified by --worldname on the "
679 "command line") << std::endl;
680 commanded_world = worldspecs[i].path;
686 dstream << _("World") << " '" << commanded_worldname
687 << _("' not available. Available worlds:") << std::endl;
688 print_worldspecs(worldspecs, dstream);
692 game_params->world_path = get_clean_world_path(commanded_world);
693 return commanded_world != "";
696 if (cmd_args.exists("world"))
697 commanded_world = cmd_args.get("world");
698 else if (cmd_args.exists("map-dir"))
699 commanded_world = cmd_args.get("map-dir");
700 else if (cmd_args.exists("nonopt0")) // First nameless argument
701 commanded_world = cmd_args.get("nonopt0");
703 game_params->world_path = get_clean_world_path(commanded_world);
704 return commanded_world != "";
707 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
710 std::string commanded_world = "";
712 if (g_settings->exists("map-dir"))
713 commanded_world = g_settings->get("map-dir");
715 game_params->world_path = get_clean_world_path(commanded_world);
717 return commanded_world != "";
720 static bool auto_select_world(GameParams *game_params)
722 // No world was specified; try to select it automatically
723 // Get information about available worlds
725 verbosestream << _("Determining world path") << std::endl;
727 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
728 std::string world_path;
730 // If there is only a single world, use it
731 if (worldspecs.size() == 1) {
732 world_path = worldspecs[0].path;
733 dstream <<_("Automatically selecting world at") << " ["
734 << world_path << "]" << std::endl;
735 // If there are multiple worlds, list them
736 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
737 dstream << _("Multiple worlds are available.") << std::endl;
738 dstream << _("Please select one using --worldname <name>"
739 " or --world <path>") << std::endl;
740 print_worldspecs(worldspecs, dstream);
742 // If there are no worlds, automatically create a new one
744 // This is the ultimate default world path
745 world_path = porting::path_user + DIR_DELIM + "worlds" +
747 infostream << "Creating default world at ["
748 << world_path << "]" << std::endl;
751 assert(world_path != ""); // Post-condition
752 game_params->world_path = world_path;
756 static std::string get_clean_world_path(const std::string &path)
758 const std::string worldmt = "world.mt";
759 std::string clean_path;
761 if (path.size() > worldmt.size()
762 && path.substr(path.size() - worldmt.size()) == worldmt) {
763 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
764 clean_path = path.substr(0, path.size() - worldmt.size());
772 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
776 success = get_game_from_cmdline(game_params, cmd_args);
778 success = determine_subgame(game_params);
783 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
785 SubgameSpec commanded_gamespec;
787 if (cmd_args.exists("gameid")) {
788 std::string gameid = cmd_args.get("gameid");
789 commanded_gamespec = findSubgame(gameid);
790 if (!commanded_gamespec.isValid()) {
791 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
794 dstream << _("Using game specified by --gameid on the command line")
796 game_params->game_spec = commanded_gamespec;
803 static bool determine_subgame(GameParams *game_params)
805 SubgameSpec gamespec;
807 assert(game_params->world_path != ""); // Pre-condition
809 verbosestream << _("Determining gameid/gamespec") << std::endl;
810 // If world doesn't exist
811 if (game_params->world_path != ""
812 && !getWorldExists(game_params->world_path)) {
813 // Try to take gamespec from command line
814 if (game_params->game_spec.isValid()) {
815 gamespec = game_params->game_spec;
816 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
817 } else { // Otherwise we will be using "minetest"
818 gamespec = findSubgame(g_settings->get("default_game"));
819 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
820 if (!gamespec.isValid()) {
821 errorstream << "Subgame specified in default_game ["
822 << g_settings->get("default_game")
823 << "] is invalid." << std::endl;
827 } else { // World exists
828 std::string world_gameid = getWorldGameId(game_params->world_path, false);
829 // If commanded to use a gameid, do so
830 if (game_params->game_spec.isValid()) {
831 gamespec = game_params->game_spec;
832 if (game_params->game_spec.id != world_gameid) {
833 errorstream << "WARNING: Using commanded gameid ["
834 << gamespec.id << "]" << " instead of world gameid ["
835 << world_gameid << "]" << std::endl;
838 // If world contains an embedded game, use it;
839 // Otherwise find world from local system.
840 gamespec = findWorldSubgame(game_params->world_path);
841 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
845 if (!gamespec.isValid()) {
846 errorstream << "Subgame [" << gamespec.id << "] could not be found."
851 game_params->game_spec = gamespec;
856 /*****************************************************************************
858 *****************************************************************************/
859 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
861 DSTACK("Dedicated server branch");
863 verbosestream << _("Using world path") << " ["
864 << game_params.world_path << "]" << std::endl;
865 verbosestream << _("Using gameid") << " ["
866 << game_params.game_spec.id << "]" << std::endl;
869 std::string bind_str = g_settings->get("bind_address");
870 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
872 if (g_settings->getBool("ipv6_server")) {
873 bind_addr.setAddress((IPv6AddressBytes*) NULL);
876 bind_addr.Resolve(bind_str.c_str());
877 } catch (ResolveError &e) {
878 infostream << "Resolving bind address \"" << bind_str
879 << "\" failed: " << e.what()
880 << " -- Listening on all addresses." << std::endl;
882 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
883 errorstream << "Unable to listen on "
884 << bind_addr.serializeString()
885 << L" because IPv6 is disabled" << std::endl;
889 // Database migration
890 if (cmd_args.exists("migrate"))
891 return migrate_database(game_params, cmd_args);
894 Server server(game_params.world_path,
895 game_params.game_spec, false, bind_addr.isIPv6());
897 server.start(bind_addr);
900 bool &kill = *porting::signal_handler_killstatus();
901 dedicated_server_loop(server, kill);
906 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args)
908 std::string migrate_to = cmd_args.get("migrate");
910 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
911 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
912 errorstream << "Cannot read world.mt!" << std::endl;
915 if (!world_mt.exists("backend")) {
916 errorstream << "Please specify your current backend in world.mt:"
918 << " backend = {sqlite3|leveldb|redis|dummy}"
922 std::string backend = world_mt.get("backend");
923 if (backend == migrate_to) {
924 errorstream << "Cannot migrate: new backend is same"
925 << " as the old one" << std::endl;
928 Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
929 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
932 time_t last_update_time = 0;
933 bool &kill = *porting::signal_handler_killstatus();
935 std::vector<v3s16> blocks;
936 old_db->listAllLoadableBlocks(blocks);
938 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
939 if (kill) return false;
941 const std::string &data = old_db->loadBlock(*it);
943 new_db->saveBlock(*it, data);
945 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
947 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
948 std::cerr << " Migrated " << count << " blocks, "
949 << (100.0 * count / blocks.size()) << "% completed.\r";
952 last_update_time = time(NULL);
955 std::cerr << std::endl;
960 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
961 world_mt.set("backend", migrate_to);
962 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
963 errorstream << "Failed to update world.mt!" << std::endl;
965 actionstream << "world.mt updated" << std::endl;