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.
22 #pragma message ("Disabling unit tests")
24 #warning "Disabling unit tests"
27 #define ENABLE_TESTS 0
30 #define ENABLE_TESTS 1
34 #ifndef SERVER // Dedicated server isn't linked with Irrlicht
35 #pragma comment(lib, "Irrlicht.lib")
36 // This would get rid of the console window
37 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
39 #pragma comment(lib, "zlibwapi.lib")
40 #pragma comment(lib, "Shell32.lib")
43 #include "irrlicht.h" // createDevice
46 #include "mainmenumanager.h"
50 #include "irrlichttypes_extrabloated.h"
55 #include "constants.h"
61 #include "guiMainMenu.h"
66 #include "defaultsettings.h"
72 #include "util/string.h"
74 #include "quicktune.h"
75 #include "serverlist.h"
76 #include "httpfetch.h"
77 #include "guiEngine.h"
78 #include "mapsector.h"
80 #include "fontengine.h"
82 #include "database-sqlite3.h"
84 #include "database-leveldb.h"
88 #include "database-redis.h"
91 #ifdef HAVE_TOUCHSCREENGUI
92 #include "touchscreengui.h"
97 These are loaded from the config file.
99 static Settings main_settings;
100 Settings *g_settings = &main_settings;
101 std::string g_settings_path;
104 Profiler main_profiler;
105 Profiler *g_profiler = &main_profiler;
107 // Menu clouds are created later
108 Clouds *g_menuclouds = 0;
109 irr::scene::ISceneManager *g_menucloudsmgr = 0;
116 std::ostream *dout_con_ptr = &dummyout;
117 std::ostream *derr_con_ptr = &verbosestream;
120 std::ostream *dout_server_ptr = &infostream;
121 std::ostream *derr_server_ptr = &errorstream;
124 std::ostream *dout_client_ptr = &infostream;
125 std::ostream *derr_client_ptr = &errorstream;
127 #define DEBUGFILE "debug.txt"
128 #define DEFAULT_SERVER_PORT 30000
130 typedef std::map<std::string, ValueSpec> OptionList;
134 std::string world_path;
135 SubgameSpec game_spec;
136 bool is_dedicated_server;
140 /**********************************************************************
142 **********************************************************************/
144 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
145 static void set_allowed_options(OptionList *allowed_options);
147 static void print_help(const OptionList &allowed_options);
148 static void print_allowed_options(const OptionList &allowed_options);
149 static void print_version();
150 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
152 static void print_modified_quicktune_values();
154 static void list_game_ids();
155 static void list_worlds();
156 static void setup_log_params(const Settings &cmd_args);
157 static bool create_userdata_path();
158 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
159 static void startup_message();
160 static bool read_config_file(const Settings &cmd_args);
161 static void init_debug_streams(int *log_level, const Settings &cmd_args);
163 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
164 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
166 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
167 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
168 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
169 static bool auto_select_world(GameParams *game_params);
170 static std::string get_clean_world_path(const std::string &path);
172 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
173 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
174 static bool determine_subgame(GameParams *game_params);
176 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
177 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
181 static bool print_video_modes();
182 static void speed_tests();
185 /**********************************************************************/
192 /* mainmenumanager.h */
194 gui::IGUIEnvironment* guienv = NULL;
195 gui::IGUIStaticText *guiroot = NULL;
196 MainMenuManager g_menumgr;
200 return (g_menumgr.menuCount() == 0);
203 // Passed to menus to allow disconnecting and exiting
204 MainGameCallback *g_gamecallback = NULL;
208 gettime.h implementation
215 /* Use imprecise system calls directly (from porting.h) */
216 return porting::getTime(PRECISION_MILLI);
219 u32 getTime(TimePrecision prec)
221 return porting::getTime(prec);
226 // A small helper class
230 virtual u32 getTime(TimePrecision prec) = 0;
233 // A precise irrlicht one
234 class IrrlichtTimeGetter: public TimeGetter
237 IrrlichtTimeGetter(IrrlichtDevice *device):
240 u32 getTime(TimePrecision prec)
242 if (prec == PRECISION_MILLI) {
243 if (m_device == NULL)
245 return m_device->getTimer()->getRealTime();
247 return porting::getTime(prec);
251 IrrlichtDevice *m_device;
253 // Not so precise one which works without irrlicht
254 class SimpleTimeGetter: public TimeGetter
257 u32 getTime(TimePrecision prec)
259 return porting::getTime(prec);
263 // A pointer to a global instance of the time getter
265 TimeGetter *g_timegetter = NULL;
269 if (g_timegetter == NULL)
271 return g_timegetter->getTime(PRECISION_MILLI);
274 u32 getTime(TimePrecision prec) {
275 if (g_timegetter == NULL)
277 return g_timegetter->getTime(prec);
281 class StderrLogOutput: public ILogOutput
284 /* line: Full line with timestamp, level and thread */
285 void printLog(const std::string &line)
287 std::cerr << line << std::endl;
289 } main_stderr_log_out;
291 class DstreamNoStderrLogOutput: public ILogOutput
294 /* line: Full line with timestamp, level and thread */
295 void printLog(const std::string &line)
297 dstream_no_stderr << line << std::endl;
299 } main_dstream_no_stderr_log_out;
304 Event handler for Irrlicht
306 NOTE: Everything possible should be moved out from here,
307 probably to InputHandler and the_game
310 class MyEventReceiver : public IEventReceiver
313 // This is the one method that we have to implement
314 virtual bool OnEvent(const SEvent& event)
317 React to nothing here if a menu is active
319 if (noMenuActive() == false) {
320 #ifdef HAVE_TOUCHSCREENGUI
321 if (m_touchscreengui != 0) {
322 m_touchscreengui->Toggle(false);
325 return g_menumgr.preprocessEvent(event);
328 // Remember whether each key is down or up
329 if (event.EventType == irr::EET_KEY_INPUT_EVENT) {
330 if (event.KeyInput.PressedDown) {
331 keyIsDown.set(event.KeyInput);
332 keyWasDown.set(event.KeyInput);
334 keyIsDown.unset(event.KeyInput);
338 #ifdef HAVE_TOUCHSCREENGUI
339 // case of touchscreengui we have to handle different events
340 if ((m_touchscreengui != 0) &&
341 (event.EventType == irr::EET_TOUCH_INPUT_EVENT)) {
342 m_touchscreengui->translateEvent(event);
346 // handle mouse events
347 if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) {
348 if (noMenuActive() == false) {
350 middle_active = false;
351 right_active = false;
353 left_active = event.MouseInput.isLeftPressed();
354 middle_active = event.MouseInput.isMiddlePressed();
355 right_active = event.MouseInput.isRightPressed();
357 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
360 if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN) {
363 if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
366 if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP) {
367 rightreleased = true;
369 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
370 mouse_wheel += event.MouseInput.Wheel;
374 if (event.EventType == irr::EET_LOG_TEXT_EVENT) {
375 dstream << std::string("Irrlicht log: ") + std::string(event.LogEvent.Text)
379 /* always return false in order to continue processing events */
383 bool IsKeyDown(const KeyPress &keyCode) const
385 return keyIsDown[keyCode];
388 // Checks whether a key was down and resets the state
389 bool WasKeyDown(const KeyPress &keyCode)
391 bool b = keyWasDown[keyCode];
393 keyWasDown.unset(keyCode);
410 rightclicked = false;
411 leftreleased = false;
412 rightreleased = false;
415 middle_active = false;
416 right_active = false;
424 #ifdef HAVE_TOUCHSCREENGUI
425 m_touchscreengui = NULL;
440 #ifdef HAVE_TOUCHSCREENGUI
441 TouchScreenGUI* m_touchscreengui;
445 // The current state of keys
447 // Whether a key has been pressed or not
452 Separated input handler
455 class RealInputHandler : public InputHandler
458 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
460 m_receiver(receiver),
464 virtual bool isKeyDown(const KeyPress &keyCode)
466 return m_receiver->IsKeyDown(keyCode);
468 virtual bool wasKeyDown(const KeyPress &keyCode)
470 return m_receiver->WasKeyDown(keyCode);
472 virtual v2s32 getMousePos()
474 if (m_device->getCursorControl()) {
475 return m_device->getCursorControl()->getPosition();
481 virtual void setMousePos(s32 x, s32 y)
483 if (m_device->getCursorControl()) {
484 m_device->getCursorControl()->setPosition(x, y);
487 m_mousepos = v2s32(x,y);
491 virtual bool getLeftState()
493 return m_receiver->left_active;
495 virtual bool getRightState()
497 return m_receiver->right_active;
500 virtual bool getLeftClicked()
502 return m_receiver->leftclicked;
504 virtual bool getRightClicked()
506 return m_receiver->rightclicked;
508 virtual void resetLeftClicked()
510 m_receiver->leftclicked = false;
512 virtual void resetRightClicked()
514 m_receiver->rightclicked = false;
517 virtual bool getLeftReleased()
519 return m_receiver->leftreleased;
521 virtual bool getRightReleased()
523 return m_receiver->rightreleased;
525 virtual void resetLeftReleased()
527 m_receiver->leftreleased = false;
529 virtual void resetRightReleased()
531 m_receiver->rightreleased = false;
534 virtual s32 getMouseWheel()
536 return m_receiver->getMouseWheel();
541 m_receiver->clearInput();
544 IrrlichtDevice *m_device;
545 MyEventReceiver *m_receiver;
549 class RandomInputHandler : public InputHandler
557 rightclicked = false;
558 leftreleased = false;
559 rightreleased = false;
562 virtual bool isKeyDown(const KeyPress &keyCode)
564 return keydown[keyCode];
566 virtual bool wasKeyDown(const KeyPress &keyCode)
570 virtual v2s32 getMousePos()
574 virtual void setMousePos(s32 x, s32 y)
576 mousepos = v2s32(x, y);
579 virtual bool getLeftState()
583 virtual bool getRightState()
588 virtual bool getLeftClicked()
592 virtual bool getRightClicked()
596 virtual void resetLeftClicked()
600 virtual void resetRightClicked()
602 rightclicked = false;
605 virtual bool getLeftReleased()
609 virtual bool getRightReleased()
611 return rightreleased;
613 virtual void resetLeftReleased()
615 leftreleased = false;
617 virtual void resetRightReleased()
619 rightreleased = false;
622 virtual s32 getMouseWheel()
627 virtual void step(float dtime)
630 static float counter1 = 0;
632 if (counter1 < 0.0) {
633 counter1 = 0.1 * Rand(1, 40);
634 keydown.toggle(getKeySetting("keymap_jump"));
638 static float counter1 = 0;
640 if (counter1 < 0.0) {
641 counter1 = 0.1 * Rand(1, 40);
642 keydown.toggle(getKeySetting("keymap_special1"));
646 static float counter1 = 0;
648 if (counter1 < 0.0) {
649 counter1 = 0.1 * Rand(1, 40);
650 keydown.toggle(getKeySetting("keymap_forward"));
654 static float counter1 = 0;
656 if (counter1 < 0.0) {
657 counter1 = 0.1 * Rand(1, 40);
658 keydown.toggle(getKeySetting("keymap_left"));
662 static float counter1 = 0;
664 if (counter1 < 0.0) {
665 counter1 = 0.1 * Rand(1, 20);
666 mousespeed = v2s32(Rand(-20, 20), Rand(-15, 20));
670 static float counter1 = 0;
672 if (counter1 < 0.0) {
673 counter1 = 0.1 * Rand(1, 30);
674 leftdown = !leftdown;
682 static float counter1 = 0;
684 if (counter1 < 0.0) {
685 counter1 = 0.1 * Rand(1, 15);
686 rightdown = !rightdown;
690 rightreleased = true;
693 mousepos += mousespeed;
696 s32 Rand(s32 min, s32 max)
698 return (myrand()%(max-min+1))+min;
717 list_video_modes(false),
718 skip_main_menu(false),
729 simple_singleplayer_mode(false),
730 current_playername("inv£lid"),
731 current_password(""),
732 current_address("does-not-exist"),
738 bool run(GameParams &game_params, const Settings &cmd_args);
741 void init_args(GameParams &game_params, const Settings &cmd_args);
742 bool init_engine(int log_level);
744 bool launch_game(std::wstring *error_message, GameParams &game_params,
745 const Settings &cmd_args);
747 void main_menu(MainMenuData *menudata);
748 bool create_engine_device(int log_level);
750 bool list_video_modes;
755 std::string playername;
756 std::string password;
757 IrrlichtDevice *device;
759 MyEventReceiver *receiver;
762 scene::ISceneManager *smgr;
763 SubgameSpec gamespec;
765 bool simple_singleplayer_mode;
767 // These are set up based on the menu and other things
768 // TODO: Are these required since there's already playername, password, etc
769 std::string current_playername;
770 std::string current_password;
771 std::string current_address;
777 static OptionList allowed_options;
779 int main(int argc, char *argv[])
783 debug_set_exception_handler();
785 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
786 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
788 log_register_thread("main");
791 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
793 || cmd_args.getFlag("help")
794 || cmd_args.exists("nonopt1")) {
795 print_help(allowed_options);
796 return cmd_args_ok ? 0 : 1;
799 if (cmd_args.getFlag("version")) {
804 setup_log_params(cmd_args);
806 porting::signal_handler_init();
807 porting::initializePaths();
809 if (!create_userdata_path()) {
810 errorstream << "Cannot create user data directory" << std::endl;
814 // Initialize debug stacks
816 DSTACK(__FUNCTION_NAME);
819 BEGIN_DEBUG_EXCEPTION_HANDLER
821 // List gameids if requested
822 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
827 // List worlds if requested
828 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
833 GameParams game_params;
834 if (!init_common(&game_params.log_level, cmd_args, argc, argv))
839 if ((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
840 || cmd_args.getFlag("enable-unittests") == true) {
846 game_params.is_dedicated_server = true;
848 game_params.is_dedicated_server = cmd_args.getFlag("server");
851 if (!game_configure(&game_params, cmd_args))
854 assert(game_params.world_path != "");
856 infostream << "Using commanded world path ["
857 << game_params.world_path << "]" << std::endl;
859 //Run dedicated server if asked to or no other option
860 g_settings->set("server_dedicated",
861 game_params.is_dedicated_server ? "true" : "false");
863 if (game_params.is_dedicated_server)
864 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
867 ClientLauncher launcher;
868 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
873 // Update configuration file
874 if (g_settings_path != "")
875 g_settings->updateConfigFile(g_settings_path.c_str());
877 print_modified_quicktune_values();
879 // Stop httpfetch thread (if started)
882 END_DEBUG_EXCEPTION_HANDLER(errorstream)
888 /*****************************************************************************
890 *****************************************************************************/
893 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
895 set_allowed_options(&allowed_options);
897 return cmd_args->parseCommandLine(argc, argv, allowed_options);
900 static void set_allowed_options(OptionList *allowed_options)
902 allowed_options->clear();
904 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
905 _("Show allowed options"))));
906 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
907 _("Show version information"))));
908 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
909 _("Load configuration from specified file"))));
910 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
911 _("Set network port (UDP)"))));
912 allowed_options->insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
913 _("Disable unit tests"))));
914 allowed_options->insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
915 _("Enable unit tests"))));
916 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
917 _("Same as --world (deprecated)"))));
918 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
919 _("Set world path (implies local game) ('list' lists all)"))));
920 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
921 _("Set world by name (implies local game)"))));
922 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
923 _("Print to console errors only"))));
924 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
925 _("Print more information to console"))));
926 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
927 _("Print even more information to console"))));
928 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
929 _("Print enormous amounts of information to log and console"))));
930 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
931 _("Set logfile path ('' = no logging)"))));
932 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
933 _("Set gameid (\"--gameid list\" prints available ones)"))));
934 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
935 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
937 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
938 _("Show available video modes"))));
939 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
940 _("Run speed tests"))));
941 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
942 _("Address to connect to. ('' = local game)"))));
943 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
944 _("Enable random user input, for testing"))));
945 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
946 _("Run dedicated server"))));
947 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
948 _("Set player name"))));
949 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
950 _("Set password"))));
951 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
952 _("Disable main menu"))));
957 static void print_help(const OptionList &allowed_options)
959 dstream << _("Allowed options:") << std::endl;
960 print_allowed_options(allowed_options);
963 static void print_allowed_options(const OptionList &allowed_options)
965 for (OptionList::const_iterator i = allowed_options.begin();
966 i != allowed_options.end(); ++i) {
967 std::ostringstream os1(std::ios::binary);
968 os1 << " --" << i->first;
969 if (i->second.type != VALUETYPE_FLAG)
970 os1 << _(" <value>");
972 dstream << padStringRight(os1.str(), 24);
974 if (i->second.help != NULL)
975 dstream << i->second.help;
977 dstream << std::endl;
981 static void print_version()
984 dstream << "minetestserver " << minetest_version_hash << std::endl;
986 dstream << "Minetest " << minetest_version_hash << std::endl;
987 dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
989 dstream << "Build info: " << minetest_build_info << std::endl;
992 static void list_game_ids()
994 std::set<std::string> gameids = getAvailableGameIds();
995 for (std::set<std::string>::const_iterator i = gameids.begin();
996 i != gameids.end(); i++)
997 dstream << (*i) <<std::endl;
1000 static void list_worlds()
1002 dstream << _("Available worlds:") << std::endl;
1003 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1004 print_worldspecs(worldspecs, dstream);
1007 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
1010 for (size_t i = 0; i < worldspecs.size(); i++) {
1011 std::string name = worldspecs[i].name;
1012 std::string path = worldspecs[i].path;
1013 if (name.find(" ") != std::string::npos)
1014 name = std::string("'") + name + "'";
1015 path = std::string("'") + path + "'";
1016 name = padStringRight(name, 14);
1017 os << " " << name << " " << path << std::endl;
1021 static void print_modified_quicktune_values()
1023 bool header_printed = false;
1024 std::vector<std::string> names = getQuicktuneNames();
1026 for (u32 i = 0; i < names.size(); i++) {
1027 QuicktuneValue val = getQuicktuneValue(names[i]);
1030 if (!header_printed) {
1031 dstream << "Modified quicktune values:" << std::endl;
1032 header_printed = true;
1034 dstream << names[i] << " = " << val.getString() << std::endl;
1038 static void setup_log_params(const Settings &cmd_args)
1040 // Quiet mode, print errors only
1041 if (cmd_args.getFlag("quiet")) {
1042 log_remove_output(&main_stderr_log_out);
1043 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
1046 // If trace is enabled, enable logging of certain things
1047 if (cmd_args.getFlag("trace")) {
1048 dstream << _("Enabling trace level debug output") << std::endl;
1049 log_trace_level_enabled = true;
1050 dout_con_ptr = &verbosestream; // this is somewhat old crap
1051 socket_enable_debug_output = true; // socket doesn't use log.h
1054 // In certain cases, output info level on stderr
1055 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
1056 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
1057 log_add_output(&main_stderr_log_out, LMT_INFO);
1059 // In certain cases, output verbose level on stderr
1060 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
1061 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
1064 static bool create_userdata_path()
1069 porting::initAndroid();
1071 porting::setExternalStorageDir(porting::jnienv);
1072 if (!fs::PathExists(porting::path_user)) {
1073 success = fs::CreateDir(porting::path_user);
1077 porting::copyAssets();
1079 // Create user data directory
1080 success = fs::CreateDir(porting::path_user);
1083 infostream << "path_share = " << porting::path_share << std::endl;
1084 infostream << "path_user = " << porting::path_user << std::endl;
1089 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[])
1092 set_default_settings(g_settings);
1094 // Initialize sockets
1096 atexit(sockets_cleanup);
1098 if (!read_config_file(cmd_args))
1101 init_debug_streams(log_level, cmd_args);
1103 // Initialize random seed
1107 // Initialize HTTP fetcher
1108 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1111 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1112 g_settings->get("language"), argc, argv);
1114 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1115 g_settings->get("language"));
1121 static void startup_message()
1123 infostream << PROJECT_NAME << " " << _("with")
1124 << " SER_FMT_VER_HIGHEST_READ="
1125 << (int)SER_FMT_VER_HIGHEST_READ << ", "
1126 << minetest_build_info << std::endl;
1129 static bool read_config_file(const Settings &cmd_args)
1131 // Path of configuration file in use
1132 assert(g_settings_path == ""); // Sanity check
1134 if (cmd_args.exists("config")) {
1135 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1137 errorstream << "Could not read configuration from \""
1138 << cmd_args.get("config") << "\"" << std::endl;
1141 g_settings_path = cmd_args.get("config");
1143 std::vector<std::string> filenames;
1144 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
1145 // Legacy configuration file location
1146 filenames.push_back(porting::path_user +
1147 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1150 // Try also from a lower level (to aid having the same configuration
1151 // for many RUN_IN_PLACE installs)
1152 filenames.push_back(porting::path_user +
1153 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1156 for (size_t i = 0; i < filenames.size(); i++) {
1157 bool r = g_settings->readConfigFile(filenames[i].c_str());
1159 g_settings_path = filenames[i];
1164 // If no path found, use the first one (menu creates the file)
1165 if (g_settings_path == "")
1166 g_settings_path = filenames[0];
1172 static void init_debug_streams(int *log_level, const Settings &cmd_args)
1175 std::string logfile = DEBUGFILE;
1177 std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
1179 if (cmd_args.exists("logfile"))
1180 logfile = cmd_args.get("logfile");
1182 log_remove_output(&main_dstream_no_stderr_log_out);
1183 *log_level = g_settings->getS32("debug_log_level");
1185 if (*log_level == 0) //no logging
1187 if (*log_level < 0) {
1188 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
1190 } else if (*log_level > LMT_NUM_VALUES) {
1191 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
1192 << "; Using " << LMT_NUM_VALUES << std::endl;
1193 *log_level = LMT_NUM_VALUES;
1196 log_add_output_maxlev(&main_dstream_no_stderr_log_out,
1197 (LogMessageLevel)(*log_level - 1));
1199 debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
1201 infostream << "logfile = " << logfile << std::endl;
1203 atexit(debugstreams_deinit);
1206 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
1208 game_configure_port(game_params, cmd_args);
1210 if (!game_configure_world(game_params, cmd_args)) {
1211 errorstream << "No world path specified or found." << std::endl;
1215 game_configure_subgame(game_params, cmd_args);
1220 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
1222 if (cmd_args.exists("port"))
1223 game_params->socket_port = cmd_args.getU16("port");
1225 game_params->socket_port = g_settings->getU16("port");
1227 if (game_params->socket_port == 0)
1228 game_params->socket_port = DEFAULT_SERVER_PORT;
1231 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
1233 if (get_world_from_cmdline(game_params, cmd_args))
1235 if (get_world_from_config(game_params, cmd_args))
1238 return auto_select_world(game_params);
1241 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1243 std::string commanded_world = "";
1246 std::string commanded_worldname = "";
1247 if (cmd_args.exists("worldname"))
1248 commanded_worldname = cmd_args.get("worldname");
1250 // If a world name was specified, convert it to a path
1251 if (commanded_worldname != "") {
1252 // Get information about available worlds
1253 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1255 for (u32 i = 0; i < worldspecs.size(); i++) {
1256 std::string name = worldspecs[i].name;
1257 if (name == commanded_worldname) {
1258 dstream << _("Using world specified by --worldname on the "
1259 "command line") << std::endl;
1260 commanded_world = worldspecs[i].path;
1266 dstream << _("World") << " '" << commanded_worldname
1267 << _("' not available. Available worlds:") << std::endl;
1268 print_worldspecs(worldspecs, dstream);
1272 game_params->world_path = get_clean_world_path(commanded_world);
1273 return commanded_world != "";
1276 if (cmd_args.exists("world"))
1277 commanded_world = cmd_args.get("world");
1278 else if (cmd_args.exists("map-dir"))
1279 commanded_world = cmd_args.get("map-dir");
1280 else if (cmd_args.exists("nonopt0")) // First nameless argument
1281 commanded_world = cmd_args.get("nonopt0");
1283 game_params->world_path = get_clean_world_path(commanded_world);
1284 return commanded_world != "";
1287 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
1290 std::string commanded_world = "";
1292 if (g_settings->exists("map-dir"))
1293 commanded_world = g_settings->get("map-dir");
1295 game_params->world_path = get_clean_world_path(commanded_world);
1297 return commanded_world != "";
1300 static bool auto_select_world(GameParams *game_params)
1302 // No world was specified; try to select it automatically
1303 // Get information about available worlds
1305 verbosestream << _("Determining world path") << std::endl;
1307 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1308 std::string world_path;
1310 // If there is only a single world, use it
1311 if (worldspecs.size() == 1) {
1312 world_path = worldspecs[0].path;
1313 dstream <<_("Automatically selecting world at") << " ["
1314 << world_path << "]" << std::endl;
1315 // If there are multiple worlds, list them
1316 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
1317 dstream << _("Multiple worlds are available.") << std::endl;
1318 dstream << _("Please select one using --worldname <name>"
1319 " or --world <path>") << std::endl;
1320 print_worldspecs(worldspecs, dstream);
1322 // If there are no worlds, automatically create a new one
1324 // This is the ultimate default world path
1325 world_path = porting::path_user + DIR_DELIM + "worlds" +
1326 DIR_DELIM + "world";
1327 infostream << "Creating default world at ["
1328 << world_path << "]" << std::endl;
1331 assert(world_path != "");
1332 game_params->world_path = world_path;
1336 static std::string get_clean_world_path(const std::string &path)
1338 const std::string worldmt = "world.mt";
1339 std::string clean_path;
1341 if (path.size() > worldmt.size()
1342 && path.substr(path.size() - worldmt.size()) == worldmt) {
1343 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
1344 clean_path = path.substr(0, path.size() - worldmt.size());
1352 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
1356 success = get_game_from_cmdline(game_params, cmd_args);
1358 success = determine_subgame(game_params);
1363 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1365 SubgameSpec commanded_gamespec;
1367 if (cmd_args.exists("gameid")) {
1368 std::string gameid = cmd_args.get("gameid");
1369 commanded_gamespec = findSubgame(gameid);
1370 if (!commanded_gamespec.isValid()) {
1371 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
1374 dstream << _("Using game specified by --gameid on the command line")
1376 game_params->game_spec = commanded_gamespec;
1383 static bool determine_subgame(GameParams *game_params)
1385 SubgameSpec gamespec;
1387 assert(game_params->world_path != ""); // pre-condition
1389 verbosestream << _("Determining gameid/gamespec") << std::endl;
1390 // If world doesn't exist
1391 if (game_params->world_path != ""
1392 && !getWorldExists(game_params->world_path)) {
1393 // Try to take gamespec from command line
1394 if (game_params->game_spec.isValid()) {
1395 gamespec = game_params->game_spec;
1396 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
1397 } else { // Otherwise we will be using "minetest"
1398 gamespec = findSubgame(g_settings->get("default_game"));
1399 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
1400 if (!gamespec.isValid()) {
1401 errorstream << "Subgame specified in default_game ["
1402 << g_settings->get("default_game")
1403 << "] is invalid." << std::endl;
1407 } else { // World exists
1408 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1409 // If commanded to use a gameid, do so
1410 if (game_params->game_spec.isValid()) {
1411 gamespec = game_params->game_spec;
1412 if (game_params->game_spec.id != world_gameid) {
1413 errorstream << "WARNING: Using commanded gameid ["
1414 << gamespec.id << "]" << " instead of world gameid ["
1415 << world_gameid << "]" << std::endl;
1418 // If world contains an embedded game, use it;
1419 // Otherwise find world from local system.
1420 gamespec = findWorldSubgame(game_params->world_path);
1421 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1425 if (!gamespec.isValid()) {
1426 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1431 game_params->game_spec = gamespec;
1436 /*****************************************************************************
1438 *****************************************************************************/
1439 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1441 DSTACK("Dedicated server branch");
1443 verbosestream << _("Using world path") << " ["
1444 << game_params.world_path << "]" << std::endl;
1445 verbosestream << _("Using gameid") << " ["
1446 << game_params.game_spec.id << "]" << std::endl;
1449 std::string bind_str = g_settings->get("bind_address");
1450 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1452 if (g_settings->getBool("ipv6_server")) {
1453 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1456 bind_addr.Resolve(bind_str.c_str());
1457 } catch (ResolveError &e) {
1458 infostream << "Resolving bind address \"" << bind_str
1459 << "\" failed: " << e.what()
1460 << " -- Listening on all addresses." << std::endl;
1462 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1463 errorstream << "Unable to listen on "
1464 << bind_addr.serializeString()
1465 << L" because IPv6 is disabled" << std::endl;
1470 Server server(game_params.world_path,
1471 game_params.game_spec, false, bind_addr.isIPv6());
1473 // Database migration
1474 if (cmd_args.exists("migrate"))
1475 return migrate_database(game_params, cmd_args, &server);
1477 server.start(bind_addr);
1480 bool &kill = *porting::signal_handler_killstatus();
1481 dedicated_server_loop(server, kill);
1486 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1490 bool success = world_mt.readConfigFile((game_params.world_path
1491 + DIR_DELIM + "world.mt").c_str());
1493 errorstream << "Cannot read world.mt" << std::endl;
1497 if (!world_mt.exists("backend")) {
1498 errorstream << "Please specify your current backend in world.mt file:"
1499 << std::endl << " backend = {sqlite3|leveldb|redis|dummy}"
1504 std::string backend = world_mt.get("backend");
1506 std::string migrate_to = cmd_args.get("migrate");
1508 if (backend == migrate_to) {
1509 errorstream << "Cannot migrate: new backend is same as the old one"
1514 if (migrate_to == "sqlite3")
1515 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1516 game_params.world_path);
1518 else if (migrate_to == "leveldb")
1519 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1520 game_params.world_path);
1523 else if (migrate_to == "redis")
1524 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1525 game_params.world_path);
1528 errorstream << "Migration to " << migrate_to << " is not supported"
1533 std::list<v3s16> blocks;
1534 ServerMap &old_map = ((ServerMap&)server->getMap());
1535 old_map.listAllLoadableBlocks(blocks);
1537 new_db->beginSave();
1538 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1539 MapBlock *block = old_map.loadBlock(*i);
1541 errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1543 old_map.saveBlock(block, new_db);
1544 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1545 sector->deleteBlock(block);
1548 if (count % 500 == 0)
1549 actionstream << "Migrated " << count << " blocks "
1550 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1555 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1556 world_mt.set("backend", migrate_to);
1557 if (!world_mt.updateConfigFile(
1558 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1559 errorstream << "Failed to update world.mt!" << std::endl;
1561 actionstream << "world.mt updated" << std::endl;
1567 /*****************************************************************************
1569 *****************************************************************************/
1572 ClientLauncher::~ClientLauncher()
1581 delete g_fontengine;
1588 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1590 init_args(game_params, cmd_args);
1592 // List video modes if requested
1593 if (list_video_modes)
1594 return print_video_modes();
1596 if (!init_engine(game_params.log_level)) {
1597 errorstream << "Could not initialize game engine." << std::endl;
1601 // Speed tests (done after irrlicht is loaded to get timer)
1602 if (cmd_args.getFlag("speedtests")) {
1603 dstream << "Running speed tests" << std::endl;
1608 video::IVideoDriver *video_driver = device->getVideoDriver();
1609 if (video_driver == NULL) {
1610 errorstream << "Could not initialize video driver." << std::endl;
1614 porting::setXorgClassHint(video_driver->getExposedVideoData(), "Minetest");
1617 This changes the minimum allowed number of vertices in a VBO.
1620 //driver->setMinHardwareBufferVertexCount(50);
1622 // Create time getter
1623 g_timegetter = new IrrlichtTimeGetter(device);
1625 // Create game callback for menus
1626 g_gamecallback = new MainGameCallback(device);
1628 device->setResizable(true);
1631 input = new RandomInputHandler();
1633 input = new RealInputHandler(device, receiver);
1635 smgr = device->getSceneManager();
1637 guienv = device->getGUIEnvironment();
1638 skin = guienv->getSkin();
1639 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1640 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1641 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1642 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1643 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1645 g_fontengine = new FontEngine(g_settings, guienv);
1646 assert(g_fontengine != NULL);
1648 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1649 // Irrlicht 1.8 input colours
1650 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1651 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1654 // Create the menu clouds
1655 if (!g_menucloudsmgr)
1656 g_menucloudsmgr = smgr->createNewSceneManager();
1658 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1659 g_menucloudsmgr, -1, rand(), 100);
1660 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1661 scene::ICameraSceneNode* camera;
1662 camera = g_menucloudsmgr->addCameraSceneNode(0,
1663 v3f(0, 0, 0), v3f(0, 60, 100));
1664 camera->setFarValue(10000);
1670 ChatBackend chat_backend;
1672 // If an error occurs, this is set to something by menu().
1673 // It is then displayed before the menu shows on the next call to menu()
1674 std::wstring error_message = L"";
1676 bool first_loop = true;
1682 bool *kill = porting::signal_handler_killstatus();
1684 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1686 // Set the window caption
1687 const wchar_t *text = wgettext("Main Menu");
1688 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1691 try { // This is used for catching disconnects
1696 We need some kind of a root node to be able to add
1697 custom gui elements directly on the screen.
1698 Otherwise they won't be automatically drawn.
1700 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1702 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1704 // If skip_main_menu, we only want to startup once
1705 if (skip_main_menu && !first_loop)
1710 if (!game_has_run) {
1717 // Break out of menu-game loop to shut down cleanly
1718 if (!device->run() || *kill) {
1719 if (g_settings_path != "")
1720 g_settings->updateConfigFile(g_settings_path.c_str());
1724 if (current_playername.length() > PLAYERNAME_SIZE-1) {
1725 error_message = wgettext("Player name too long.");
1726 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1727 g_settings->set("name", playername);
1731 device->getVideoDriver()->setTextureCreationFlag(
1732 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1734 #ifdef HAVE_TOUCHSCREENGUI
1735 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1736 g_touchscreengui = receiver->m_touchscreengui;
1751 simple_singleplayer_mode
1755 #ifdef HAVE_TOUCHSCREENGUI
1756 delete g_touchscreengui;
1757 g_touchscreengui = NULL;
1758 receiver->m_touchscreengui = NULL;
1762 catch (con::PeerNotFoundException &e) {
1763 error_message = wgettext("Connection error (timed out?)");
1764 errorstream << wide_to_narrow(error_message) << std::endl;
1768 catch (std::exception &e) {
1769 std::string narrow_message = "Some exception: \"";
1770 narrow_message += e.what();
1771 narrow_message += "\"";
1772 errorstream << narrow_message << std::endl;
1773 error_message = narrow_to_wide(narrow_message);
1777 // If no main menu, show error and exit
1778 if (skip_main_menu) {
1779 if (error_message != L"") {
1780 verbosestream << "error_message = "
1781 << wide_to_narrow(error_message) << std::endl;
1788 g_menuclouds->drop();
1789 g_menucloudsmgr->drop();
1794 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1797 skip_main_menu = cmd_args.getFlag("go");
1799 // FIXME: This is confusing (but correct)
1801 /* If world_path is set then override it unless skipping the main menu using
1802 * the --go command line param. Else, give preference to the address
1803 * supplied on the command line
1805 address = g_settings->get("address");
1806 if (game_params.world_path != "" && !skip_main_menu)
1808 else if (cmd_args.exists("address"))
1809 address = cmd_args.get("address");
1811 playername = g_settings->get("name");
1812 if (cmd_args.exists("name"))
1813 playername = cmd_args.get("name");
1815 list_video_modes = cmd_args.getFlag("videomodes");
1817 use_freetype = g_settings->getBool("freetype");
1819 random_input = g_settings->getBool("random_input")
1820 || cmd_args.getFlag("random-input");
1823 bool ClientLauncher::init_engine(int log_level)
1825 receiver = new MyEventReceiver();
1826 create_engine_device(log_level);
1827 return device != NULL;
1830 bool ClientLauncher::launch_game(std::wstring *error_message,
1831 GameParams &game_params, const Settings &cmd_args)
1833 // Initialize menu data
1834 MainMenuData menudata;
1835 menudata.address = address;
1836 menudata.name = playername;
1837 menudata.port = itos(game_params.socket_port);
1838 menudata.errormessage = wide_to_narrow(*error_message);
1840 *error_message = L"";
1842 if (cmd_args.exists("password"))
1843 menudata.password = cmd_args.get("password");
1845 menudata.enable_public = g_settings->getBool("server_announce");
1847 // If a world was commanded, append and select it
1848 if (game_params.world_path != "") {
1849 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1850 worldspec.name = _("[--world parameter]");
1852 if (worldspec.gameid == "") { // Create new
1853 worldspec.gameid = g_settings->get("default_game");
1854 worldspec.name += " [new]";
1856 worldspec.path = game_params.world_path;
1859 /* Show the GUI menu
1861 if (!skip_main_menu) {
1862 main_menu(&menudata);
1864 // Skip further loading if there was an exit signal.
1865 if (*porting::signal_handler_killstatus())
1868 address = menudata.address;
1869 int newport = stoi(menudata.port);
1871 game_params.socket_port = newport;
1873 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1875 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1877 if (menudata.selected_world >= 0
1878 && menudata.selected_world < (int)worldspecs.size()) {
1879 g_settings->set("selected_world_path",
1880 worldspecs[menudata.selected_world].path);
1881 worldspec = worldspecs[menudata.selected_world];
1885 if (menudata.errormessage != "") {
1886 /* The calling function will pass this back into this function upon the
1887 * next iteration (if any) causing it to be displayed by the GUI
1889 *error_message = narrow_to_wide(menudata.errormessage);
1893 if (menudata.name == "")
1894 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1896 playername = menudata.name;
1898 password = translatePassword(playername, narrow_to_wide(menudata.password));
1900 g_settings->set("name", playername);
1902 current_playername = playername;
1903 current_password = password;
1904 current_address = address;
1905 current_port = game_params.socket_port;
1907 // If using simple singleplayer mode, override
1908 if (simple_singleplayer_mode) {
1909 assert(skip_main_menu == false);
1910 current_playername = "singleplayer";
1911 current_password = "";
1912 current_address = "";
1913 current_port = myrand_range(49152, 65535);
1914 } else if (address != "") {
1915 ServerListSpec server;
1916 server["name"] = menudata.servername;
1917 server["address"] = menudata.address;
1918 server["port"] = menudata.port;
1919 server["description"] = menudata.serverdescription;
1920 ServerList::insert(server);
1923 infostream << "Selected world: " << worldspec.name
1924 << " [" << worldspec.path << "]" << std::endl;
1926 if (current_address == "") { // If local game
1927 if (worldspec.path == "") {
1928 *error_message = wgettext("No world selected and no address "
1929 "provided. Nothing to do.");
1930 errorstream << wide_to_narrow(*error_message) << std::endl;
1934 if (!fs::PathExists(worldspec.path)) {
1935 *error_message = wgettext("Provided world path doesn't exist: ")
1936 + narrow_to_wide(worldspec.path);
1937 errorstream << wide_to_narrow(*error_message) << std::endl;
1941 // Load gamespec for required game
1942 gamespec = findWorldSubgame(worldspec.path);
1943 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1944 *error_message = wgettext("Could not find or load game \"")
1945 + narrow_to_wide(worldspec.gameid) + L"\"";
1946 errorstream << wide_to_narrow(*error_message) << std::endl;
1950 if (porting::signal_handler_killstatus())
1953 if (game_params.game_spec.isValid() &&
1954 game_params.game_spec.id != worldspec.gameid) {
1955 errorstream << "WARNING: Overriding gamespec from \""
1956 << worldspec.gameid << "\" to \""
1957 << game_params.game_spec.id << "\"" << std::endl;
1958 gamespec = game_params.game_spec;
1961 if (!gamespec.isValid()) {
1962 *error_message = wgettext("Invalid gamespec.");
1963 *error_message += L" (world_gameid="
1964 + narrow_to_wide(worldspec.gameid) + L")";
1965 errorstream << wide_to_narrow(*error_message) << std::endl;
1973 void ClientLauncher::main_menu(MainMenuData *menudata)
1975 bool *kill = porting::signal_handler_killstatus();
1976 video::IVideoDriver *driver = device->getVideoDriver();
1978 infostream << "Waiting for other menus" << std::endl;
1979 while (device->run() && *kill == false) {
1982 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1985 // On some computers framerate doesn't seem to be automatically limited
1988 infostream << "Waited for other menus" << std::endl;
1990 // Cursor can be non-visible when coming from the game
1992 device->getCursorControl()->setVisible(true);
1995 /* show main menu */
1996 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
1998 smgr->clear(); /* leave scene manager in a clean state */
2001 bool ClientLauncher::create_engine_device(int log_level)
2003 static const irr::ELOG_LEVEL irr_log_level[5] = {
2008 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2015 // Resolution selection
2016 bool fullscreen = g_settings->getBool("fullscreen");
2017 u16 screenW = g_settings->getU16("screenW");
2018 u16 screenH = g_settings->getU16("screenH");
2021 bool vsync = g_settings->getBool("vsync");
2022 u16 bits = g_settings->getU16("fullscreen_bpp");
2023 u16 fsaa = g_settings->getU16("fsaa");
2026 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2027 std::string driverstring = g_settings->get("video_driver");
2028 std::vector<video::E_DRIVER_TYPE> drivers
2029 = porting::getSupportedVideoDrivers();
2031 for (i = 0; i != drivers.size(); i++) {
2032 if (!strcasecmp(driverstring.c_str(),
2033 porting::getVideoDriverName(drivers[i]))) {
2034 driverType = drivers[i];
2038 if (i == drivers.size()) {
2039 errorstream << "Invalid video_driver specified; "
2040 "defaulting to opengl" << std::endl;
2043 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2044 params.DriverType = driverType;
2045 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
2047 params.AntiAlias = fsaa;
2048 params.Fullscreen = fullscreen;
2049 params.Stencilbuffer = false;
2050 params.Vsync = vsync;
2051 params.EventReceiver = receiver;
2052 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2054 params.PrivateData = porting::app_global;
2055 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2056 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2059 device = createDeviceEx(params);
2062 // Map our log level to irrlicht engine one.
2063 ILogger* irr_logger = device->getLogger();
2064 irr_logger->setLogLevel(irr_log_level[log_level]);
2066 porting::initIrrlicht(device);
2069 return device != NULL;
2074 static bool print_video_modes()
2076 IrrlichtDevice *nulldevice;
2078 bool vsync = g_settings->getBool("vsync");
2079 u16 fsaa = g_settings->getU16("fsaa");
2080 MyEventReceiver* receiver = new MyEventReceiver();
2082 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2083 params.DriverType = video::EDT_NULL;
2084 params.WindowSize = core::dimension2d<u32>(640, 480);
2086 params.AntiAlias = fsaa;
2087 params.Fullscreen = false;
2088 params.Stencilbuffer = false;
2089 params.Vsync = vsync;
2090 params.EventReceiver = receiver;
2091 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2093 nulldevice = createDeviceEx(params);
2095 if (nulldevice == NULL) {
2100 dstream << _("Available video modes (WxHxD):") << std::endl;
2102 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2104 if (videomode_list != NULL) {
2105 s32 videomode_count = videomode_list->getVideoModeCount();
2106 core::dimension2d<u32> videomode_res;
2107 s32 videomode_depth;
2108 for (s32 i = 0; i < videomode_count; ++i) {
2109 videomode_res = videomode_list->getVideoModeResolution(i);
2110 videomode_depth = videomode_list->getVideoModeDepth(i);
2111 dstream << videomode_res.Width << "x" << videomode_res.Height
2112 << "x" << videomode_depth << std::endl;
2115 dstream << _("Active video mode (WxHxD):") << std::endl;
2116 videomode_res = videomode_list->getDesktopResolution();
2117 videomode_depth = videomode_list->getDesktopDepth();
2118 dstream << videomode_res.Width << "x" << videomode_res.Height
2119 << "x" << videomode_depth << std::endl;
2126 return videomode_list != NULL;
2131 /*****************************************************************************
2133 *****************************************************************************/
2135 static void speed_tests()
2137 // volatile to avoid some potential compiler optimisations
2138 volatile static s16 temp16;
2139 volatile static f32 tempf;
2140 static v3f tempv3f1;
2141 static v3f tempv3f2;
2142 static std::string tempstring;
2143 static std::string tempstring2;
2147 tempstring = std::string();
2148 tempstring2 = std::string();
2151 infostream << "The following test should take around 20ms." << std::endl;
2152 TimeTaker timer("Testing std::string speed");
2153 const u32 jj = 10000;
2154 for (u32 j = 0; j < jj; j++) {
2158 for (u32 i = 0; i < ii; i++) {
2159 tempstring2 += "asd";
2161 for (u32 i = 0; i < ii+1; i++) {
2162 tempstring += "asd";
2163 if (tempstring == tempstring2)
2169 infostream << "All of the following tests should take around 100ms each."
2173 TimeTaker timer("Testing floating-point conversion speed");
2175 for (u32 i = 0; i < 4000000; i++) {
2182 TimeTaker timer("Testing floating-point vector speed");
2184 tempv3f1 = v3f(1, 2, 3);
2185 tempv3f2 = v3f(4, 5, 6);
2186 for (u32 i = 0; i < 10000000; i++) {
2187 tempf += tempv3f1.dotProduct(tempv3f2);
2188 tempv3f2 += v3f(7, 8, 9);
2193 TimeTaker timer("Testing std::map speed");
2195 std::map<v2s16, f32> map1;
2198 for (s16 y = 0; y < ii; y++) {
2199 for (s16 x = 0; x < ii; x++) {
2200 map1[v2s16(x, y)] = tempf;
2204 for (s16 y = ii - 1; y >= 0; y--) {
2205 for (s16 x = 0; x < ii; x++) {
2206 tempf = map1[v2s16(x, y)];
2212 infostream << "Around 5000/ms should do well here." << std::endl;
2213 TimeTaker timer("Testing mutex speed");
2220 for (; i < n; i++) {
2226 while(timer.getTimerTime() < 10);
2228 u32 dtime = timer.stop();
2229 u32 per_ms = n / dtime;
2230 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;