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 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
784 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
786 log_register_thread("main");
789 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
791 || cmd_args.getFlag("help")
792 || cmd_args.exists("nonopt1")) {
793 print_help(allowed_options);
794 return cmd_args_ok ? 0 : 1;
797 if (cmd_args.getFlag("version")) {
802 setup_log_params(cmd_args);
804 porting::signal_handler_init();
805 porting::initializePaths();
807 if (!create_userdata_path()) {
808 errorstream << "Cannot create user data directory" << std::endl;
812 // Initialize debug stacks
814 DSTACK(__FUNCTION_NAME);
817 BEGIN_DEBUG_EXCEPTION_HANDLER
819 // List gameids if requested
820 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
825 // List worlds if requested
826 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
831 GameParams game_params;
832 if (!init_common(&game_params.log_level, cmd_args, argc, argv))
837 if ((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
838 || cmd_args.getFlag("enable-unittests") == true) {
844 game_params.is_dedicated_server = true;
846 game_params.is_dedicated_server = cmd_args.getFlag("server");
849 if (!game_configure(&game_params, cmd_args))
852 assert(game_params.world_path != "");
854 infostream << "Using commanded world path ["
855 << game_params.world_path << "]" << std::endl;
857 //Run dedicated server if asked to or no other option
858 g_settings->set("server_dedicated",
859 game_params.is_dedicated_server ? "true" : "false");
861 if (game_params.is_dedicated_server)
862 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
865 ClientLauncher launcher;
866 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
871 // Update configuration file
872 if (g_settings_path != "")
873 g_settings->updateConfigFile(g_settings_path.c_str());
875 print_modified_quicktune_values();
877 // Stop httpfetch thread (if started)
880 END_DEBUG_EXCEPTION_HANDLER(errorstream)
886 /*****************************************************************************
888 *****************************************************************************/
891 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
893 set_allowed_options(&allowed_options);
895 return cmd_args->parseCommandLine(argc, argv, allowed_options);
898 static void set_allowed_options(OptionList *allowed_options)
900 allowed_options->clear();
902 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
903 _("Show allowed options"))));
904 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
905 _("Show version information"))));
906 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
907 _("Load configuration from specified file"))));
908 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
909 _("Set network port (UDP)"))));
910 allowed_options->insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
911 _("Disable unit tests"))));
912 allowed_options->insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
913 _("Enable unit tests"))));
914 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
915 _("Same as --world (deprecated)"))));
916 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
917 _("Set world path (implies local game) ('list' lists all)"))));
918 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
919 _("Set world by name (implies local game)"))));
920 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
921 _("Print to console errors only"))));
922 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
923 _("Print more information to console"))));
924 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
925 _("Print even more information to console"))));
926 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
927 _("Print enormous amounts of information to log and console"))));
928 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
929 _("Set logfile path ('' = no logging)"))));
930 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
931 _("Set gameid (\"--gameid list\" prints available ones)"))));
932 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
933 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
935 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
936 _("Show available video modes"))));
937 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
938 _("Run speed tests"))));
939 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
940 _("Address to connect to. ('' = local game)"))));
941 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
942 _("Enable random user input, for testing"))));
943 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
944 _("Run dedicated server"))));
945 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
946 _("Set player name"))));
947 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
948 _("Set password"))));
949 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
950 _("Disable main menu"))));
955 static void print_help(const OptionList &allowed_options)
957 dstream << _("Allowed options:") << std::endl;
958 print_allowed_options(allowed_options);
961 static void print_allowed_options(const OptionList &allowed_options)
963 for (OptionList::const_iterator i = allowed_options.begin();
964 i != allowed_options.end(); ++i) {
965 std::ostringstream os1(std::ios::binary);
966 os1 << " --" << i->first;
967 if (i->second.type != VALUETYPE_FLAG)
968 os1 << _(" <value>");
970 dstream << padStringRight(os1.str(), 24);
972 if (i->second.help != NULL)
973 dstream << i->second.help;
975 dstream << std::endl;
979 static void print_version()
982 dstream << "minetestserver " << minetest_version_hash << std::endl;
984 dstream << "Minetest " << minetest_version_hash << std::endl;
985 dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
987 dstream << "Build info: " << minetest_build_info << std::endl;
990 static void list_game_ids()
992 std::set<std::string> gameids = getAvailableGameIds();
993 for (std::set<std::string>::const_iterator i = gameids.begin();
994 i != gameids.end(); i++)
995 dstream << (*i) <<std::endl;
998 static void list_worlds()
1000 dstream << _("Available worlds:") << std::endl;
1001 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1002 print_worldspecs(worldspecs, dstream);
1005 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
1008 for (size_t i = 0; i < worldspecs.size(); i++) {
1009 std::string name = worldspecs[i].name;
1010 std::string path = worldspecs[i].path;
1011 if (name.find(" ") != std::string::npos)
1012 name = std::string("'") + name + "'";
1013 path = std::string("'") + path + "'";
1014 name = padStringRight(name, 14);
1015 os << " " << name << " " << path << std::endl;
1019 static void print_modified_quicktune_values()
1021 bool header_printed = false;
1022 std::vector<std::string> names = getQuicktuneNames();
1024 for (u32 i = 0; i < names.size(); i++) {
1025 QuicktuneValue val = getQuicktuneValue(names[i]);
1028 if (!header_printed) {
1029 dstream << "Modified quicktune values:" << std::endl;
1030 header_printed = true;
1032 dstream << names[i] << " = " << val.getString() << std::endl;
1036 static void setup_log_params(const Settings &cmd_args)
1038 // Quiet mode, print errors only
1039 if (cmd_args.getFlag("quiet")) {
1040 log_remove_output(&main_stderr_log_out);
1041 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
1044 // If trace is enabled, enable logging of certain things
1045 if (cmd_args.getFlag("trace")) {
1046 dstream << _("Enabling trace level debug output") << std::endl;
1047 log_trace_level_enabled = true;
1048 dout_con_ptr = &verbosestream; // this is somewhat old crap
1049 socket_enable_debug_output = true; // socket doesn't use log.h
1052 // In certain cases, output info level on stderr
1053 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
1054 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
1055 log_add_output(&main_stderr_log_out, LMT_INFO);
1057 // In certain cases, output verbose level on stderr
1058 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
1059 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
1062 static bool create_userdata_path()
1067 porting::initAndroid();
1069 porting::setExternalStorageDir(porting::jnienv);
1070 if (!fs::PathExists(porting::path_user)) {
1071 success = fs::CreateDir(porting::path_user);
1075 porting::copyAssets();
1077 // Create user data directory
1078 success = fs::CreateDir(porting::path_user);
1081 infostream << "path_share = " << porting::path_share << std::endl;
1082 infostream << "path_user = " << porting::path_user << std::endl;
1087 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[])
1090 set_default_settings(g_settings);
1092 // Initialize sockets
1094 atexit(sockets_cleanup);
1096 if (!read_config_file(cmd_args))
1099 init_debug_streams(log_level, cmd_args);
1101 // Initialize random seed
1105 // Initialize HTTP fetcher
1106 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1109 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1110 g_settings->get("language"), argc, argv);
1112 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1113 g_settings->get("language"));
1119 static void startup_message()
1121 infostream << PROJECT_NAME << " " << _("with")
1122 << " SER_FMT_VER_HIGHEST_READ="
1123 << (int)SER_FMT_VER_HIGHEST_READ << ", "
1124 << minetest_build_info << std::endl;
1127 static bool read_config_file(const Settings &cmd_args)
1129 // Path of configuration file in use
1130 assert(g_settings_path == ""); // Sanity check
1132 if (cmd_args.exists("config")) {
1133 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1135 errorstream << "Could not read configuration from \""
1136 << cmd_args.get("config") << "\"" << std::endl;
1139 g_settings_path = cmd_args.get("config");
1141 std::vector<std::string> filenames;
1142 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
1143 // Legacy configuration file location
1144 filenames.push_back(porting::path_user +
1145 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1148 // Try also from a lower level (to aid having the same configuration
1149 // for many RUN_IN_PLACE installs)
1150 filenames.push_back(porting::path_user +
1151 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1154 for (size_t i = 0; i < filenames.size(); i++) {
1155 bool r = g_settings->readConfigFile(filenames[i].c_str());
1157 g_settings_path = filenames[i];
1162 // If no path found, use the first one (menu creates the file)
1163 if (g_settings_path == "")
1164 g_settings_path = filenames[0];
1170 static void init_debug_streams(int *log_level, const Settings &cmd_args)
1173 std::string logfile = DEBUGFILE;
1175 std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
1177 if (cmd_args.exists("logfile"))
1178 logfile = cmd_args.get("logfile");
1180 log_remove_output(&main_dstream_no_stderr_log_out);
1181 *log_level = g_settings->getS32("debug_log_level");
1183 if (*log_level == 0) //no logging
1185 if (*log_level < 0) {
1186 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
1188 } else if (*log_level > LMT_NUM_VALUES) {
1189 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
1190 << "; Using " << LMT_NUM_VALUES << std::endl;
1191 *log_level = LMT_NUM_VALUES;
1194 log_add_output_maxlev(&main_dstream_no_stderr_log_out,
1195 (LogMessageLevel)(*log_level - 1));
1197 debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
1199 infostream << "logfile = " << logfile << std::endl;
1201 atexit(debugstreams_deinit);
1204 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
1206 game_configure_port(game_params, cmd_args);
1208 if (!game_configure_world(game_params, cmd_args)) {
1209 errorstream << "No world path specified or found." << std::endl;
1213 game_configure_subgame(game_params, cmd_args);
1218 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
1220 if (cmd_args.exists("port"))
1221 game_params->socket_port = cmd_args.getU16("port");
1223 game_params->socket_port = g_settings->getU16("port");
1225 if (game_params->socket_port == 0)
1226 game_params->socket_port = DEFAULT_SERVER_PORT;
1229 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
1231 if (get_world_from_cmdline(game_params, cmd_args))
1233 if (get_world_from_config(game_params, cmd_args))
1236 return auto_select_world(game_params);
1239 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1241 std::string commanded_world = "";
1244 std::string commanded_worldname = "";
1245 if (cmd_args.exists("worldname"))
1246 commanded_worldname = cmd_args.get("worldname");
1248 // If a world name was specified, convert it to a path
1249 if (commanded_worldname != "") {
1250 // Get information about available worlds
1251 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1253 for (u32 i = 0; i < worldspecs.size(); i++) {
1254 std::string name = worldspecs[i].name;
1255 if (name == commanded_worldname) {
1256 dstream << _("Using world specified by --worldname on the "
1257 "command line") << std::endl;
1258 commanded_world = worldspecs[i].path;
1264 dstream << _("World") << " '" << commanded_worldname
1265 << _("' not available. Available worlds:") << std::endl;
1266 print_worldspecs(worldspecs, dstream);
1270 game_params->world_path = get_clean_world_path(commanded_world);
1271 return commanded_world != "";
1274 if (cmd_args.exists("world"))
1275 commanded_world = cmd_args.get("world");
1276 else if (cmd_args.exists("map-dir"))
1277 commanded_world = cmd_args.get("map-dir");
1278 else if (cmd_args.exists("nonopt0")) // First nameless argument
1279 commanded_world = cmd_args.get("nonopt0");
1281 game_params->world_path = get_clean_world_path(commanded_world);
1282 return commanded_world != "";
1285 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
1288 std::string commanded_world = "";
1290 if (g_settings->exists("map-dir"))
1291 commanded_world = g_settings->get("map-dir");
1293 game_params->world_path = get_clean_world_path(commanded_world);
1295 return commanded_world != "";
1298 static bool auto_select_world(GameParams *game_params)
1300 // No world was specified; try to select it automatically
1301 // Get information about available worlds
1303 verbosestream << _("Determining world path") << std::endl;
1305 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1306 std::string world_path;
1308 // If there is only a single world, use it
1309 if (worldspecs.size() == 1) {
1310 world_path = worldspecs[0].path;
1311 dstream <<_("Automatically selecting world at") << " ["
1312 << world_path << "]" << std::endl;
1313 // If there are multiple worlds, list them
1314 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
1315 dstream << _("Multiple worlds are available.") << std::endl;
1316 dstream << _("Please select one using --worldname <name>"
1317 " or --world <path>") << std::endl;
1318 print_worldspecs(worldspecs, dstream);
1320 // If there are no worlds, automatically create a new one
1322 // This is the ultimate default world path
1323 world_path = porting::path_user + DIR_DELIM + "worlds" +
1324 DIR_DELIM + "world";
1325 infostream << "Creating default world at ["
1326 << world_path << "]" << std::endl;
1329 assert(world_path != "");
1330 game_params->world_path = world_path;
1334 static std::string get_clean_world_path(const std::string &path)
1336 const std::string worldmt = "world.mt";
1337 std::string clean_path;
1339 if (path.size() > worldmt.size()
1340 && path.substr(path.size() - worldmt.size()) == worldmt) {
1341 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
1342 clean_path = path.substr(0, path.size() - worldmt.size());
1350 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
1354 success = get_game_from_cmdline(game_params, cmd_args);
1356 success = determine_subgame(game_params);
1361 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1363 SubgameSpec commanded_gamespec;
1365 if (cmd_args.exists("gameid")) {
1366 std::string gameid = cmd_args.get("gameid");
1367 commanded_gamespec = findSubgame(gameid);
1368 if (!commanded_gamespec.isValid()) {
1369 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
1372 dstream << _("Using game specified by --gameid on the command line")
1374 game_params->game_spec = commanded_gamespec;
1381 static bool determine_subgame(GameParams *game_params)
1383 SubgameSpec gamespec;
1385 assert(game_params->world_path != ""); // pre-condition
1387 verbosestream << _("Determining gameid/gamespec") << std::endl;
1388 // If world doesn't exist
1389 if (game_params->world_path != ""
1390 && !getWorldExists(game_params->world_path)) {
1391 // Try to take gamespec from command line
1392 if (game_params->game_spec.isValid()) {
1393 gamespec = game_params->game_spec;
1394 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
1395 } else { // Otherwise we will be using "minetest"
1396 gamespec = findSubgame(g_settings->get("default_game"));
1397 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
1398 if (!gamespec.isValid()) {
1399 errorstream << "Subgame specified in default_game ["
1400 << g_settings->get("default_game")
1401 << "] is invalid." << std::endl;
1405 } else { // World exists
1406 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1407 // If commanded to use a gameid, do so
1408 if (game_params->game_spec.isValid()) {
1409 gamespec = game_params->game_spec;
1410 if (game_params->game_spec.id != world_gameid) {
1411 errorstream << "WARNING: Using commanded gameid ["
1412 << gamespec.id << "]" << " instead of world gameid ["
1413 << world_gameid << "]" << std::endl;
1416 // If world contains an embedded game, use it;
1417 // Otherwise find world from local system.
1418 gamespec = findWorldSubgame(game_params->world_path);
1419 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1423 if (!gamespec.isValid()) {
1424 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1429 game_params->game_spec = gamespec;
1434 /*****************************************************************************
1436 *****************************************************************************/
1437 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1439 DSTACK("Dedicated server branch");
1441 verbosestream << _("Using world path") << " ["
1442 << game_params.world_path << "]" << std::endl;
1443 verbosestream << _("Using gameid") << " ["
1444 << game_params.game_spec.id << "]" << std::endl;
1447 std::string bind_str = g_settings->get("bind_address");
1448 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1450 if (g_settings->getBool("ipv6_server")) {
1451 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1454 bind_addr.Resolve(bind_str.c_str());
1455 } catch (ResolveError &e) {
1456 infostream << "Resolving bind address \"" << bind_str
1457 << "\" failed: " << e.what()
1458 << " -- Listening on all addresses." << std::endl;
1460 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1461 errorstream << "Unable to listen on "
1462 << bind_addr.serializeString()
1463 << L" because IPv6 is disabled" << std::endl;
1468 Server server(game_params.world_path,
1469 game_params.game_spec, false, bind_addr.isIPv6());
1471 // Database migration
1472 if (cmd_args.exists("migrate"))
1473 return migrate_database(game_params, cmd_args, &server);
1475 server.start(bind_addr);
1478 bool &kill = *porting::signal_handler_killstatus();
1479 dedicated_server_loop(server, kill);
1484 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1488 bool success = world_mt.readConfigFile((game_params.world_path
1489 + DIR_DELIM + "world.mt").c_str());
1491 errorstream << "Cannot read world.mt" << std::endl;
1495 if (!world_mt.exists("backend")) {
1496 errorstream << "Please specify your current backend in world.mt file:"
1497 << std::endl << " backend = {sqlite3|leveldb|redis|dummy}"
1502 std::string backend = world_mt.get("backend");
1504 std::string migrate_to = cmd_args.get("migrate");
1506 if (backend == migrate_to) {
1507 errorstream << "Cannot migrate: new backend is same as the old one"
1512 if (migrate_to == "sqlite3")
1513 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1514 game_params.world_path);
1516 else if (migrate_to == "leveldb")
1517 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1518 game_params.world_path);
1521 else if (migrate_to == "redis")
1522 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1523 game_params.world_path);
1526 errorstream << "Migration to " << migrate_to << " is not supported"
1531 std::list<v3s16> blocks;
1532 ServerMap &old_map = ((ServerMap&)server->getMap());
1533 old_map.listAllLoadableBlocks(blocks);
1535 new_db->beginSave();
1536 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1537 MapBlock *block = old_map.loadBlock(*i);
1539 errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1541 old_map.saveBlock(block, new_db);
1542 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1543 sector->deleteBlock(block);
1546 if (count % 500 == 0)
1547 actionstream << "Migrated " << count << " blocks "
1548 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1553 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1554 world_mt.set("backend", migrate_to);
1555 if (!world_mt.updateConfigFile(
1556 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1557 errorstream << "Failed to update world.mt!" << std::endl;
1559 actionstream << "world.mt updated" << std::endl;
1565 /*****************************************************************************
1567 *****************************************************************************/
1570 ClientLauncher::~ClientLauncher()
1579 delete g_fontengine;
1585 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1587 init_args(game_params, cmd_args);
1589 // List video modes if requested
1590 if (list_video_modes)
1591 return print_video_modes();
1593 if (!init_engine(game_params.log_level)) {
1594 errorstream << "Could not initialize game engine." << std::endl;
1598 // Speed tests (done after irrlicht is loaded to get timer)
1599 if (cmd_args.getFlag("speedtests")) {
1600 dstream << "Running speed tests" << std::endl;
1605 if (device->getVideoDriver() == NULL) {
1606 errorstream << "Could not initialize video driver." << std::endl;
1611 This changes the minimum allowed number of vertices in a VBO.
1614 //driver->setMinHardwareBufferVertexCount(50);
1616 // Create time getter
1617 g_timegetter = new IrrlichtTimeGetter(device);
1619 // Create game callback for menus
1620 g_gamecallback = new MainGameCallback(device);
1622 device->setResizable(true);
1625 input = new RandomInputHandler();
1627 input = new RealInputHandler(device, receiver);
1629 smgr = device->getSceneManager();
1631 guienv = device->getGUIEnvironment();
1632 skin = guienv->getSkin();
1633 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1634 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1635 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1636 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1637 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1639 g_fontengine = new FontEngine(g_settings, guienv);
1640 assert(g_fontengine != NULL);
1642 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1643 // Irrlicht 1.8 input colours
1644 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1645 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1648 // Create the menu clouds
1649 if (!g_menucloudsmgr)
1650 g_menucloudsmgr = smgr->createNewSceneManager();
1652 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1653 g_menucloudsmgr, -1, rand(), 100);
1654 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1655 scene::ICameraSceneNode* camera;
1656 camera = g_menucloudsmgr->addCameraSceneNode(0,
1657 v3f(0, 0, 0), v3f(0, 60, 100));
1658 camera->setFarValue(10000);
1664 ChatBackend chat_backend;
1666 // If an error occurs, this is set to something by menu().
1667 // It is then displayed before the menu shows on the next call to menu()
1668 std::wstring error_message = L"";
1670 bool first_loop = true;
1676 bool *kill = porting::signal_handler_killstatus();
1678 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1680 // Set the window caption
1681 wchar_t *text = wgettext("Main Menu");
1682 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1685 try { // This is used for catching disconnects
1690 We need some kind of a root node to be able to add
1691 custom gui elements directly on the screen.
1692 Otherwise they won't be automatically drawn.
1694 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1696 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1698 // If skip_main_menu, we only want to startup once
1699 if (skip_main_menu && !first_loop)
1704 if (!game_has_run) {
1711 // Break out of menu-game loop to shut down cleanly
1712 if (!device->run() || *kill) {
1713 if (g_settings_path != "")
1714 g_settings->updateConfigFile(g_settings_path.c_str());
1718 if (current_playername.length() > PLAYERNAME_SIZE-1) {
1719 error_message = wgettext("Player name too long.");
1720 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1721 g_settings->set("name", playername);
1725 device->getVideoDriver()->setTextureCreationFlag(
1726 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1728 #ifdef HAVE_TOUCHSCREENGUI
1729 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1730 g_touchscreengui = receiver->m_touchscreengui;
1745 simple_singleplayer_mode
1749 #ifdef HAVE_TOUCHSCREENGUI
1750 delete g_touchscreengui;
1751 g_touchscreengui = NULL;
1752 receiver->m_touchscreengui = NULL;
1756 catch (con::PeerNotFoundException &e) {
1757 error_message = wgettext("Connection error (timed out?)");
1758 errorstream << wide_to_narrow(error_message) << std::endl;
1762 catch (std::exception &e) {
1763 std::string narrow_message = "Some exception: \"";
1764 narrow_message += e.what();
1765 narrow_message += "\"";
1766 errorstream << narrow_message << std::endl;
1767 error_message = narrow_to_wide(narrow_message);
1771 // If no main menu, show error and exit
1772 if (skip_main_menu) {
1773 if (error_message != L"") {
1774 verbosestream << "error_message = "
1775 << wide_to_narrow(error_message) << std::endl;
1782 g_menuclouds->drop();
1783 g_menucloudsmgr->drop();
1788 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1791 skip_main_menu = cmd_args.getFlag("go");
1793 // FIXME: This is confusing (but correct)
1795 /* If world_path is set then override it unless skipping the main menu using
1796 * the --go command line param. Else, give preference to the address
1797 * supplied on the command line
1799 address = g_settings->get("address");
1800 if (game_params.world_path != "" && !skip_main_menu)
1802 else if (cmd_args.exists("address"))
1803 address = cmd_args.get("address");
1805 playername = g_settings->get("name");
1806 if (cmd_args.exists("name"))
1807 playername = cmd_args.get("name");
1809 list_video_modes = cmd_args.getFlag("videomodes");
1811 use_freetype = g_settings->getBool("freetype");
1813 random_input = g_settings->getBool("random_input")
1814 || cmd_args.getFlag("random-input");
1817 bool ClientLauncher::init_engine(int log_level)
1819 receiver = new MyEventReceiver();
1820 create_engine_device(log_level);
1821 return device != NULL;
1824 bool ClientLauncher::launch_game(std::wstring *error_message,
1825 GameParams &game_params, const Settings &cmd_args)
1827 // Initialize menu data
1828 MainMenuData menudata;
1829 menudata.address = address;
1830 menudata.name = playername;
1831 menudata.port = itos(game_params.socket_port);
1832 menudata.errormessage = wide_to_narrow(*error_message);
1834 *error_message = L"";
1836 if (cmd_args.exists("password"))
1837 menudata.password = cmd_args.get("password");
1839 menudata.enable_public = g_settings->getBool("server_announce");
1841 // If a world was commanded, append and select it
1842 if (game_params.world_path != "") {
1843 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1844 worldspec.name = _("[--world parameter]");
1846 if (worldspec.gameid == "") { // Create new
1847 worldspec.gameid = g_settings->get("default_game");
1848 worldspec.name += " [new]";
1850 worldspec.path = game_params.world_path;
1853 /* Show the GUI menu
1855 if (!skip_main_menu) {
1856 main_menu(&menudata);
1858 address = menudata.address;
1859 int newport = stoi(menudata.port);
1861 game_params.socket_port = newport;
1863 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1865 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1866 worldspecs = getAvailableWorlds();
1868 if (menudata.selected_world >= 0
1869 && menudata.selected_world < (int)worldspecs.size()) {
1870 g_settings->set("selected_world_path",
1871 worldspecs[menudata.selected_world].path);
1872 worldspec = worldspecs[menudata.selected_world];
1876 if (menudata.errormessage != "") {
1877 /* The calling function will pass this back into this function upon the
1878 * next iteration (if any) causing it to be displayed by the GUI
1880 *error_message = narrow_to_wide(menudata.errormessage);
1884 if (menudata.name == "")
1885 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1887 playername = menudata.name;
1889 password = translatePassword(playername, narrow_to_wide(menudata.password));
1891 g_settings->set("name", playername);
1893 current_playername = playername;
1894 current_password = password;
1895 current_address = address;
1896 current_port = game_params.socket_port;
1898 // If using simple singleplayer mode, override
1899 if (simple_singleplayer_mode) {
1900 assert(skip_main_menu == false);
1901 current_playername = "singleplayer";
1902 current_password = "";
1903 current_address = "";
1904 current_port = myrand_range(49152, 65535);
1905 } else if (address != "") {
1906 ServerListSpec server;
1907 server["name"] = menudata.servername;
1908 server["address"] = menudata.address;
1909 server["port"] = menudata.port;
1910 server["description"] = menudata.serverdescription;
1911 ServerList::insert(server);
1914 infostream << "Selected world: " << worldspec.name
1915 << " [" << worldspec.path << "]" << std::endl;
1917 if (current_address == "") { // If local game
1918 if (worldspec.path == "") {
1919 *error_message = wgettext("No world selected and no address "
1920 "provided. Nothing to do.");
1921 errorstream << wide_to_narrow(*error_message) << std::endl;
1925 if (!fs::PathExists(worldspec.path)) {
1926 *error_message = wgettext("Provided world path doesn't exist: ")
1927 + narrow_to_wide(worldspec.path);
1928 errorstream << wide_to_narrow(*error_message) << std::endl;
1932 // Load gamespec for required game
1933 gamespec = findWorldSubgame(worldspec.path);
1934 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1935 *error_message = wgettext("Could not find or load game \"")
1936 + narrow_to_wide(worldspec.gameid) + L"\"";
1937 errorstream << wide_to_narrow(*error_message) << std::endl;
1940 if (game_params.game_spec.isValid() &&
1941 game_params.game_spec.id != worldspec.gameid) {
1942 errorstream << "WARNING: Overriding gamespec from \""
1943 << worldspec.gameid << "\" to \""
1944 << game_params.game_spec.id << "\"" << std::endl;
1945 gamespec = game_params.game_spec;
1948 if (!gamespec.isValid()) {
1949 *error_message = wgettext("Invalid gamespec.");
1950 *error_message += L" (world_gameid="
1951 + narrow_to_wide(worldspec.gameid) + L")";
1952 errorstream << wide_to_narrow(*error_message) << std::endl;
1960 void ClientLauncher::main_menu(MainMenuData *menudata)
1962 bool *kill = porting::signal_handler_killstatus();
1963 video::IVideoDriver *driver = device->getVideoDriver();
1965 infostream << "Waiting for other menus" << std::endl;
1966 while (device->run() && *kill == false) {
1969 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1972 // On some computers framerate doesn't seem to be automatically limited
1975 infostream << "Waited for other menus" << std::endl;
1977 // Cursor can be non-visible when coming from the game
1979 device->getCursorControl()->setVisible(true);
1982 /* show main menu */
1983 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
1985 smgr->clear(); /* leave scene manager in a clean state */
1988 bool ClientLauncher::create_engine_device(int log_level)
1990 static const char *driverids[] = {
1997 #ifdef _IRR_COMPILE_WITH_OGLES1_
2000 #ifdef _IRR_COMPILE_WITH_OGLES2_
2006 static const irr::ELOG_LEVEL irr_log_level[5] = {
2011 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2018 // Resolution selection
2019 bool fullscreen = g_settings->getBool("fullscreen");
2020 u16 screenW = g_settings->getU16("screenW");
2021 u16 screenH = g_settings->getU16("screenH");
2024 bool vsync = g_settings->getBool("vsync");
2025 u16 bits = g_settings->getU16("fullscreen_bpp");
2026 u16 fsaa = g_settings->getU16("fsaa");
2029 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2031 std::string driverstring = g_settings->get("video_driver");
2032 for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2033 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2034 driverType = (video::E_DRIVER_TYPE) i;
2038 if (strcasecmp("invalid", driverids[i]) == 0) {
2039 errorstream << "WARNING: Invalid video_driver specified;"
2040 << " defaulting to opengl" << std::endl;
2045 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2046 params.DriverType = driverType;
2047 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
2049 params.AntiAlias = fsaa;
2050 params.Fullscreen = fullscreen;
2051 params.Stencilbuffer = false;
2052 params.Vsync = vsync;
2053 params.EventReceiver = receiver;
2054 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2056 params.PrivateData = porting::app_global;
2057 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2058 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2061 device = createDeviceEx(params);
2064 // Map our log level to irrlicht engine one.
2065 ILogger* irr_logger = device->getLogger();
2066 irr_logger->setLogLevel(irr_log_level[log_level]);
2068 porting::initIrrlicht(device);
2071 return device != NULL;
2076 static bool print_video_modes()
2078 IrrlichtDevice *nulldevice;
2080 bool vsync = g_settings->getBool("vsync");
2081 u16 fsaa = g_settings->getU16("fsaa");
2082 MyEventReceiver* receiver = new MyEventReceiver();
2084 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2085 params.DriverType = video::EDT_NULL;
2086 params.WindowSize = core::dimension2d<u32>(640, 480);
2088 params.AntiAlias = fsaa;
2089 params.Fullscreen = false;
2090 params.Stencilbuffer = false;
2091 params.Vsync = vsync;
2092 params.EventReceiver = receiver;
2093 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2095 nulldevice = createDeviceEx(params);
2097 if (nulldevice == NULL) {
2102 dstream << _("Available video modes (WxHxD):") << std::endl;
2104 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2106 if (videomode_list != NULL) {
2107 s32 videomode_count = videomode_list->getVideoModeCount();
2108 core::dimension2d<u32> videomode_res;
2109 s32 videomode_depth;
2110 for (s32 i = 0; i < videomode_count; ++i) {
2111 videomode_res = videomode_list->getVideoModeResolution(i);
2112 videomode_depth = videomode_list->getVideoModeDepth(i);
2113 dstream << videomode_res.Width << "x" << videomode_res.Height
2114 << "x" << videomode_depth << std::endl;
2117 dstream << _("Active video mode (WxHxD):") << std::endl;
2118 videomode_res = videomode_list->getDesktopResolution();
2119 videomode_depth = videomode_list->getDesktopDepth();
2120 dstream << videomode_res.Width << "x" << videomode_res.Height
2121 << "x" << videomode_depth << std::endl;
2128 return videomode_list != NULL;
2133 /*****************************************************************************
2135 *****************************************************************************/
2137 static void speed_tests()
2139 // volatile to avoid some potential compiler optimisations
2140 volatile static s16 temp16;
2141 volatile static f32 tempf;
2142 static v3f tempv3f1;
2143 static v3f tempv3f2;
2144 static std::string tempstring;
2145 static std::string tempstring2;
2149 tempstring = std::string();
2150 tempstring2 = std::string();
2153 infostream << "The following test should take around 20ms." << std::endl;
2154 TimeTaker timer("Testing std::string speed");
2155 const u32 jj = 10000;
2156 for (u32 j = 0; j < jj; j++) {
2160 for (u32 i = 0; i < ii; i++) {
2161 tempstring2 += "asd";
2163 for (u32 i = 0; i < ii+1; i++) {
2164 tempstring += "asd";
2165 if (tempstring == tempstring2)
2171 infostream << "All of the following tests should take around 100ms each."
2175 TimeTaker timer("Testing floating-point conversion speed");
2177 for (u32 i = 0; i < 4000000; i++) {
2184 TimeTaker timer("Testing floating-point vector speed");
2186 tempv3f1 = v3f(1, 2, 3);
2187 tempv3f2 = v3f(4, 5, 6);
2188 for (u32 i = 0; i < 10000000; i++) {
2189 tempf += tempv3f1.dotProduct(tempv3f2);
2190 tempv3f2 += v3f(7, 8, 9);
2195 TimeTaker timer("Testing std::map speed");
2197 std::map<v2s16, f32> map1;
2200 for (s16 y = 0; y < ii; y++) {
2201 for (s16 x = 0; x < ii; x++) {
2202 map1[v2s16(x, y)] = tempf;
2206 for (s16 y = ii - 1; y >= 0; y--) {
2207 for (s16 x = 0; x < ii; x++) {
2208 tempf = map1[v2s16(x, y)];
2214 infostream << "Around 5000/ms should do well here." << std::endl;
2215 TimeTaker timer("Testing mutex speed");
2222 for (; i < n; i++) {
2228 while(timer.getTimerTime() < 10);
2230 u32 dtime = timer.stop();
2231 u32 per_ms = n / dtime;
2232 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;