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"
83 #include "database-sqlite3.h"
85 #include "database-leveldb.h"
88 #include "database-redis.h"
93 These are loaded from the config file.
95 Settings main_settings;
96 Settings *g_settings = &main_settings;
97 std::string g_settings_path;
100 Profiler main_profiler;
101 Profiler *g_profiler = &main_profiler;
103 // Menu clouds are created later
104 Clouds *g_menuclouds = 0;
105 irr::scene::ISceneManager *g_menucloudsmgr = 0;
112 std::ostream *dout_con_ptr = &dummyout;
113 std::ostream *derr_con_ptr = &verbosestream;
116 std::ostream *dout_server_ptr = &infostream;
117 std::ostream *derr_server_ptr = &errorstream;
120 std::ostream *dout_client_ptr = &infostream;
121 std::ostream *derr_client_ptr = &errorstream;
128 /* mainmenumanager.h */
130 gui::IGUIEnvironment* guienv = NULL;
131 gui::IGUIStaticText *guiroot = NULL;
132 MainMenuManager g_menumgr;
136 return (g_menumgr.menuCount() == 0);
139 // Passed to menus to allow disconnecting and exiting
140 MainGameCallback *g_gamecallback = NULL;
144 gettime.h implementation
151 /* Use imprecise system calls directly (from porting.h) */
152 return porting::getTime(PRECISION_MILLI);
155 u32 getTime(TimePrecision prec)
157 return porting::getTime(prec);
162 // A small helper class
166 virtual u32 getTime(TimePrecision prec) = 0;
169 // A precise irrlicht one
170 class IrrlichtTimeGetter: public TimeGetter
173 IrrlichtTimeGetter(IrrlichtDevice *device):
176 u32 getTime(TimePrecision prec)
178 if (prec == PRECISION_MILLI) {
181 return m_device->getTimer()->getRealTime();
183 return porting::getTime(prec);
187 IrrlichtDevice *m_device;
189 // Not so precise one which works without irrlicht
190 class SimpleTimeGetter: public TimeGetter
193 u32 getTime(TimePrecision prec)
195 return porting::getTime(prec);
199 // A pointer to a global instance of the time getter
201 TimeGetter *g_timegetter = NULL;
205 if(g_timegetter == NULL)
207 return g_timegetter->getTime(PRECISION_MILLI);
210 u32 getTime(TimePrecision prec) {
211 if (g_timegetter == NULL)
213 return g_timegetter->getTime(prec);
217 class StderrLogOutput: public ILogOutput
220 /* line: Full line with timestamp, level and thread */
221 void printLog(const std::string &line)
223 std::cerr<<line<<std::endl;
225 } main_stderr_log_out;
227 class DstreamNoStderrLogOutput: public ILogOutput
230 /* line: Full line with timestamp, level and thread */
231 void printLog(const std::string &line)
233 dstream_no_stderr<<line<<std::endl;
235 } main_dstream_no_stderr_log_out;
240 Event handler for Irrlicht
242 NOTE: Everything possible should be moved out from here,
243 probably to InputHandler and the_game
246 class MyEventReceiver : public IEventReceiver
249 // This is the one method that we have to implement
250 virtual bool OnEvent(const SEvent& event)
253 React to nothing here if a menu is active
255 if(noMenuActive() == false)
257 return g_menumgr.preprocessEvent(event);
260 // Remember whether each key is down or up
261 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
263 if(event.KeyInput.PressedDown) {
264 keyIsDown.set(event.KeyInput);
265 keyWasDown.set(event.KeyInput);
267 keyIsDown.unset(event.KeyInput);
271 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
273 if(noMenuActive() == false)
276 middle_active = false;
277 right_active = false;
281 left_active = event.MouseInput.isLeftPressed();
282 middle_active = event.MouseInput.isMiddlePressed();
283 right_active = event.MouseInput.isRightPressed();
285 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
289 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
293 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
297 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
299 rightreleased = true;
301 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
303 mouse_wheel += event.MouseInput.Wheel;
307 if(event.EventType == irr::EET_LOG_TEXT_EVENT)
309 dstream<<"Irrlicht log: "<<event.LogEvent.Text<<std::endl;
312 /* always return false in order to continue processing events */
316 bool IsKeyDown(const KeyPress &keyCode) const
318 return keyIsDown[keyCode];
321 // Checks whether a key was down and resets the state
322 bool WasKeyDown(const KeyPress &keyCode)
324 bool b = keyWasDown[keyCode];
326 keyWasDown.unset(keyCode);
343 rightclicked = false;
344 leftreleased = false;
345 rightreleased = false;
348 middle_active = false;
349 right_active = false;
372 // The current state of keys
374 // Whether a key has been pressed or not
379 Separated input handler
382 class RealInputHandler : public InputHandler
385 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
390 virtual bool isKeyDown(const KeyPress &keyCode)
392 return m_receiver->IsKeyDown(keyCode);
394 virtual bool wasKeyDown(const KeyPress &keyCode)
396 return m_receiver->WasKeyDown(keyCode);
398 virtual v2s32 getMousePos()
400 return m_device->getCursorControl()->getPosition();
402 virtual void setMousePos(s32 x, s32 y)
404 m_device->getCursorControl()->setPosition(x, y);
407 virtual bool getLeftState()
409 return m_receiver->left_active;
411 virtual bool getRightState()
413 return m_receiver->right_active;
416 virtual bool getLeftClicked()
418 return m_receiver->leftclicked;
420 virtual bool getRightClicked()
422 return m_receiver->rightclicked;
424 virtual void resetLeftClicked()
426 m_receiver->leftclicked = false;
428 virtual void resetRightClicked()
430 m_receiver->rightclicked = false;
433 virtual bool getLeftReleased()
435 return m_receiver->leftreleased;
437 virtual bool getRightReleased()
439 return m_receiver->rightreleased;
441 virtual void resetLeftReleased()
443 m_receiver->leftreleased = false;
445 virtual void resetRightReleased()
447 m_receiver->rightreleased = false;
450 virtual s32 getMouseWheel()
452 return m_receiver->getMouseWheel();
457 m_receiver->clearInput();
460 IrrlichtDevice *m_device;
461 MyEventReceiver *m_receiver;
464 class RandomInputHandler : public InputHandler
472 rightclicked = false;
473 leftreleased = false;
474 rightreleased = false;
477 virtual bool isKeyDown(const KeyPress &keyCode)
479 return keydown[keyCode];
481 virtual bool wasKeyDown(const KeyPress &keyCode)
485 virtual v2s32 getMousePos()
489 virtual void setMousePos(s32 x, s32 y)
491 mousepos = v2s32(x,y);
494 virtual bool getLeftState()
498 virtual bool getRightState()
503 virtual bool getLeftClicked()
507 virtual bool getRightClicked()
511 virtual void resetLeftClicked()
515 virtual void resetRightClicked()
517 rightclicked = false;
520 virtual bool getLeftReleased()
524 virtual bool getRightReleased()
526 return rightreleased;
528 virtual void resetLeftReleased()
530 leftreleased = false;
532 virtual void resetRightReleased()
534 rightreleased = false;
537 virtual s32 getMouseWheel()
542 virtual void step(float dtime)
545 static float counter1 = 0;
549 counter1 = 0.1*Rand(1, 40);
550 keydown.toggle(getKeySetting("keymap_jump"));
554 static float counter1 = 0;
558 counter1 = 0.1*Rand(1, 40);
559 keydown.toggle(getKeySetting("keymap_special1"));
563 static float counter1 = 0;
567 counter1 = 0.1*Rand(1, 40);
568 keydown.toggle(getKeySetting("keymap_forward"));
572 static float counter1 = 0;
576 counter1 = 0.1*Rand(1, 40);
577 keydown.toggle(getKeySetting("keymap_left"));
581 static float counter1 = 0;
585 counter1 = 0.1*Rand(1, 20);
586 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
590 static float counter1 = 0;
594 counter1 = 0.1*Rand(1, 30);
595 leftdown = !leftdown;
603 static float counter1 = 0;
607 counter1 = 0.1*Rand(1, 15);
608 rightdown = !rightdown;
612 rightreleased = true;
615 mousepos += mousespeed;
618 s32 Rand(s32 min, s32 max)
620 return (myrand()%(max-min+1))+min;
636 // These are defined global so that they're not optimized too much.
637 // Can't change them to volatile.
642 std::string tempstring;
643 std::string tempstring2;
648 infostream<<"The following test should take around 20ms."<<std::endl;
649 TimeTaker timer("Testing std::string speed");
650 const u32 jj = 10000;
651 for(u32 j=0; j<jj; j++)
656 for(u32 i=0; i<ii; i++){
657 tempstring2 += "asd";
659 for(u32 i=0; i<ii+1; i++){
661 if(tempstring == tempstring2)
667 infostream<<"All of the following tests should take around 100ms each."
671 TimeTaker timer("Testing floating-point conversion speed");
673 for(u32 i=0; i<4000000; i++){
680 TimeTaker timer("Testing floating-point vector speed");
682 tempv3f1 = v3f(1,2,3);
683 tempv3f2 = v3f(4,5,6);
684 for(u32 i=0; i<10000000; i++){
685 tempf += tempv3f1.dotProduct(tempv3f2);
686 tempv3f2 += v3f(7,8,9);
691 TimeTaker timer("Testing std::map speed");
693 std::map<v2s16, f32> map1;
696 for(s16 y=0; y<ii; y++){
697 for(s16 x=0; x<ii; x++){
698 map1[v2s16(x,y)] = tempf;
702 for(s16 y=ii-1; y>=0; y--){
703 for(s16 x=0; x<ii; x++){
704 tempf = map1[v2s16(x,y)];
710 infostream<<"Around 5000/ms should do well here."<<std::endl;
711 TimeTaker timer("Testing mutex speed");
724 while(timer.getTimerTime() < 10);
726 u32 dtime = timer.stop();
727 u32 per_ms = n / dtime;
728 infostream<<"Done. "<<dtime<<"ms, "
729 <<per_ms<<"/ms"<<std::endl;
733 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
736 for(u32 i=0; i<worldspecs.size(); i++){
737 std::string name = worldspecs[i].name;
738 std::string path = worldspecs[i].path;
739 if(name.find(" ") != std::string::npos)
740 name = std::string("'") + name + "'";
741 path = std::string("'") + path + "'";
742 name = padStringRight(name, 14);
743 os<<" "<<name<<" "<<path<<std::endl;
747 int main(int argc, char *argv[])
755 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
756 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
758 log_register_thread("main");
763 // List all allowed options
764 std::map<std::string, ValueSpec> allowed_options;
765 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
766 _("Show allowed options"))));
767 allowed_options.insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
768 _("Show version information"))));
769 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
770 _("Load configuration from specified file"))));
771 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
772 _("Set network port (UDP)"))));
773 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
774 _("Disable unit tests"))));
775 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
776 _("Enable unit tests"))));
777 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
778 _("Same as --world (deprecated)"))));
779 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
780 _("Set world path (implies local game) ('list' lists all)"))));
781 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
782 _("Set world by name (implies local game)"))));
783 allowed_options.insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
784 _("Print to console errors only"))));
785 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
786 _("Print more information to console"))));
787 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
788 _("Print even more information to console"))));
789 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
790 _("Print enormous amounts of information to log and console"))));
791 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
792 _("Set logfile path ('' = no logging)"))));
793 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
794 _("Set gameid (\"--gameid list\" prints available ones)"))));
795 allowed_options.insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
796 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
798 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
799 _("Show available video modes"))));
800 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
801 _("Run speed tests"))));
802 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
803 _("Address to connect to. ('' = local game)"))));
804 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
805 _("Enable random user input, for testing"))));
806 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
807 _("Run dedicated server"))));
808 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
809 _("Set player name"))));
810 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
811 _("Set password"))));
812 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
813 _("Disable main menu"))));
818 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
820 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
822 dstream<<_("Allowed options:")<<std::endl;
823 for(std::map<std::string, ValueSpec>::iterator
824 i = allowed_options.begin();
825 i != allowed_options.end(); ++i)
827 std::ostringstream os1(std::ios::binary);
828 os1<<" --"<<i->first;
829 if(i->second.type == VALUETYPE_FLAG)
833 dstream<<padStringRight(os1.str(), 24);
835 if(i->second.help != NULL)
836 dstream<<i->second.help;
840 return cmd_args.getFlag("help") ? 0 : 1;
843 if(cmd_args.getFlag("version"))
846 dstream<<"minetestserver "<<minetest_version_hash<<std::endl;
848 dstream<<"Minetest "<<minetest_version_hash<<std::endl;
849 dstream<<"Using Irrlicht "<<IRRLICHT_SDK_VERSION<<std::endl;
851 dstream<<"Build info: "<<minetest_build_info<<std::endl;
856 Low-level initialization
859 // Quiet mode, print errors only
860 if(cmd_args.getFlag("quiet")){
861 log_remove_output(&main_stderr_log_out);
862 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
864 // If trace is enabled, enable logging of certain things
865 if(cmd_args.getFlag("trace")){
866 dstream<<_("Enabling trace level debug output")<<std::endl;
867 log_trace_level_enabled = true;
868 dout_con_ptr = &verbosestream; // this is somewhat old crap
869 socket_enable_debug_output = true; // socket doesn't use log.h
871 // In certain cases, output info level on stderr
872 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
873 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
874 log_add_output(&main_stderr_log_out, LMT_INFO);
875 // In certain cases, output verbose level on stderr
876 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
877 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
879 porting::signal_handler_init();
880 bool &kill = *porting::signal_handler_killstatus();
882 porting::initializePaths();
884 // Create user data directory
885 fs::CreateDir(porting::path_user);
887 infostream<<"path_share = "<<porting::path_share<<std::endl;
888 infostream<<"path_user = "<<porting::path_user<<std::endl;
890 // Initialize debug stacks
892 DSTACK(__FUNCTION_NAME);
895 BEGIN_DEBUG_EXCEPTION_HANDLER
897 // List gameids if requested
898 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
900 std::set<std::string> gameids = getAvailableGameIds();
901 for(std::set<std::string>::const_iterator i = gameids.begin();
902 i != gameids.end(); i++)
903 dstream<<(*i)<<std::endl;
907 // List worlds if requested
908 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
909 dstream<<_("Available worlds:")<<std::endl;
910 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
911 print_worldspecs(worldspecs, dstream);
915 // Print startup message
916 infostream<<PROJECT_NAME<<
917 " "<<_("with")<<" SER_FMT_VER_HIGHEST_READ="<<(int)SER_FMT_VER_HIGHEST_READ
918 <<", "<<minetest_build_info
925 // Initialize default settings
926 set_default_settings(g_settings);
928 // Initialize sockets
930 atexit(sockets_cleanup);
936 // Path of configuration file in use
937 g_settings_path = "";
939 if(cmd_args.exists("config"))
941 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
944 errorstream<<"Could not read configuration from \""
945 <<cmd_args.get("config")<<"\""<<std::endl;
948 g_settings_path = cmd_args.get("config");
952 std::vector<std::string> filenames;
953 filenames.push_back(porting::path_user +
954 DIR_DELIM + "minetest.conf");
955 // Legacy configuration file location
956 filenames.push_back(porting::path_user +
957 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
959 // Try also from a lower level (to aid having the same configuration
960 // for many RUN_IN_PLACE installs)
961 filenames.push_back(porting::path_user +
962 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
965 for(u32 i=0; i<filenames.size(); i++)
967 bool r = g_settings->readConfigFile(filenames[i].c_str());
970 g_settings_path = filenames[i];
975 // If no path found, use the first one (menu creates the file)
976 if(g_settings_path == "")
977 g_settings_path = filenames[0];
980 // Initialize debug streams
981 #define DEBUGFILE "debug.txt"
983 std::string logfile = DEBUGFILE;
985 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
987 if(cmd_args.exists("logfile"))
988 logfile = cmd_args.get("logfile");
990 log_remove_output(&main_dstream_no_stderr_log_out);
991 int loglevel = g_settings->getS32("debug_log_level");
993 if (loglevel == 0) //no logging
995 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
996 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
999 debugstreams_init(false, logfile.c_str());
1001 debugstreams_init(false, NULL);
1003 infostream<<"logfile = "<<logfile<<std::endl;
1005 // Initialize random seed
1009 // Initialize HTTP fetcher
1010 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1016 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1017 || cmd_args.getFlag("enable-unittests") == true)
1022 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"),argc,argv);
1024 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"));
1033 if(cmd_args.exists("port"))
1034 port = cmd_args.getU16("port");
1035 else if(g_settings->exists("port"))
1036 port = g_settings->getU16("port");
1041 std::string commanded_world = "";
1042 if(cmd_args.exists("world"))
1043 commanded_world = cmd_args.get("world");
1044 else if(cmd_args.exists("map-dir"))
1045 commanded_world = cmd_args.get("map-dir");
1046 else if(cmd_args.exists("nonopt0")) // First nameless argument
1047 commanded_world = cmd_args.get("nonopt0");
1048 else if(g_settings->exists("map-dir"))
1049 commanded_world = g_settings->get("map-dir");
1052 std::string commanded_worldname = "";
1053 if(cmd_args.exists("worldname"))
1054 commanded_worldname = cmd_args.get("worldname");
1056 // Strip world.mt from commanded_world
1058 std::string worldmt = "world.mt";
1059 if(commanded_world.size() > worldmt.size() &&
1060 commanded_world.substr(commanded_world.size()-worldmt.size())
1062 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1063 commanded_world = commanded_world.substr(
1064 0, commanded_world.size()-worldmt.size());
1068 // If a world name was specified, convert it to a path
1069 if(commanded_worldname != ""){
1070 // Get information about available worlds
1071 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1073 for(u32 i=0; i<worldspecs.size(); i++){
1074 std::string name = worldspecs[i].name;
1075 if(name == commanded_worldname){
1076 if(commanded_world != ""){
1077 dstream<<_("--worldname takes precedence over previously "
1078 "selected world.")<<std::endl;
1080 commanded_world = worldspecs[i].path;
1086 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1087 "available. Available worlds:")<<std::endl;
1088 print_worldspecs(worldspecs, dstream);
1094 SubgameSpec commanded_gamespec;
1095 if(cmd_args.exists("gameid")){
1096 std::string gameid = cmd_args.get("gameid");
1097 commanded_gamespec = findSubgame(gameid);
1098 if(!commanded_gamespec.isValid()){
1099 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1106 Run dedicated server if asked to or no other option
1109 bool run_dedicated_server = true;
1111 bool run_dedicated_server = cmd_args.getFlag("server");
1113 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1114 if(run_dedicated_server)
1116 DSTACK("Dedicated server branch");
1117 // Create time getter if built with Irrlicht
1119 g_timegetter = new SimpleTimeGetter();
1123 std::string world_path;
1124 verbosestream<<_("Determining world path")<<std::endl;
1125 bool is_legacy_world = false;
1126 // If a world was commanded, use it
1127 if(commanded_world != ""){
1128 world_path = commanded_world;
1129 infostream<<"Using commanded world path ["<<world_path<<"]"
1132 // No world was specified; try to select it automatically
1135 // Get information about available worlds
1136 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1137 // If a world name was specified, select it
1138 if(commanded_worldname != ""){
1140 for(u32 i=0; i<worldspecs.size(); i++){
1141 std::string name = worldspecs[i].name;
1142 if(name == commanded_worldname){
1143 world_path = worldspecs[i].path;
1147 if(world_path == ""){
1148 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1149 "available. Available worlds:")<<std::endl;
1150 print_worldspecs(worldspecs, dstream);
1154 // If there is only a single world, use it
1155 if(worldspecs.size() == 1){
1156 world_path = worldspecs[0].path;
1157 dstream<<_("Automatically selecting world at")<<" ["
1158 <<world_path<<"]"<<std::endl;
1159 // If there are multiple worlds, list them
1160 } else if(worldspecs.size() > 1){
1161 dstream<<_("Multiple worlds are available.")<<std::endl;
1162 dstream<<_("Please select one using --worldname <name>"
1163 " or --world <path>")<<std::endl;
1164 print_worldspecs(worldspecs, dstream);
1166 // If there are no worlds, automatically create a new one
1168 // This is the ultimate default world path
1169 world_path = porting::path_user + DIR_DELIM + "worlds" +
1170 DIR_DELIM + "world";
1171 infostream<<"Creating default world at ["
1172 <<world_path<<"]"<<std::endl;
1176 if(world_path == ""){
1177 errorstream<<"No world path specified or found."<<std::endl;
1180 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1182 // We need a gamespec.
1183 SubgameSpec gamespec;
1184 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1185 // If world doesn't exist
1186 if(!getWorldExists(world_path))
1188 // Try to take gamespec from command line
1189 if(commanded_gamespec.isValid()){
1190 gamespec = commanded_gamespec;
1191 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1193 // Otherwise we will be using "minetest"
1195 gamespec = findSubgame(g_settings->get("default_game"));
1196 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1202 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1203 // If commanded to use a gameid, do so
1204 if(commanded_gamespec.isValid()){
1205 gamespec = commanded_gamespec;
1206 if(commanded_gamespec.id != world_gameid){
1207 errorstream<<"WARNING: Using commanded gameid ["
1208 <<gamespec.id<<"]"<<" instead of world gameid ["
1209 <<world_gameid<<"]"<<std::endl;
1212 // If world contains an embedded game, use it;
1213 // Otherwise find world from local system.
1214 gamespec = findWorldSubgame(world_path);
1215 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1218 if(!gamespec.isValid()){
1219 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1223 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1226 std::string bind_str = g_settings->get("bind_address");
1227 Address bind_addr(0,0,0,0, port);
1229 if (g_settings->getBool("ipv6_server")) {
1230 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1233 bind_addr.Resolve(bind_str.c_str());
1234 } catch (ResolveError &e) {
1235 infostream << "Resolving bind address \"" << bind_str
1236 << "\" failed: " << e.what()
1237 << " -- Listening on all addresses." << std::endl;
1239 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1240 errorstream << "Unable to listen on "
1241 << bind_addr.serializeString()
1242 << L" because IPv6 is disabled" << std::endl;
1247 Server server(world_path, gamespec, false, bind_addr.isIPv6());
1249 // Database migration
1250 if (cmd_args.exists("migrate")) {
1251 std::string migrate_to = cmd_args.get("migrate");
1253 bool success = world_mt.readConfigFile((world_path + DIR_DELIM + "world.mt").c_str());
1255 errorstream << "Cannot read world.mt" << std::endl;
1258 if (!world_mt.exists("backend")) {
1259 errorstream << "Please specify your current backend in world.mt file:"
1260 << std::endl << " backend = {sqlite3|leveldb|redis|dummy}" << std::endl;
1263 std::string backend = world_mt.get("backend");
1265 if (backend == migrate_to) {
1266 errorstream << "Cannot migrate: new backend is same as the old one" << std::endl;
1269 if (migrate_to == "sqlite3")
1270 new_db = new Database_SQLite3(&(ServerMap&)server.getMap(), world_path);
1272 else if (migrate_to == "leveldb")
1273 new_db = new Database_LevelDB(&(ServerMap&)server.getMap(), world_path);
1276 else if (migrate_to == "redis")
1277 new_db = new Database_Redis(&(ServerMap&)server.getMap(), world_path);
1280 errorstream << "Migration to " << migrate_to << " is not supported" << std::endl;
1284 std::list<v3s16> blocks;
1285 ServerMap &old_map = ((ServerMap&)server.getMap());
1286 old_map.listAllLoadableBlocks(blocks);
1288 new_db->beginSave();
1289 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); ++i) {
1290 MapBlock *block = old_map.loadBlock(*i);
1291 new_db->saveBlock(block);
1292 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1293 sector->deleteBlock(block);
1295 if (count % 500 == 0)
1296 actionstream << "Migrated " << count << " blocks "
1297 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1302 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1303 world_mt.set("backend", migrate_to);
1304 if(!world_mt.updateConfigFile((world_path + DIR_DELIM + "world.mt").c_str()))
1305 errorstream<<"Failed to update world.mt!"<<std::endl;
1307 actionstream<<"world.mt updated"<<std::endl;
1312 server.start(bind_addr);
1315 dedicated_server_loop(server, kill);
1320 #ifndef SERVER // Exclude from dedicated server build
1326 std::string address = g_settings->get("address");
1327 if(commanded_world != "")
1329 else if(cmd_args.exists("address"))
1330 address = cmd_args.get("address");
1332 std::string playername = g_settings->get("name");
1333 if(cmd_args.exists("name"))
1334 playername = cmd_args.get("name");
1336 bool skip_main_menu = cmd_args.getFlag("go");
1339 Device initialization
1342 // Resolution selection
1344 bool fullscreen = g_settings->getBool("fullscreen");
1345 u16 screenW = g_settings->getU16("screenW");
1346 u16 screenH = g_settings->getU16("screenH");
1350 bool vsync = g_settings->getBool("vsync");
1351 u16 bits = g_settings->getU16("fullscreen_bpp");
1352 u16 fsaa = g_settings->getU16("fsaa");
1356 video::E_DRIVER_TYPE driverType;
1358 std::string driverstring = g_settings->get("video_driver");
1360 if(driverstring == "null")
1361 driverType = video::EDT_NULL;
1362 else if(driverstring == "software")
1363 driverType = video::EDT_SOFTWARE;
1364 else if(driverstring == "burningsvideo")
1365 driverType = video::EDT_BURNINGSVIDEO;
1366 else if(driverstring == "direct3d8")
1367 driverType = video::EDT_DIRECT3D8;
1368 else if(driverstring == "direct3d9")
1369 driverType = video::EDT_DIRECT3D9;
1370 else if(driverstring == "opengl")
1371 driverType = video::EDT_OPENGL;
1372 #ifdef _IRR_COMPILE_WITH_OGLES1_
1373 else if(driverstring == "ogles1")
1374 driverType = video::EDT_OGLES1;
1376 #ifdef _IRR_COMPILE_WITH_OGLES2_
1377 else if(driverstring == "ogles2")
1378 driverType = video::EDT_OGLES2;
1382 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1383 "to opengl"<<std::endl;
1384 driverType = video::EDT_OPENGL;
1388 List video modes if requested
1391 MyEventReceiver receiver;
1393 if(cmd_args.getFlag("videomodes")){
1394 IrrlichtDevice *nulldevice;
1396 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1397 params.DriverType = video::EDT_NULL;
1398 params.WindowSize = core::dimension2d<u32>(640, 480);
1400 params.AntiAlias = fsaa;
1401 params.Fullscreen = false;
1402 params.Stencilbuffer = false;
1403 params.Vsync = vsync;
1404 params.EventReceiver = &receiver;
1405 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1407 nulldevice = createDeviceEx(params);
1412 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1414 video::IVideoModeList *videomode_list =
1415 nulldevice->getVideoModeList();
1417 if(videomode_list == 0){
1422 s32 videomode_count = videomode_list->getVideoModeCount();
1423 core::dimension2d<u32> videomode_res;
1424 s32 videomode_depth;
1425 for (s32 i = 0; i < videomode_count; ++i){
1426 videomode_res = videomode_list->getVideoModeResolution(i);
1427 videomode_depth = videomode_list->getVideoModeDepth(i);
1428 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1429 <<"x"<<videomode_depth<<std::endl;
1432 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1433 videomode_res = videomode_list->getDesktopResolution();
1434 videomode_depth = videomode_list->getDesktopDepth();
1435 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1436 <<"x"<<videomode_depth<<std::endl;
1444 Create device and exit if creation failed
1447 IrrlichtDevice *device;
1449 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1450 params.DriverType = driverType;
1451 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1453 params.AntiAlias = fsaa;
1454 params.Fullscreen = fullscreen;
1455 params.Stencilbuffer = false;
1456 params.Vsync = vsync;
1457 params.EventReceiver = &receiver;
1458 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1460 device = createDeviceEx(params);
1463 return 1; // could not create selected driver.
1466 // Map our log level to irrlicht engine one.
1467 static const irr::ELOG_LEVEL irr_log_level[5] = {
1472 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
1479 ILogger* irr_logger = device->getLogger();
1480 irr_logger->setLogLevel(irr_log_level[loglevel]);
1482 porting::initIrrlicht(device);
1485 Continue initialization
1488 video::IVideoDriver* driver = device->getVideoDriver();
1491 This changes the minimum allowed number of vertices in a VBO.
1494 //driver->setMinHardwareBufferVertexCount(50);
1496 // Create time getter
1497 g_timegetter = new IrrlichtTimeGetter(device);
1499 // Create game callback for menus
1500 g_gamecallback = new MainGameCallback(device);
1503 Speed tests (done after irrlicht is loaded to get timer)
1505 if(cmd_args.getFlag("speedtests"))
1507 dstream<<"Running speed tests"<<std::endl;
1513 device->setResizable(true);
1515 bool random_input = g_settings->getBool("random_input")
1516 || cmd_args.getFlag("random-input");
1517 InputHandler *input = NULL;
1519 input = new RandomInputHandler();
1521 input = new RealInputHandler(device, &receiver);
1524 scene::ISceneManager* smgr = device->getSceneManager();
1526 guienv = device->getGUIEnvironment();
1527 gui::IGUISkin* skin = guienv->getSkin();
1528 std::string font_path = g_settings->get("font_path");
1529 gui::IGUIFont *font;
1531 bool use_freetype = g_settings->getBool("freetype");
1533 std::string fallback;
1534 if (is_yes(gettext("needs_fallback_font")))
1535 fallback = "fallback_";
1536 u16 font_size = g_settings->getU16(fallback + "font_size");
1537 font_path = g_settings->get(fallback + "font_path");
1538 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1539 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1540 font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size, true, true, font_shadow, font_shadow_alpha);
1542 font = guienv->getFont(font_path.c_str());
1545 font = guienv->getFont(font_path.c_str());
1548 skin->setFont(font);
1550 errorstream<<"WARNING: Font file was not found."
1551 " Using default font."<<std::endl;
1552 // If font was not found, this will get us one
1553 font = skin->getFont();
1556 u32 text_height = font->getDimension(L"Hello, world!").Height;
1557 infostream<<"text_height="<<text_height<<std::endl;
1559 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1560 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1561 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1562 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1563 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1564 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1565 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1566 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1568 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1569 // Irrlicht 1.8 input colours
1570 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1571 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1575 // Create the menu clouds
1576 if (!g_menucloudsmgr)
1577 g_menucloudsmgr = smgr->createNewSceneManager();
1579 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1580 g_menucloudsmgr, -1, rand(), 100);
1581 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1582 scene::ICameraSceneNode* camera;
1583 camera = g_menucloudsmgr->addCameraSceneNode(0,
1584 v3f(0,0,0), v3f(0, 60, 100));
1585 camera->setFarValue(10000);
1591 ChatBackend chat_backend;
1594 If an error occurs, this is set to something and the
1595 menu-game loop is restarted. It is then displayed before
1598 std::wstring error_message = L"";
1600 // The password entered during the menu screen,
1601 std::string password;
1603 bool first_loop = true;
1608 while(device->run() && kill == false)
1610 // Set the window caption
1611 wchar_t* text = wgettext("Main Menu");
1612 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1615 // This is used for catching disconnects
1620 Clear everything from the GUIEnvironment
1625 We need some kind of a root node to be able to add
1626 custom gui elements directly on the screen.
1627 Otherwise they won't be automatically drawn.
1629 guiroot = guienv->addStaticText(L"",
1630 core::rect<s32>(0, 0, 10000, 10000));
1632 SubgameSpec gamespec;
1633 WorldSpec worldspec;
1634 bool simple_singleplayer_mode = false;
1636 // These are set up based on the menu and other things
1637 std::string current_playername = "inv£lid";
1638 std::string current_password = "";
1639 std::string current_address = "does-not-exist";
1640 int current_port = 0;
1643 Out-of-game menu loop.
1645 Loop quits when menu returns proper parameters.
1647 while(kill == false)
1649 // If skip_main_menu, only go through here once
1650 if(skip_main_menu && !first_loop){
1656 // Cursor can be non-visible when coming from the game
1657 device->getCursorControl()->setVisible(true);
1658 // Some stuff are left to scene manager when coming from the game
1662 // Initialize menu data
1663 MainMenuData menudata;
1664 menudata.address = address;
1665 menudata.name = playername;
1666 menudata.port = itos(port);
1667 menudata.errormessage = wide_to_narrow(error_message);
1668 error_message = L"";
1669 if(cmd_args.exists("password"))
1670 menudata.password = cmd_args.get("password");
1672 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1674 menudata.enable_public = g_settings->getBool("server_announce");
1676 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1678 // If a world was commanded, append and select it
1679 if(commanded_world != ""){
1681 std::string gameid = getWorldGameId(commanded_world, true);
1682 std::string name = _("[--world parameter]");
1684 gameid = g_settings->get("default_game");
1687 //TODO find within worldspecs and set config
1690 if(skip_main_menu == false)
1692 video::IVideoDriver* driver = device->getVideoDriver();
1694 infostream<<"Waiting for other menus"<<std::endl;
1695 while(device->run() && kill == false)
1699 driver->beginScene(true, true,
1700 video::SColor(255,128,128,128));
1703 // On some computers framerate doesn't seem to be
1704 // automatically limited
1707 infostream<<"Waited for other menus"<<std::endl;
1709 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata,kill);
1712 //once finished you'll never end up here
1716 if(menudata.errormessage != ""){
1717 error_message = narrow_to_wide(menudata.errormessage);
1721 //update worldspecs (necessary as new world may have been created)
1722 worldspecs = getAvailableWorlds();
1724 if (menudata.name == "")
1725 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1727 playername = menudata.name;
1729 password = translatePassword(playername, narrow_to_wide(menudata.password));
1730 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1732 address = menudata.address;
1733 int newport = stoi(menudata.port);
1737 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1740 g_settings->set("name", playername);
1742 if((menudata.selected_world >= 0) &&
1743 (menudata.selected_world < (int)worldspecs.size()))
1744 g_settings->set("selected_world_path",
1745 worldspecs[menudata.selected_world].path);
1747 // Break out of menu-game loop to shut down cleanly
1748 if(device->run() == false || kill == true)
1751 current_playername = playername;
1752 current_password = password;
1753 current_address = address;
1754 current_port = port;
1756 // If using simple singleplayer mode, override
1757 if(simple_singleplayer_mode){
1758 current_playername = "singleplayer";
1759 current_password = "";
1760 current_address = "";
1761 current_port = myrand_range(49152, 65535);
1763 else if (address != "")
1765 ServerListSpec server;
1766 server["name"] = menudata.servername;
1767 server["address"] = menudata.address;
1768 server["port"] = menudata.port;
1769 server["description"] = menudata.serverdescription;
1770 ServerList::insert(server);
1773 // Set world path to selected one
1774 if ((menudata.selected_world >= 0) &&
1775 (menudata.selected_world < (int)worldspecs.size())) {
1776 worldspec = worldspecs[menudata.selected_world];
1777 infostream<<"Selected world: "<<worldspec.name
1778 <<" ["<<worldspec.path<<"]"<<std::endl;
1782 if(current_address == "")
1784 if(menudata.selected_world == -1){
1785 error_message = wgettext("No world selected and no address "
1786 "provided. Nothing to do.");
1787 errorstream<<wide_to_narrow(error_message)<<std::endl;
1790 // Load gamespec for required game
1791 gamespec = findWorldSubgame(worldspec.path);
1792 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1793 error_message = wgettext("Could not find or load game \"")
1794 + narrow_to_wide(worldspec.gameid) + L"\"";
1795 errorstream<<wide_to_narrow(error_message)<<std::endl;
1798 if(commanded_gamespec.isValid() &&
1799 commanded_gamespec.id != worldspec.gameid){
1800 errorstream<<"WARNING: Overriding gamespec from \""
1801 <<worldspec.gameid<<"\" to \""
1802 <<commanded_gamespec.id<<"\""<<std::endl;
1803 gamespec = commanded_gamespec;
1806 if(!gamespec.isValid()){
1807 error_message = wgettext("Invalid gamespec.");
1808 error_message += L" (world_gameid="
1809 +narrow_to_wide(worldspec.gameid)+L")";
1810 errorstream<<wide_to_narrow(error_message)<<std::endl;
1819 // Break out of menu-game loop to shut down cleanly
1820 if(device->run() == false || kill == true) {
1821 if(g_settings_path != "") {
1822 g_settings->updateConfigFile(
1823 g_settings_path.c_str());
1845 simple_singleplayer_mode
1850 catch(con::PeerNotFoundException &e)
1852 error_message = wgettext("Connection error (timed out?)");
1853 errorstream<<wide_to_narrow(error_message)<<std::endl;
1856 catch(std::exception &e)
1858 std::string narrow_message = "Some exception: \"";
1859 narrow_message += e.what();
1860 narrow_message += "\"";
1861 errorstream<<narrow_message<<std::endl;
1862 error_message = narrow_to_wide(narrow_message);
1866 // If no main menu, show error and exit
1869 if(error_message != L""){
1870 verbosestream<<"error_message = "
1871 <<wide_to_narrow(error_message)<<std::endl;
1879 g_menuclouds->drop();
1880 g_menucloudsmgr->drop();
1885 In the end, delete the Irrlicht device.
1896 // Update configuration file
1897 if(g_settings_path != "")
1898 g_settings->updateConfigFile(g_settings_path.c_str());
1900 // Print modified quicktune values
1902 bool header_printed = false;
1903 std::vector<std::string> names = getQuicktuneNames();
1904 for(u32 i=0; i<names.size(); i++){
1905 QuicktuneValue val = getQuicktuneValue(names[i]);
1908 if(!header_printed){
1909 dstream<<"Modified quicktune values:"<<std::endl;
1910 header_printed = true;
1912 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1916 // Stop httpfetch thread (if started)
1917 httpfetch_cleanup();
1919 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1921 debugstreams_deinit();