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"
73 #include "xCGUITTFont.h"
75 #include "util/string.h"
77 #include "quicktune.h"
78 #include "serverlist.h"
79 #include "httpfetch.h"
80 #include "guiEngine.h"
81 #include "mapsector.h"
84 #include "database-sqlite3.h"
86 #include "database-leveldb.h"
90 #include "database-redis.h"
93 #ifdef HAVE_TOUCHSCREENGUI
94 #include "touchscreengui.h"
99 These are loaded from the config file.
101 static Settings main_settings;
102 Settings *g_settings = &main_settings;
103 std::string g_settings_path;
106 Profiler main_profiler;
107 Profiler *g_profiler = &main_profiler;
109 // Menu clouds are created later
110 Clouds *g_menuclouds = 0;
111 irr::scene::ISceneManager *g_menucloudsmgr = 0;
118 std::ostream *dout_con_ptr = &dummyout;
119 std::ostream *derr_con_ptr = &verbosestream;
122 std::ostream *dout_server_ptr = &infostream;
123 std::ostream *derr_server_ptr = &errorstream;
126 std::ostream *dout_client_ptr = &infostream;
127 std::ostream *derr_client_ptr = &errorstream;
129 #define DEBUGFILE "debug.txt"
130 #define DEFAULT_SERVER_PORT 30000
132 typedef std::map<std::string, ValueSpec> OptionList;
136 std::string world_path;
137 SubgameSpec game_spec;
138 bool is_dedicated_server;
142 /**********************************************************************
144 **********************************************************************/
146 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
147 static void set_allowed_options(OptionList *allowed_options);
149 static void print_help(const OptionList &allowed_options);
150 static void print_allowed_options(const OptionList &allowed_options);
151 static void print_version();
152 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
154 static void print_modified_quicktune_values();
156 static void list_game_ids();
157 static void list_worlds();
158 static void setup_log_params(const Settings &cmd_args);
159 static bool create_userdata_path();
160 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
161 static void startup_message();
162 static bool read_config_file(const Settings &cmd_args);
163 static void init_debug_streams(int *log_level, const Settings &cmd_args);
165 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
166 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
168 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
169 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
170 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
171 static bool auto_select_world(GameParams *game_params);
172 static std::string get_clean_world_path(const std::string &path);
174 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
175 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
176 static bool determine_subgame(GameParams *game_params);
178 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
179 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
183 static bool print_video_modes();
184 static void speed_tests();
187 /**********************************************************************/
194 /* mainmenumanager.h */
196 gui::IGUIEnvironment* guienv = NULL;
197 gui::IGUIStaticText *guiroot = NULL;
198 MainMenuManager g_menumgr;
202 return (g_menumgr.menuCount() == 0);
205 // Passed to menus to allow disconnecting and exiting
206 MainGameCallback *g_gamecallback = NULL;
210 gettime.h implementation
217 /* Use imprecise system calls directly (from porting.h) */
218 return porting::getTime(PRECISION_MILLI);
221 u32 getTime(TimePrecision prec)
223 return porting::getTime(prec);
228 // A small helper class
232 virtual u32 getTime(TimePrecision prec) = 0;
235 // A precise irrlicht one
236 class IrrlichtTimeGetter: public TimeGetter
239 IrrlichtTimeGetter(IrrlichtDevice *device):
242 u32 getTime(TimePrecision prec)
244 if (prec == PRECISION_MILLI) {
245 if (m_device == NULL)
247 return m_device->getTimer()->getRealTime();
249 return porting::getTime(prec);
253 IrrlichtDevice *m_device;
255 // Not so precise one which works without irrlicht
256 class SimpleTimeGetter: public TimeGetter
259 u32 getTime(TimePrecision prec)
261 return porting::getTime(prec);
265 // A pointer to a global instance of the time getter
267 TimeGetter *g_timegetter = NULL;
271 if (g_timegetter == NULL)
273 return g_timegetter->getTime(PRECISION_MILLI);
276 u32 getTime(TimePrecision prec) {
277 if (g_timegetter == NULL)
279 return g_timegetter->getTime(prec);
283 class StderrLogOutput: public ILogOutput
286 /* line: Full line with timestamp, level and thread */
287 void printLog(const std::string &line)
289 std::cerr << line << std::endl;
291 } main_stderr_log_out;
293 class DstreamNoStderrLogOutput: public ILogOutput
296 /* line: Full line with timestamp, level and thread */
297 void printLog(const std::string &line)
299 dstream_no_stderr << line << std::endl;
301 } main_dstream_no_stderr_log_out;
306 Event handler for Irrlicht
308 NOTE: Everything possible should be moved out from here,
309 probably to InputHandler and the_game
312 class MyEventReceiver : public IEventReceiver
315 // This is the one method that we have to implement
316 virtual bool OnEvent(const SEvent& event)
319 React to nothing here if a menu is active
321 if (noMenuActive() == false) {
322 #ifdef HAVE_TOUCHSCREENGUI
323 if (m_touchscreengui != 0) {
324 m_touchscreengui->Toggle(false);
327 return g_menumgr.preprocessEvent(event);
330 // Remember whether each key is down or up
331 if (event.EventType == irr::EET_KEY_INPUT_EVENT) {
332 if (event.KeyInput.PressedDown) {
333 keyIsDown.set(event.KeyInput);
334 keyWasDown.set(event.KeyInput);
336 keyIsDown.unset(event.KeyInput);
340 #ifdef HAVE_TOUCHSCREENGUI
341 // case of touchscreengui we have to handle different events
342 if ((m_touchscreengui != 0) &&
343 (event.EventType == irr::EET_TOUCH_INPUT_EVENT)) {
344 m_touchscreengui->translateEvent(event);
348 // handle mouse events
349 if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) {
350 if (noMenuActive() == false) {
352 middle_active = false;
353 right_active = false;
355 left_active = event.MouseInput.isLeftPressed();
356 middle_active = event.MouseInput.isMiddlePressed();
357 right_active = event.MouseInput.isRightPressed();
359 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
362 if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN) {
365 if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
368 if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP) {
369 rightreleased = true;
371 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
372 mouse_wheel += event.MouseInput.Wheel;
376 if (event.EventType == irr::EET_LOG_TEXT_EVENT) {
377 dstream << std::string("Irrlicht log: ") + std::string(event.LogEvent.Text)
381 /* always return false in order to continue processing events */
385 bool IsKeyDown(const KeyPress &keyCode) const
387 return keyIsDown[keyCode];
390 // Checks whether a key was down and resets the state
391 bool WasKeyDown(const KeyPress &keyCode)
393 bool b = keyWasDown[keyCode];
395 keyWasDown.unset(keyCode);
412 rightclicked = false;
413 leftreleased = false;
414 rightreleased = false;
417 middle_active = false;
418 right_active = false;
426 #ifdef HAVE_TOUCHSCREENGUI
427 m_touchscreengui = NULL;
442 #ifdef HAVE_TOUCHSCREENGUI
443 TouchScreenGUI* m_touchscreengui;
447 // The current state of keys
449 // Whether a key has been pressed or not
454 Separated input handler
457 class RealInputHandler : public InputHandler
460 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
462 m_receiver(receiver),
466 virtual bool isKeyDown(const KeyPress &keyCode)
468 return m_receiver->IsKeyDown(keyCode);
470 virtual bool wasKeyDown(const KeyPress &keyCode)
472 return m_receiver->WasKeyDown(keyCode);
474 virtual v2s32 getMousePos()
476 if (m_device->getCursorControl()) {
477 return m_device->getCursorControl()->getPosition();
483 virtual void setMousePos(s32 x, s32 y)
485 if (m_device->getCursorControl()) {
486 m_device->getCursorControl()->setPosition(x, y);
489 m_mousepos = v2s32(x,y);
493 virtual bool getLeftState()
495 return m_receiver->left_active;
497 virtual bool getRightState()
499 return m_receiver->right_active;
502 virtual bool getLeftClicked()
504 return m_receiver->leftclicked;
506 virtual bool getRightClicked()
508 return m_receiver->rightclicked;
510 virtual void resetLeftClicked()
512 m_receiver->leftclicked = false;
514 virtual void resetRightClicked()
516 m_receiver->rightclicked = false;
519 virtual bool getLeftReleased()
521 return m_receiver->leftreleased;
523 virtual bool getRightReleased()
525 return m_receiver->rightreleased;
527 virtual void resetLeftReleased()
529 m_receiver->leftreleased = false;
531 virtual void resetRightReleased()
533 m_receiver->rightreleased = false;
536 virtual s32 getMouseWheel()
538 return m_receiver->getMouseWheel();
543 m_receiver->clearInput();
546 IrrlichtDevice *m_device;
547 MyEventReceiver *m_receiver;
551 class RandomInputHandler : public InputHandler
559 rightclicked = false;
560 leftreleased = false;
561 rightreleased = false;
564 virtual bool isKeyDown(const KeyPress &keyCode)
566 return keydown[keyCode];
568 virtual bool wasKeyDown(const KeyPress &keyCode)
572 virtual v2s32 getMousePos()
576 virtual void setMousePos(s32 x, s32 y)
578 mousepos = v2s32(x, y);
581 virtual bool getLeftState()
585 virtual bool getRightState()
590 virtual bool getLeftClicked()
594 virtual bool getRightClicked()
598 virtual void resetLeftClicked()
602 virtual void resetRightClicked()
604 rightclicked = false;
607 virtual bool getLeftReleased()
611 virtual bool getRightReleased()
613 return rightreleased;
615 virtual void resetLeftReleased()
617 leftreleased = false;
619 virtual void resetRightReleased()
621 rightreleased = false;
624 virtual s32 getMouseWheel()
629 virtual void step(float dtime)
632 static float counter1 = 0;
634 if (counter1 < 0.0) {
635 counter1 = 0.1 * Rand(1, 40);
636 keydown.toggle(getKeySetting("keymap_jump"));
640 static float counter1 = 0;
642 if (counter1 < 0.0) {
643 counter1 = 0.1 * Rand(1, 40);
644 keydown.toggle(getKeySetting("keymap_special1"));
648 static float counter1 = 0;
650 if (counter1 < 0.0) {
651 counter1 = 0.1 * Rand(1, 40);
652 keydown.toggle(getKeySetting("keymap_forward"));
656 static float counter1 = 0;
658 if (counter1 < 0.0) {
659 counter1 = 0.1 * Rand(1, 40);
660 keydown.toggle(getKeySetting("keymap_left"));
664 static float counter1 = 0;
666 if (counter1 < 0.0) {
667 counter1 = 0.1 * Rand(1, 20);
668 mousespeed = v2s32(Rand(-20, 20), Rand(-15, 20));
672 static float counter1 = 0;
674 if (counter1 < 0.0) {
675 counter1 = 0.1 * Rand(1, 30);
676 leftdown = !leftdown;
684 static float counter1 = 0;
686 if (counter1 < 0.0) {
687 counter1 = 0.1 * Rand(1, 15);
688 rightdown = !rightdown;
692 rightreleased = true;
695 mousepos += mousespeed;
698 s32 Rand(s32 min, s32 max)
700 return (myrand()%(max-min+1))+min;
719 list_video_modes(false),
720 skip_main_menu(false),
731 simple_singleplayer_mode(false),
732 current_playername("inv£lid"),
733 current_password(""),
734 current_address("does-not-exist"),
740 bool run(GameParams &game_params, const Settings &cmd_args);
743 void init_args(GameParams &game_params, const Settings &cmd_args);
744 bool init_engine(int log_level);
746 bool launch_game(std::wstring *error_message, GameParams &game_params,
747 const Settings &cmd_args);
749 void main_menu(MainMenuData *menudata);
750 bool create_engine_device(int log_level);
752 bool list_video_modes;
757 std::string playername;
758 std::string password;
759 IrrlichtDevice *device;
761 MyEventReceiver *receiver;
764 scene::ISceneManager *smgr;
765 SubgameSpec gamespec;
767 bool simple_singleplayer_mode;
769 // These are set up based on the menu and other things
770 // TODO: Are these required since there's already playername, password, etc
771 std::string current_playername;
772 std::string current_password;
773 std::string current_address;
779 static OptionList allowed_options;
781 int main(int argc, char *argv[])
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;
1401 } else { // World exists
1402 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1403 // If commanded to use a gameid, do so
1404 if (game_params->game_spec.isValid()) {
1405 gamespec = game_params->game_spec;
1406 if (game_params->game_spec.id != world_gameid) {
1407 errorstream << "WARNING: Using commanded gameid ["
1408 << gamespec.id << "]" << " instead of world gameid ["
1409 << world_gameid << "]" << std::endl;
1412 // If world contains an embedded game, use it;
1413 // Otherwise find world from local system.
1414 gamespec = findWorldSubgame(game_params->world_path);
1415 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1419 if (!gamespec.isValid()) {
1420 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1425 game_params->game_spec = gamespec;
1430 /*****************************************************************************
1432 *****************************************************************************/
1433 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1435 DSTACK("Dedicated server branch");
1437 verbosestream << _("Using world path") << " ["
1438 << game_params.world_path << "]" << std::endl;
1439 verbosestream << _("Using gameid") << " ["
1440 << game_params.game_spec.id << "]" << std::endl;
1443 std::string bind_str = g_settings->get("bind_address");
1444 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1446 if (g_settings->getBool("ipv6_server")) {
1447 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1450 bind_addr.Resolve(bind_str.c_str());
1451 } catch (ResolveError &e) {
1452 infostream << "Resolving bind address \"" << bind_str
1453 << "\" failed: " << e.what()
1454 << " -- Listening on all addresses." << std::endl;
1456 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1457 errorstream << "Unable to listen on "
1458 << bind_addr.serializeString()
1459 << L" because IPv6 is disabled" << std::endl;
1464 Server server(game_params.world_path,
1465 game_params.game_spec, false, bind_addr.isIPv6());
1467 // Database migration
1468 if (cmd_args.exists("migrate"))
1469 return migrate_database(game_params, cmd_args, &server);
1471 server.start(bind_addr);
1474 bool &kill = *porting::signal_handler_killstatus();
1475 dedicated_server_loop(server, kill);
1480 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1484 bool success = world_mt.readConfigFile((game_params.world_path
1485 + DIR_DELIM + "world.mt").c_str());
1487 errorstream << "Cannot read world.mt" << std::endl;
1491 if (!world_mt.exists("backend")) {
1492 errorstream << "Please specify your current backend in world.mt file:"
1493 << std::endl << " backend = {sqlite3|leveldb|redis|dummy}"
1498 std::string backend = world_mt.get("backend");
1500 std::string migrate_to = cmd_args.get("migrate");
1502 if (backend == migrate_to) {
1503 errorstream << "Cannot migrate: new backend is same as the old one"
1508 if (migrate_to == "sqlite3")
1509 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1510 game_params.world_path);
1512 else if (migrate_to == "leveldb")
1513 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1514 game_params.world_path);
1517 else if (migrate_to == "redis")
1518 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1519 game_params.world_path);
1522 errorstream << "Migration to " << migrate_to << " is not supported"
1527 std::list<v3s16> blocks;
1528 ServerMap &old_map = ((ServerMap&)server->getMap());
1529 old_map.listAllLoadableBlocks(blocks);
1531 new_db->beginSave();
1532 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1533 MapBlock *block = old_map.loadBlock(*i);
1535 errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1537 old_map.saveBlock(block, new_db);
1538 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1539 sector->deleteBlock(block);
1542 if (count % 500 == 0)
1543 actionstream << "Migrated " << count << " blocks "
1544 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1549 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1550 world_mt.set("backend", migrate_to);
1551 if (!world_mt.updateConfigFile(
1552 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1553 errorstream << "Failed to update world.mt!" << std::endl;
1555 actionstream << "world.mt updated" << std::endl;
1561 /*****************************************************************************
1563 *****************************************************************************/
1566 ClientLauncher::~ClientLauncher()
1578 if (use_freetype && font != NULL)
1583 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1585 init_args(game_params, cmd_args);
1587 // List video modes if requested
1588 if (list_video_modes)
1589 return print_video_modes();
1591 if (!init_engine(game_params.log_level)) {
1592 errorstream << "Could not initialize game engine." << std::endl;
1596 late_init_default_settings(g_settings);
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 std::string font_path = g_settings->get("font_path");
1638 std::string fallback;
1639 if (is_yes(gettext("needs_fallback_font")))
1640 fallback = "fallback_";
1641 u16 font_size = g_settings->getU16(fallback + "font_size");
1642 font_path = g_settings->get(fallback + "font_path");
1643 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1644 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1645 font = gui::CGUITTFont::createTTFont(guienv,
1646 font_path.c_str(), font_size, true, true,
1647 font_shadow, font_shadow_alpha);
1649 font = guienv->getFont(font_path.c_str());
1652 font = guienv->getFont(font_path.c_str());
1655 skin->setFont(font);
1657 errorstream << "WARNING: Font file was not found. Using default font."
1660 font = skin->getFont(); // If font was not found, this will get us one
1663 u32 text_height = font->getDimension(L"Hello, world!").Height;
1664 infostream << "text_height=" << text_height << std::endl;
1666 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1667 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1668 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1669 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1670 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1672 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1673 // Irrlicht 1.8 input colours
1674 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1675 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1678 // Create the menu clouds
1679 if (!g_menucloudsmgr)
1680 g_menucloudsmgr = smgr->createNewSceneManager();
1682 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1683 g_menucloudsmgr, -1, rand(), 100);
1684 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1685 scene::ICameraSceneNode* camera;
1686 camera = g_menucloudsmgr->addCameraSceneNode(0,
1687 v3f(0, 0, 0), v3f(0, 60, 100));
1688 camera->setFarValue(10000);
1694 ChatBackend chat_backend;
1696 // If an error occurs, this is set to something by menu().
1697 // It is then displayed before the menu shows on the next call to menu()
1698 std::wstring error_message = L"";
1700 bool first_loop = true;
1706 bool *kill = porting::signal_handler_killstatus();
1708 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1710 // Set the window caption
1711 wchar_t *text = wgettext("Main Menu");
1712 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1715 try { // This is used for catching disconnects
1720 We need some kind of a root node to be able to add
1721 custom gui elements directly on the screen.
1722 Otherwise they won't be automatically drawn.
1724 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1726 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1728 // If skip_main_menu, we only want to startup once
1729 if (skip_main_menu && !first_loop)
1734 if (!game_has_run) {
1741 // Break out of menu-game loop to shut down cleanly
1742 if (!device->run() || *kill) {
1743 if (g_settings_path != "")
1744 g_settings->updateConfigFile(g_settings_path.c_str());
1748 if (current_playername.length() > PLAYERNAME_SIZE-1) {
1749 error_message = wgettext("Player name too long.");
1750 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1751 g_settings->set("name", playername);
1755 device->getVideoDriver()->setTextureCreationFlag(
1756 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1758 #ifdef HAVE_TOUCHSCREENGUI
1759 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1760 g_touchscreengui = receiver->m_touchscreengui;
1776 simple_singleplayer_mode
1780 #ifdef HAVE_TOUCHSCREENGUI
1781 delete g_touchscreengui;
1782 g_touchscreengui = NULL;
1783 receiver->m_touchscreengui = NULL;
1787 catch (con::PeerNotFoundException &e) {
1788 error_message = wgettext("Connection error (timed out?)");
1789 errorstream << wide_to_narrow(error_message) << std::endl;
1793 catch (std::exception &e) {
1794 std::string narrow_message = "Some exception: \"";
1795 narrow_message += e.what();
1796 narrow_message += "\"";
1797 errorstream << narrow_message << std::endl;
1798 error_message = narrow_to_wide(narrow_message);
1802 // If no main menu, show error and exit
1803 if (skip_main_menu) {
1804 if (error_message != L"") {
1805 verbosestream << "error_message = "
1806 << wide_to_narrow(error_message) << std::endl;
1813 g_menuclouds->drop();
1814 g_menucloudsmgr->drop();
1819 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1822 skip_main_menu = cmd_args.getFlag("go");
1824 // FIXME: This is confusing (but correct)
1826 /* If world_path is set then override it unless skipping the main menu using
1827 * the --go command line param. Else, give preference to the address
1828 * supplied on the command line
1830 address = g_settings->get("address");
1831 if (game_params.world_path != "" && !skip_main_menu)
1833 else if (cmd_args.exists("address"))
1834 address = cmd_args.get("address");
1836 playername = g_settings->get("name");
1837 if (cmd_args.exists("name"))
1838 playername = cmd_args.get("name");
1840 list_video_modes = cmd_args.getFlag("videomodes");
1842 use_freetype = g_settings->getBool("freetype");
1844 random_input = g_settings->getBool("random_input")
1845 || cmd_args.getFlag("random-input");
1848 bool ClientLauncher::init_engine(int log_level)
1850 receiver = new MyEventReceiver();
1851 create_engine_device(log_level);
1852 return device != NULL;
1855 bool ClientLauncher::launch_game(std::wstring *error_message,
1856 GameParams &game_params, const Settings &cmd_args)
1858 // Initialize menu data
1859 MainMenuData menudata;
1860 menudata.address = address;
1861 menudata.name = playername;
1862 menudata.port = itos(game_params.socket_port);
1863 menudata.errormessage = wide_to_narrow(*error_message);
1865 *error_message = L"";
1867 if (cmd_args.exists("password"))
1868 menudata.password = cmd_args.get("password");
1870 menudata.enable_public = g_settings->getBool("server_announce");
1872 // If a world was commanded, append and select it
1873 if (game_params.world_path != "") {
1874 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1875 worldspec.name = _("[--world parameter]");
1877 if (worldspec.gameid == "") { // Create new
1878 worldspec.gameid = g_settings->get("default_game");
1879 worldspec.name += " [new]";
1881 worldspec.path = game_params.world_path;
1884 /* Show the GUI menu
1886 if (!skip_main_menu) {
1887 main_menu(&menudata);
1889 address = menudata.address;
1890 int newport = stoi(menudata.port);
1892 game_params.socket_port = newport;
1894 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1896 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1897 worldspecs = getAvailableWorlds();
1899 if (menudata.selected_world >= 0
1900 && menudata.selected_world < (int)worldspecs.size()) {
1901 g_settings->set("selected_world_path",
1902 worldspecs[menudata.selected_world].path);
1903 worldspec = worldspecs[menudata.selected_world];
1907 if (menudata.errormessage != "") {
1908 /* The calling function will pass this back into this function upon the
1909 * next iteration (if any) causing it to be displayed by the GUI
1911 *error_message = narrow_to_wide(menudata.errormessage);
1915 if (menudata.name == "")
1916 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1918 playername = menudata.name;
1920 password = translatePassword(playername, narrow_to_wide(menudata.password));
1922 g_settings->set("name", playername);
1924 current_playername = playername;
1925 current_password = password;
1926 current_address = address;
1927 current_port = game_params.socket_port;
1929 // If using simple singleplayer mode, override
1930 if (simple_singleplayer_mode) {
1931 assert(skip_main_menu == false);
1932 current_playername = "singleplayer";
1933 current_password = "";
1934 current_address = "";
1935 current_port = myrand_range(49152, 65535);
1936 } else if (address != "") {
1937 ServerListSpec server;
1938 server["name"] = menudata.servername;
1939 server["address"] = menudata.address;
1940 server["port"] = menudata.port;
1941 server["description"] = menudata.serverdescription;
1942 ServerList::insert(server);
1945 infostream << "Selected world: " << worldspec.name
1946 << " [" << worldspec.path << "]" << std::endl;
1948 if (current_address == "") { // If local game
1949 if (worldspec.path == "") {
1950 *error_message = wgettext("No world selected and no address "
1951 "provided. Nothing to do.");
1952 errorstream << wide_to_narrow(*error_message) << std::endl;
1956 if (!fs::PathExists(worldspec.path)) {
1957 *error_message = wgettext("Provided world path doesn't exist: ")
1958 + narrow_to_wide(worldspec.path);
1959 errorstream << wide_to_narrow(*error_message) << std::endl;
1963 // Load gamespec for required game
1964 gamespec = findWorldSubgame(worldspec.path);
1965 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1966 *error_message = wgettext("Could not find or load game \"")
1967 + narrow_to_wide(worldspec.gameid) + L"\"";
1968 errorstream << wide_to_narrow(*error_message) << std::endl;
1971 if (game_params.game_spec.isValid() &&
1972 game_params.game_spec.id != worldspec.gameid) {
1973 errorstream << "WARNING: Overriding gamespec from \""
1974 << worldspec.gameid << "\" to \""
1975 << game_params.game_spec.id << "\"" << std::endl;
1976 gamespec = game_params.game_spec;
1979 if (!gamespec.isValid()) {
1980 *error_message = wgettext("Invalid gamespec.");
1981 *error_message += L" (world_gameid="
1982 + narrow_to_wide(worldspec.gameid) + L")";
1983 errorstream << wide_to_narrow(*error_message) << std::endl;
1991 void ClientLauncher::main_menu(MainMenuData *menudata)
1993 bool *kill = porting::signal_handler_killstatus();
1994 video::IVideoDriver *driver = device->getVideoDriver();
1996 infostream << "Waiting for other menus" << std::endl;
1997 while (device->run() && *kill == false) {
2000 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
2003 // On some computers framerate doesn't seem to be automatically limited
2006 infostream << "Waited for other menus" << std::endl;
2008 // Cursor can be non-visible when coming from the game
2010 device->getCursorControl()->setVisible(true);
2013 /* show main menu */
2014 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
2016 smgr->clear(); /* leave scene manager in a clean state */
2019 bool ClientLauncher::create_engine_device(int log_level)
2021 static const char *driverids[] = {
2028 #ifdef _IRR_COMPILE_WITH_OGLES1_
2031 #ifdef _IRR_COMPILE_WITH_OGLES2_
2037 static const irr::ELOG_LEVEL irr_log_level[5] = {
2042 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2049 // Resolution selection
2050 bool fullscreen = g_settings->getBool("fullscreen");
2051 u16 screenW = g_settings->getU16("screenW");
2052 u16 screenH = g_settings->getU16("screenH");
2055 bool vsync = g_settings->getBool("vsync");
2056 u16 bits = g_settings->getU16("fullscreen_bpp");
2057 u16 fsaa = g_settings->getU16("fsaa");
2060 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2062 std::string driverstring = g_settings->get("video_driver");
2063 for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2064 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2065 driverType = (video::E_DRIVER_TYPE) i;
2069 if (strcasecmp("invalid", driverids[i]) == 0) {
2070 errorstream << "WARNING: Invalid video_driver specified;"
2071 << " defaulting to opengl" << std::endl;
2076 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2077 params.DriverType = driverType;
2078 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
2080 params.AntiAlias = fsaa;
2081 params.Fullscreen = fullscreen;
2082 params.Stencilbuffer = false;
2083 params.Vsync = vsync;
2084 params.EventReceiver = receiver;
2085 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2087 params.PrivateData = porting::app_global;
2088 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2089 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2092 device = createDeviceEx(params);
2095 // Map our log level to irrlicht engine one.
2096 ILogger* irr_logger = device->getLogger();
2097 irr_logger->setLogLevel(irr_log_level[log_level]);
2099 porting::initIrrlicht(device);
2102 return device != NULL;
2107 static bool print_video_modes()
2109 IrrlichtDevice *nulldevice;
2111 bool vsync = g_settings->getBool("vsync");
2112 u16 fsaa = g_settings->getU16("fsaa");
2113 MyEventReceiver* receiver = new MyEventReceiver();
2115 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2116 params.DriverType = video::EDT_NULL;
2117 params.WindowSize = core::dimension2d<u32>(640, 480);
2119 params.AntiAlias = fsaa;
2120 params.Fullscreen = false;
2121 params.Stencilbuffer = false;
2122 params.Vsync = vsync;
2123 params.EventReceiver = receiver;
2124 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2126 nulldevice = createDeviceEx(params);
2128 if (nulldevice == NULL) {
2133 dstream << _("Available video modes (WxHxD):") << std::endl;
2135 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2137 if (videomode_list != NULL) {
2138 s32 videomode_count = videomode_list->getVideoModeCount();
2139 core::dimension2d<u32> videomode_res;
2140 s32 videomode_depth;
2141 for (s32 i = 0; i < videomode_count; ++i) {
2142 videomode_res = videomode_list->getVideoModeResolution(i);
2143 videomode_depth = videomode_list->getVideoModeDepth(i);
2144 dstream << videomode_res.Width << "x" << videomode_res.Height
2145 << "x" << videomode_depth << std::endl;
2148 dstream << _("Active video mode (WxHxD):") << std::endl;
2149 videomode_res = videomode_list->getDesktopResolution();
2150 videomode_depth = videomode_list->getDesktopDepth();
2151 dstream << videomode_res.Width << "x" << videomode_res.Height
2152 << "x" << videomode_depth << std::endl;
2159 return videomode_list != NULL;
2164 /*****************************************************************************
2166 *****************************************************************************/
2168 static void speed_tests()
2170 // volatile to avoid some potential compiler optimisations
2171 volatile static s16 temp16;
2172 volatile static f32 tempf;
2173 static v3f tempv3f1;
2174 static v3f tempv3f2;
2175 static std::string tempstring;
2176 static std::string tempstring2;
2180 tempstring = std::string();
2181 tempstring2 = std::string();
2184 infostream << "The following test should take around 20ms." << std::endl;
2185 TimeTaker timer("Testing std::string speed");
2186 const u32 jj = 10000;
2187 for (u32 j = 0; j < jj; j++) {
2191 for (u32 i = 0; i < ii; i++) {
2192 tempstring2 += "asd";
2194 for (u32 i = 0; i < ii+1; i++) {
2195 tempstring += "asd";
2196 if (tempstring == tempstring2)
2202 infostream << "All of the following tests should take around 100ms each."
2206 TimeTaker timer("Testing floating-point conversion speed");
2208 for (u32 i = 0; i < 4000000; i++) {
2215 TimeTaker timer("Testing floating-point vector speed");
2217 tempv3f1 = v3f(1, 2, 3);
2218 tempv3f2 = v3f(4, 5, 6);
2219 for (u32 i = 0; i < 10000000; i++) {
2220 tempf += tempv3f1.dotProduct(tempv3f2);
2221 tempv3f2 += v3f(7, 8, 9);
2226 TimeTaker timer("Testing std::map speed");
2228 std::map<v2s16, f32> map1;
2231 for (s16 y = 0; y < ii; y++) {
2232 for (s16 x = 0; x < ii; x++) {
2233 map1[v2s16(x, y)] = tempf;
2237 for (s16 y = ii - 1; y >= 0; y--) {
2238 for (s16 x = 0; x < ii; x++) {
2239 tempf = map1[v2s16(x, y)];
2245 infostream << "Around 5000/ms should do well here." << std::endl;
2246 TimeTaker timer("Testing mutex speed");
2253 for (; i < n; i++) {
2259 while(timer.getTimerTime() < 10);
2261 u32 dtime = timer.stop();
2262 u32 per_ms = n / dtime;
2263 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;