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);
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))
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);
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)
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;
1399 } else { // World exists
1400 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1401 // If commanded to use a gameid, do so
1402 if (game_params->game_spec.isValid()) {
1403 gamespec = game_params->game_spec;
1404 if (game_params->game_spec.id != world_gameid) {
1405 errorstream << "WARNING: Using commanded gameid ["
1406 << gamespec.id << "]" << " instead of world gameid ["
1407 << world_gameid << "]" << std::endl;
1410 // If world contains an embedded game, use it;
1411 // Otherwise find world from local system.
1412 gamespec = findWorldSubgame(game_params->world_path);
1413 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1417 if (!gamespec.isValid()) {
1418 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1423 game_params->game_spec = gamespec;
1428 /*****************************************************************************
1430 *****************************************************************************/
1431 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1433 DSTACK("Dedicated server branch");
1435 verbosestream << _("Using world path") << " ["
1436 << game_params.world_path << "]" << std::endl;
1437 verbosestream << _("Using gameid") << " ["
1438 << game_params.game_spec.id << "]" << std::endl;
1441 std::string bind_str = g_settings->get("bind_address");
1442 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1444 if (g_settings->getBool("ipv6_server")) {
1445 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1448 bind_addr.Resolve(bind_str.c_str());
1449 } catch (ResolveError &e) {
1450 infostream << "Resolving bind address \"" << bind_str
1451 << "\" failed: " << e.what()
1452 << " -- Listening on all addresses." << std::endl;
1454 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1455 errorstream << "Unable to listen on "
1456 << bind_addr.serializeString()
1457 << L" because IPv6 is disabled" << std::endl;
1462 Server server(game_params.world_path,
1463 game_params.game_spec, false, bind_addr.isIPv6());
1465 // Database migration
1466 if (cmd_args.exists("migrate"))
1467 return migrate_database(game_params, cmd_args, &server);
1469 server.start(bind_addr);
1472 bool &kill = *porting::signal_handler_killstatus();
1473 dedicated_server_loop(server, kill);
1478 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1482 bool success = world_mt.readConfigFile((game_params.world_path
1483 + DIR_DELIM + "world.mt").c_str());
1485 errorstream << "Cannot read world.mt" << std::endl;
1489 if (!world_mt.exists("backend")) {
1490 errorstream << "Please specify your current backend in world.mt file:"
1491 << std::endl << " backend = {sqlite3|leveldb|redis|dummy}"
1496 std::string backend = world_mt.get("backend");
1498 std::string migrate_to = cmd_args.get("migrate");
1500 if (backend == migrate_to) {
1501 errorstream << "Cannot migrate: new backend is same as the old one"
1506 if (migrate_to == "sqlite3")
1507 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1508 game_params.world_path);
1510 else if (migrate_to == "leveldb")
1511 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1512 game_params.world_path);
1515 else if (migrate_to == "redis")
1516 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1517 game_params.world_path);
1520 errorstream << "Migration to " << migrate_to << " is not supported"
1525 std::list<v3s16> blocks;
1526 ServerMap &old_map = ((ServerMap&)server->getMap());
1527 old_map.listAllLoadableBlocks(blocks);
1529 new_db->beginSave();
1530 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1531 MapBlock *block = old_map.loadBlock(*i);
1533 errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1535 old_map.saveBlock(block, new_db);
1536 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1537 sector->deleteBlock(block);
1540 if (count % 500 == 0)
1541 actionstream << "Migrated " << count << " blocks "
1542 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1547 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1548 world_mt.set("backend", migrate_to);
1549 if (!world_mt.updateConfigFile(
1550 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1551 errorstream << "Failed to update world.mt!" << std::endl;
1553 actionstream << "world.mt updated" << std::endl;
1559 /*****************************************************************************
1561 *****************************************************************************/
1564 ClientLauncher::~ClientLauncher()
1576 if (use_freetype && font != NULL)
1581 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1583 init_args(game_params, cmd_args);
1585 // List video modes if requested
1586 if (list_video_modes)
1587 return print_video_modes();
1589 if (!init_engine(game_params.log_level)) {
1590 errorstream << "Could not initialize game engine." << std::endl;
1594 late_init_default_settings(g_settings);
1596 // Speed tests (done after irrlicht is loaded to get timer)
1597 if (cmd_args.getFlag("speedtests")) {
1598 dstream << "Running speed tests" << std::endl;
1603 if (device->getVideoDriver() == NULL) {
1604 errorstream << "Could not initialize video driver." << std::endl;
1609 This changes the minimum allowed number of vertices in a VBO.
1612 //driver->setMinHardwareBufferVertexCount(50);
1614 // Create time getter
1615 g_timegetter = new IrrlichtTimeGetter(device);
1617 // Create game callback for menus
1618 g_gamecallback = new MainGameCallback(device);
1620 device->setResizable(true);
1623 input = new RandomInputHandler();
1625 input = new RealInputHandler(device, receiver);
1627 smgr = device->getSceneManager();
1629 guienv = device->getGUIEnvironment();
1630 skin = guienv->getSkin();
1631 std::string font_path = g_settings->get("font_path");
1636 std::string fallback;
1637 if (is_yes(gettext("needs_fallback_font")))
1638 fallback = "fallback_";
1639 u16 font_size = g_settings->getU16(fallback + "font_size");
1640 font_path = g_settings->get(fallback + "font_path");
1641 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1642 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1643 font = gui::CGUITTFont::createTTFont(guienv,
1644 font_path.c_str(), font_size, true, true,
1645 font_shadow, font_shadow_alpha);
1647 font = guienv->getFont(font_path.c_str());
1650 font = guienv->getFont(font_path.c_str());
1653 skin->setFont(font);
1655 errorstream << "WARNING: Font file was not found. Using default font."
1658 font = skin->getFont(); // If font was not found, this will get us one
1661 u32 text_height = font->getDimension(L"Hello, world!").Height;
1662 infostream << "text_height=" << text_height << std::endl;
1664 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1665 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1666 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1667 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1668 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1670 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1671 // Irrlicht 1.8 input colours
1672 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1673 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1676 // Create the menu clouds
1677 if (!g_menucloudsmgr)
1678 g_menucloudsmgr = smgr->createNewSceneManager();
1680 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1681 g_menucloudsmgr, -1, rand(), 100);
1682 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1683 scene::ICameraSceneNode* camera;
1684 camera = g_menucloudsmgr->addCameraSceneNode(0,
1685 v3f(0, 0, 0), v3f(0, 60, 100));
1686 camera->setFarValue(10000);
1692 ChatBackend chat_backend;
1694 // If an error occurs, this is set to something by menu().
1695 // It is then displayed before the menu shows on the next call to menu()
1696 std::wstring error_message = L"";
1698 bool first_loop = true;
1704 bool *kill = porting::signal_handler_killstatus();
1706 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1708 // Set the window caption
1709 wchar_t *text = wgettext("Main Menu");
1710 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1713 try { // This is used for catching disconnects
1718 We need some kind of a root node to be able to add
1719 custom gui elements directly on the screen.
1720 Otherwise they won't be automatically drawn.
1722 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1724 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1726 // If skip_main_menu, we only want to startup once
1727 if (skip_main_menu && !first_loop)
1732 if (!game_has_run) {
1739 // Break out of menu-game loop to shut down cleanly
1740 if (!device->run() || *kill) {
1741 if (g_settings_path != "")
1742 g_settings->updateConfigFile(g_settings_path.c_str());
1746 if (current_playername.length() > PLAYERNAME_SIZE-1) {
1747 error_message = wgettext("Player name too long.");
1748 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1749 g_settings->set("name", playername);
1753 device->getVideoDriver()->setTextureCreationFlag(
1754 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1756 #ifdef HAVE_TOUCHSCREENGUI
1757 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1758 g_touchscreengui = receiver->m_touchscreengui;
1774 simple_singleplayer_mode
1778 #ifdef HAVE_TOUCHSCREENGUI
1779 delete g_touchscreengui;
1780 g_touchscreengui = NULL;
1781 receiver->m_touchscreengui = NULL;
1785 catch (con::PeerNotFoundException &e) {
1786 error_message = wgettext("Connection error (timed out?)");
1787 errorstream << wide_to_narrow(error_message) << std::endl;
1791 catch (std::exception &e) {
1792 std::string narrow_message = "Some exception: \"";
1793 narrow_message += e.what();
1794 narrow_message += "\"";
1795 errorstream << narrow_message << std::endl;
1796 error_message = narrow_to_wide(narrow_message);
1800 // If no main menu, show error and exit
1801 if (skip_main_menu) {
1802 if (error_message != L"") {
1803 verbosestream << "error_message = "
1804 << wide_to_narrow(error_message) << std::endl;
1811 g_menuclouds->drop();
1812 g_menucloudsmgr->drop();
1817 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1819 address = g_settings->get("address");
1820 if (game_params.world_path != "")
1822 else if (cmd_args.exists("address"))
1823 address = cmd_args.get("address");
1825 playername = g_settings->get("name");
1826 if (cmd_args.exists("name"))
1827 playername = cmd_args.get("name");
1829 skip_main_menu = cmd_args.getFlag("go");
1831 list_video_modes = cmd_args.getFlag("videomodes");
1833 use_freetype = g_settings->getBool("freetype");
1835 random_input = g_settings->getBool("random_input")
1836 || cmd_args.getFlag("random-input");
1839 bool ClientLauncher::init_engine(int log_level)
1841 receiver = new MyEventReceiver();
1842 create_engine_device(log_level);
1843 return device != NULL;
1846 bool ClientLauncher::launch_game(std::wstring *error_message,
1847 GameParams &game_params, const Settings &cmd_args)
1849 // Initialize menu data
1850 MainMenuData menudata;
1851 menudata.address = address;
1852 menudata.name = playername;
1853 menudata.port = itos(game_params.socket_port);
1854 menudata.errormessage = wide_to_narrow(*error_message);
1856 *error_message = L"";
1858 if (cmd_args.exists("password"))
1859 menudata.password = cmd_args.get("password");
1861 menudata.enable_public = g_settings->getBool("server_announce");
1863 // If a world was commanded, append and select it
1864 if (game_params.world_path != "") {
1865 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1866 worldspec.name = _("[--world parameter]");
1868 if (worldspec.gameid == "") { // Create new
1869 worldspec.gameid = g_settings->get("default_game");
1870 worldspec.name += " [new]";
1872 worldspec.path = game_params.world_path;
1875 /* Show the GUI menu
1877 if (!skip_main_menu) {
1878 main_menu(&menudata);
1880 address = menudata.address;
1881 int newport = stoi(menudata.port);
1883 game_params.socket_port = newport;
1885 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1887 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1888 worldspecs = getAvailableWorlds();
1890 if (menudata.selected_world >= 0
1891 && menudata.selected_world < (int)worldspecs.size()) {
1892 g_settings->set("selected_world_path",
1893 worldspecs[menudata.selected_world].path);
1894 worldspec = worldspecs[menudata.selected_world];
1898 if (menudata.errormessage != "") {
1899 /* The calling function will pass this back into this function upon the
1900 * next iteration (if any) causing it to be displayed by the GUI
1902 *error_message = narrow_to_wide(menudata.errormessage);
1906 if (menudata.name == "")
1907 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1909 playername = menudata.name;
1911 password = translatePassword(playername, narrow_to_wide(menudata.password));
1913 g_settings->set("name", playername);
1915 current_playername = playername;
1916 current_password = password;
1917 current_address = address;
1918 current_port = game_params.socket_port;
1920 // If using simple singleplayer mode, override
1921 if (simple_singleplayer_mode) {
1922 assert(skip_main_menu == false);
1923 current_playername = "singleplayer";
1924 current_password = "";
1925 current_address = "";
1926 current_port = myrand_range(49152, 65535);
1927 } else if (address != "") {
1928 ServerListSpec server;
1929 server["name"] = menudata.servername;
1930 server["address"] = menudata.address;
1931 server["port"] = menudata.port;
1932 server["description"] = menudata.serverdescription;
1933 ServerList::insert(server);
1936 infostream << "Selected world: " << worldspec.name
1937 << " [" << worldspec.path << "]" << std::endl;
1939 if (current_address == "") { // If local game
1940 if (worldspec.path == "") {
1941 *error_message = wgettext("No world selected and no address "
1942 "provided. Nothing to do.");
1943 errorstream << wide_to_narrow(*error_message) << std::endl;
1947 if (!fs::PathExists(worldspec.path)) {
1948 *error_message = wgettext("Provided world path doesn't exist: ")
1949 + narrow_to_wide(worldspec.path);
1950 errorstream << wide_to_narrow(*error_message) << std::endl;
1954 // Load gamespec for required game
1955 gamespec = findWorldSubgame(worldspec.path);
1956 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1957 *error_message = wgettext("Could not find or load game \"")
1958 + narrow_to_wide(worldspec.gameid) + L"\"";
1959 errorstream << wide_to_narrow(*error_message) << std::endl;
1962 if (game_params.game_spec.isValid() &&
1963 game_params.game_spec.id != worldspec.gameid) {
1964 errorstream << "WARNING: Overriding gamespec from \""
1965 << worldspec.gameid << "\" to \""
1966 << game_params.game_spec.id << "\"" << std::endl;
1967 gamespec = game_params.game_spec;
1970 if (!gamespec.isValid()) {
1971 *error_message = wgettext("Invalid gamespec.");
1972 *error_message += L" (world_gameid="
1973 + narrow_to_wide(worldspec.gameid) + L")";
1974 errorstream << wide_to_narrow(*error_message) << std::endl;
1982 void ClientLauncher::main_menu(MainMenuData *menudata)
1984 bool *kill = porting::signal_handler_killstatus();
1985 video::IVideoDriver *driver = device->getVideoDriver();
1987 infostream << "Waiting for other menus" << std::endl;
1988 while (device->run() && *kill == false) {
1991 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1994 // On some computers framerate doesn't seem to be automatically limited
1997 infostream << "Waited for other menus" << std::endl;
1999 // Cursor can be non-visible when coming from the game
2001 device->getCursorControl()->setVisible(true);
2004 /* show main menu */
2005 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
2007 smgr->clear(); /* leave scene manager in a clean state */
2010 bool ClientLauncher::create_engine_device(int log_level)
2012 static const char *driverids[] = {
2019 #ifdef _IRR_COMPILE_WITH_OGLES1_
2022 #ifdef _IRR_COMPILE_WITH_OGLES2_
2028 static const irr::ELOG_LEVEL irr_log_level[5] = {
2033 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2040 // Resolution selection
2041 bool fullscreen = g_settings->getBool("fullscreen");
2042 u16 screenW = g_settings->getU16("screenW");
2043 u16 screenH = g_settings->getU16("screenH");
2046 bool vsync = g_settings->getBool("vsync");
2047 u16 bits = g_settings->getU16("fullscreen_bpp");
2048 u16 fsaa = g_settings->getU16("fsaa");
2051 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2053 std::string driverstring = g_settings->get("video_driver");
2054 for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2055 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2056 driverType = (video::E_DRIVER_TYPE) i;
2060 if (strcasecmp("invalid", driverids[i]) == 0) {
2061 errorstream << "WARNING: Invalid video_driver specified;"
2062 << " defaulting to opengl" << std::endl;
2067 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2068 params.DriverType = driverType;
2069 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
2071 params.AntiAlias = fsaa;
2072 params.Fullscreen = fullscreen;
2073 params.Stencilbuffer = false;
2074 params.Vsync = vsync;
2075 params.EventReceiver = receiver;
2076 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2078 params.PrivateData = porting::app_global;
2079 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2080 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2083 device = createDeviceEx(params);
2086 // Map our log level to irrlicht engine one.
2087 ILogger* irr_logger = device->getLogger();
2088 irr_logger->setLogLevel(irr_log_level[log_level]);
2090 porting::initIrrlicht(device);
2093 return device != NULL;
2098 static bool print_video_modes()
2100 IrrlichtDevice *nulldevice;
2102 bool vsync = g_settings->getBool("vsync");
2103 u16 fsaa = g_settings->getU16("fsaa");
2104 MyEventReceiver* receiver = new MyEventReceiver();
2106 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2107 params.DriverType = video::EDT_NULL;
2108 params.WindowSize = core::dimension2d<u32>(640, 480);
2110 params.AntiAlias = fsaa;
2111 params.Fullscreen = false;
2112 params.Stencilbuffer = false;
2113 params.Vsync = vsync;
2114 params.EventReceiver = receiver;
2115 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2117 nulldevice = createDeviceEx(params);
2119 if (nulldevice == NULL) {
2124 dstream << _("Available video modes (WxHxD):") << std::endl;
2126 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2128 if (videomode_list != NULL) {
2129 s32 videomode_count = videomode_list->getVideoModeCount();
2130 core::dimension2d<u32> videomode_res;
2131 s32 videomode_depth;
2132 for (s32 i = 0; i < videomode_count; ++i) {
2133 videomode_res = videomode_list->getVideoModeResolution(i);
2134 videomode_depth = videomode_list->getVideoModeDepth(i);
2135 dstream << videomode_res.Width << "x" << videomode_res.Height
2136 << "x" << videomode_depth << std::endl;
2139 dstream << _("Active video mode (WxHxD):") << std::endl;
2140 videomode_res = videomode_list->getDesktopResolution();
2141 videomode_depth = videomode_list->getDesktopDepth();
2142 dstream << videomode_res.Width << "x" << videomode_res.Height
2143 << "x" << videomode_depth << std::endl;
2150 return videomode_list != NULL;
2155 /*****************************************************************************
2157 *****************************************************************************/
2159 static void speed_tests()
2161 // volatile to avoid some potential compiler optimisations
2162 volatile static s16 temp16;
2163 volatile static f32 tempf;
2164 static v3f tempv3f1;
2165 static v3f tempv3f2;
2166 static std::string tempstring;
2167 static std::string tempstring2;
2171 tempstring = std::string();
2172 tempstring2 = std::string();
2175 infostream << "The following test should take around 20ms." << std::endl;
2176 TimeTaker timer("Testing std::string speed");
2177 const u32 jj = 10000;
2178 for (u32 j = 0; j < jj; j++) {
2182 for (u32 i = 0; i < ii; i++) {
2183 tempstring2 += "asd";
2185 for (u32 i = 0; i < ii+1; i++) {
2186 tempstring += "asd";
2187 if (tempstring == tempstring2)
2193 infostream << "All of the following tests should take around 100ms each."
2197 TimeTaker timer("Testing floating-point conversion speed");
2199 for (u32 i = 0; i < 4000000; i++) {
2206 TimeTaker timer("Testing floating-point vector speed");
2208 tempv3f1 = v3f(1, 2, 3);
2209 tempv3f2 = v3f(4, 5, 6);
2210 for (u32 i = 0; i < 10000000; i++) {
2211 tempf += tempv3f1.dotProduct(tempv3f2);
2212 tempv3f2 += v3f(7, 8, 9);
2217 TimeTaker timer("Testing std::map speed");
2219 std::map<v2s16, f32> map1;
2222 for (s16 y = 0; y < ii; y++) {
2223 for (s16 x = 0; x < ii; x++) {
2224 map1[v2s16(x, y)] = tempf;
2228 for (s16 y = ii - 1; y >= 0; y--) {
2229 for (s16 x = 0; x < ii; x++) {
2230 tempf = map1[v2s16(x, y)];
2236 infostream << "Around 5000/ms should do well here." << std::endl;
2237 TimeTaker timer("Testing mutex speed");
2244 for (; i < n; i++) {
2250 while(timer.getTimerTime() < 10);
2252 u32 dtime = timer.stop();
2253 u32 per_ms = n / dtime;
2254 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;