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"
90 These are loaded from the config file.
92 Settings main_settings;
93 Settings *g_settings = &main_settings;
94 std::string g_settings_path;
97 Profiler main_profiler;
98 Profiler *g_profiler = &main_profiler;
100 // Menu clouds are created later
101 Clouds *g_menuclouds = 0;
102 irr::scene::ISceneManager *g_menucloudsmgr = 0;
109 std::ostream *dout_con_ptr = &dummyout;
110 std::ostream *derr_con_ptr = &verbosestream;
113 std::ostream *dout_server_ptr = &infostream;
114 std::ostream *derr_server_ptr = &errorstream;
117 std::ostream *dout_client_ptr = &infostream;
118 std::ostream *derr_client_ptr = &errorstream;
125 /* mainmenumanager.h */
127 gui::IGUIEnvironment* guienv = NULL;
128 gui::IGUIStaticText *guiroot = NULL;
129 MainMenuManager g_menumgr;
133 return (g_menumgr.menuCount() == 0);
136 // Passed to menus to allow disconnecting and exiting
137 MainGameCallback *g_gamecallback = NULL;
141 gettime.h implementation
148 /* Use imprecise system calls directly (from porting.h) */
149 return porting::getTime(PRECISION_MILLI);
152 u32 getTime(TimePrecision prec)
154 return porting::getTime(prec);
159 // A small helper class
163 virtual u32 getTime(TimePrecision prec) = 0;
166 // A precise irrlicht one
167 class IrrlichtTimeGetter: public TimeGetter
170 IrrlichtTimeGetter(IrrlichtDevice *device):
173 u32 getTime(TimePrecision prec)
175 if (prec == PRECISION_MILLI) {
178 return m_device->getTimer()->getRealTime();
180 return porting::getTime(prec);
184 IrrlichtDevice *m_device;
186 // Not so precise one which works without irrlicht
187 class SimpleTimeGetter: public TimeGetter
190 u32 getTime(TimePrecision prec)
192 return porting::getTime(prec);
196 // A pointer to a global instance of the time getter
198 TimeGetter *g_timegetter = NULL;
202 if(g_timegetter == NULL)
204 return g_timegetter->getTime(PRECISION_MILLI);
207 u32 getTime(TimePrecision prec) {
208 if (g_timegetter == NULL)
210 return g_timegetter->getTime(prec);
214 class StderrLogOutput: public ILogOutput
217 /* line: Full line with timestamp, level and thread */
218 void printLog(const std::string &line)
220 std::cerr<<line<<std::endl;
222 } main_stderr_log_out;
224 class DstreamNoStderrLogOutput: public ILogOutput
227 /* line: Full line with timestamp, level and thread */
228 void printLog(const std::string &line)
230 dstream_no_stderr<<line<<std::endl;
232 } main_dstream_no_stderr_log_out;
237 Event handler for Irrlicht
239 NOTE: Everything possible should be moved out from here,
240 probably to InputHandler and the_game
243 class MyEventReceiver : public IEventReceiver
246 // This is the one method that we have to implement
247 virtual bool OnEvent(const SEvent& event)
250 React to nothing here if a menu is active
252 if(noMenuActive() == false)
254 return g_menumgr.preprocessEvent(event);
257 // Remember whether each key is down or up
258 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
260 if(event.KeyInput.PressedDown) {
261 keyIsDown.set(event.KeyInput);
262 keyWasDown.set(event.KeyInput);
264 keyIsDown.unset(event.KeyInput);
268 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
270 if(noMenuActive() == false)
273 middle_active = false;
274 right_active = false;
278 left_active = event.MouseInput.isLeftPressed();
279 middle_active = event.MouseInput.isMiddlePressed();
280 right_active = event.MouseInput.isRightPressed();
282 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
286 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
290 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
294 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
296 rightreleased = true;
298 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
300 mouse_wheel += event.MouseInput.Wheel;
308 bool IsKeyDown(const KeyPress &keyCode) const
310 return keyIsDown[keyCode];
313 // Checks whether a key was down and resets the state
314 bool WasKeyDown(const KeyPress &keyCode)
316 bool b = keyWasDown[keyCode];
318 keyWasDown.unset(keyCode);
335 rightclicked = false;
336 leftreleased = false;
337 rightreleased = false;
340 middle_active = false;
341 right_active = false;
363 IrrlichtDevice *m_device;
365 // The current state of keys
367 // Whether a key has been pressed or not
372 Separated input handler
375 class RealInputHandler : public InputHandler
378 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
383 virtual bool isKeyDown(const KeyPress &keyCode)
385 return m_receiver->IsKeyDown(keyCode);
387 virtual bool wasKeyDown(const KeyPress &keyCode)
389 return m_receiver->WasKeyDown(keyCode);
391 virtual v2s32 getMousePos()
393 return m_device->getCursorControl()->getPosition();
395 virtual void setMousePos(s32 x, s32 y)
397 m_device->getCursorControl()->setPosition(x, y);
400 virtual bool getLeftState()
402 return m_receiver->left_active;
404 virtual bool getRightState()
406 return m_receiver->right_active;
409 virtual bool getLeftClicked()
411 return m_receiver->leftclicked;
413 virtual bool getRightClicked()
415 return m_receiver->rightclicked;
417 virtual void resetLeftClicked()
419 m_receiver->leftclicked = false;
421 virtual void resetRightClicked()
423 m_receiver->rightclicked = false;
426 virtual bool getLeftReleased()
428 return m_receiver->leftreleased;
430 virtual bool getRightReleased()
432 return m_receiver->rightreleased;
434 virtual void resetLeftReleased()
436 m_receiver->leftreleased = false;
438 virtual void resetRightReleased()
440 m_receiver->rightreleased = false;
443 virtual s32 getMouseWheel()
445 return m_receiver->getMouseWheel();
450 m_receiver->clearInput();
453 IrrlichtDevice *m_device;
454 MyEventReceiver *m_receiver;
457 class RandomInputHandler : public InputHandler
465 rightclicked = false;
466 leftreleased = false;
467 rightreleased = false;
470 virtual bool isKeyDown(const KeyPress &keyCode)
472 return keydown[keyCode];
474 virtual bool wasKeyDown(const KeyPress &keyCode)
478 virtual v2s32 getMousePos()
482 virtual void setMousePos(s32 x, s32 y)
484 mousepos = v2s32(x,y);
487 virtual bool getLeftState()
491 virtual bool getRightState()
496 virtual bool getLeftClicked()
500 virtual bool getRightClicked()
504 virtual void resetLeftClicked()
508 virtual void resetRightClicked()
510 rightclicked = false;
513 virtual bool getLeftReleased()
517 virtual bool getRightReleased()
519 return rightreleased;
521 virtual void resetLeftReleased()
523 leftreleased = false;
525 virtual void resetRightReleased()
527 rightreleased = false;
530 virtual s32 getMouseWheel()
535 virtual void step(float dtime)
538 static float counter1 = 0;
542 counter1 = 0.1*Rand(1, 40);
543 keydown.toggle(getKeySetting("keymap_jump"));
547 static float counter1 = 0;
551 counter1 = 0.1*Rand(1, 40);
552 keydown.toggle(getKeySetting("keymap_special1"));
556 static float counter1 = 0;
560 counter1 = 0.1*Rand(1, 40);
561 keydown.toggle(getKeySetting("keymap_forward"));
565 static float counter1 = 0;
569 counter1 = 0.1*Rand(1, 40);
570 keydown.toggle(getKeySetting("keymap_left"));
574 static float counter1 = 0;
578 counter1 = 0.1*Rand(1, 20);
579 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
583 static float counter1 = 0;
587 counter1 = 0.1*Rand(1, 30);
588 leftdown = !leftdown;
596 static float counter1 = 0;
600 counter1 = 0.1*Rand(1, 15);
601 rightdown = !rightdown;
605 rightreleased = true;
608 mousepos += mousespeed;
611 s32 Rand(s32 min, s32 max)
613 return (myrand()%(max-min+1))+min;
629 // These are defined global so that they're not optimized too much.
630 // Can't change them to volatile.
635 std::string tempstring;
636 std::string tempstring2;
641 infostream<<"The following test should take around 20ms."<<std::endl;
642 TimeTaker timer("Testing std::string speed");
643 const u32 jj = 10000;
644 for(u32 j=0; j<jj; j++)
649 for(u32 i=0; i<ii; i++){
650 tempstring2 += "asd";
652 for(u32 i=0; i<ii+1; i++){
654 if(tempstring == tempstring2)
660 infostream<<"All of the following tests should take around 100ms each."
664 TimeTaker timer("Testing floating-point conversion speed");
666 for(u32 i=0; i<4000000; i++){
673 TimeTaker timer("Testing floating-point vector speed");
675 tempv3f1 = v3f(1,2,3);
676 tempv3f2 = v3f(4,5,6);
677 for(u32 i=0; i<10000000; i++){
678 tempf += tempv3f1.dotProduct(tempv3f2);
679 tempv3f2 += v3f(7,8,9);
684 TimeTaker timer("Testing std::map speed");
686 std::map<v2s16, f32> map1;
689 for(s16 y=0; y<ii; y++){
690 for(s16 x=0; x<ii; x++){
691 map1[v2s16(x,y)] = tempf;
695 for(s16 y=ii-1; y>=0; y--){
696 for(s16 x=0; x<ii; x++){
697 tempf = map1[v2s16(x,y)];
703 infostream<<"Around 5000/ms should do well here."<<std::endl;
704 TimeTaker timer("Testing mutex speed");
717 while(timer.getTimerTime() < 10);
719 u32 dtime = timer.stop();
720 u32 per_ms = n / dtime;
721 infostream<<"Done. "<<dtime<<"ms, "
722 <<per_ms<<"/ms"<<std::endl;
726 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
729 for(u32 i=0; i<worldspecs.size(); i++){
730 std::string name = worldspecs[i].name;
731 std::string path = worldspecs[i].path;
732 if(name.find(" ") != std::string::npos)
733 name = std::string("'") + name + "'";
734 path = std::string("'") + path + "'";
735 name = padStringRight(name, 14);
736 os<<" "<<name<<" "<<path<<std::endl;
740 int main(int argc, char *argv[])
748 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
749 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
751 log_register_thread("main");
756 // List all allowed options
757 std::map<std::string, ValueSpec> allowed_options;
758 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
759 _("Show allowed options"))));
760 allowed_options.insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
761 _("Show version information"))));
762 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
763 _("Load configuration from specified file"))));
764 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
765 _("Set network port (UDP)"))));
766 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
767 _("Disable unit tests"))));
768 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
769 _("Enable unit tests"))));
770 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
771 _("Same as --world (deprecated)"))));
772 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
773 _("Set world path (implies local game) ('list' lists all)"))));
774 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
775 _("Set world by name (implies local game)"))));
776 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
777 _("Print more information to console"))));
778 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
779 _("Print even more information to console"))));
780 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
781 _("Print enormous amounts of information to log and console"))));
782 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
783 _("Set logfile path ('' = no logging)"))));
784 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
785 _("Set gameid (\"--gameid list\" prints available ones)"))));
786 allowed_options.insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
787 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
789 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
790 _("Show available video modes"))));
791 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
792 _("Run speed tests"))));
793 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
794 _("Address to connect to. ('' = local game)"))));
795 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
796 _("Enable random user input, for testing"))));
797 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
798 _("Run dedicated server"))));
799 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
800 _("Set player name"))));
801 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
802 _("Set password"))));
803 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
804 _("Disable main menu"))));
809 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
811 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
813 dstream<<_("Allowed options:")<<std::endl;
814 for(std::map<std::string, ValueSpec>::iterator
815 i = allowed_options.begin();
816 i != allowed_options.end(); ++i)
818 std::ostringstream os1(std::ios::binary);
819 os1<<" --"<<i->first;
820 if(i->second.type == VALUETYPE_FLAG)
824 dstream<<padStringRight(os1.str(), 24);
826 if(i->second.help != NULL)
827 dstream<<i->second.help;
831 return cmd_args.getFlag("help") ? 0 : 1;
834 if(cmd_args.getFlag("version"))
837 dstream<<"minetestserver "<<minetest_version_hash<<std::endl;
839 dstream<<"Minetest "<<minetest_version_hash<<std::endl;
840 dstream<<"Using Irrlicht "<<IRRLICHT_SDK_VERSION<<std::endl;
842 dstream<<"Build info: "<<minetest_build_info<<std::endl;
847 Low-level initialization
850 // If trace is enabled, enable logging of certain things
851 if(cmd_args.getFlag("trace")){
852 dstream<<_("Enabling trace level debug output")<<std::endl;
853 log_trace_level_enabled = true;
854 dout_con_ptr = &verbosestream; // this is somewhat old crap
855 socket_enable_debug_output = true; // socket doesn't use log.h
857 // In certain cases, output info level on stderr
858 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
859 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
860 log_add_output(&main_stderr_log_out, LMT_INFO);
861 // In certain cases, output verbose level on stderr
862 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
863 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
865 porting::signal_handler_init();
866 bool &kill = *porting::signal_handler_killstatus();
868 porting::initializePaths();
870 // Create user data directory
871 fs::CreateDir(porting::path_user);
873 infostream<<"path_share = "<<porting::path_share<<std::endl;
874 infostream<<"path_user = "<<porting::path_user<<std::endl;
876 // Initialize debug stacks
878 DSTACK(__FUNCTION_NAME);
881 BEGIN_DEBUG_EXCEPTION_HANDLER
883 // List gameids if requested
884 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
886 std::set<std::string> gameids = getAvailableGameIds();
887 for(std::set<std::string>::const_iterator i = gameids.begin();
888 i != gameids.end(); i++)
889 dstream<<(*i)<<std::endl;
893 // List worlds if requested
894 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
895 dstream<<_("Available worlds:")<<std::endl;
896 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
897 print_worldspecs(worldspecs, dstream);
901 // Print startup message
902 infostream<<PROJECT_NAME<<
903 " "<<_("with")<<" SER_FMT_VER_HIGHEST_READ="<<(int)SER_FMT_VER_HIGHEST_READ
904 <<", "<<minetest_build_info
911 // Initialize default settings
912 set_default_settings(g_settings);
914 // Initialize sockets
916 atexit(sockets_cleanup);
922 // Path of configuration file in use
923 g_settings_path = "";
925 if(cmd_args.exists("config"))
927 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
930 errorstream<<"Could not read configuration from \""
931 <<cmd_args.get("config")<<"\""<<std::endl;
934 g_settings_path = cmd_args.get("config");
938 std::vector<std::string> filenames;
939 filenames.push_back(porting::path_user +
940 DIR_DELIM + "minetest.conf");
941 // Legacy configuration file location
942 filenames.push_back(porting::path_user +
943 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
945 // Try also from a lower level (to aid having the same configuration
946 // for many RUN_IN_PLACE installs)
947 filenames.push_back(porting::path_user +
948 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
951 for(u32 i=0; i<filenames.size(); i++)
953 bool r = g_settings->readConfigFile(filenames[i].c_str());
956 g_settings_path = filenames[i];
961 // If no path found, use the first one (menu creates the file)
962 if(g_settings_path == "")
963 g_settings_path = filenames[0];
966 // Initialize debug streams
967 #define DEBUGFILE "debug.txt"
969 std::string logfile = DEBUGFILE;
971 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
973 if(cmd_args.exists("logfile"))
974 logfile = cmd_args.get("logfile");
976 log_remove_output(&main_dstream_no_stderr_log_out);
977 int loglevel = g_settings->getS32("debug_log_level");
979 if (loglevel == 0) //no logging
981 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
982 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
985 debugstreams_init(false, logfile.c_str());
987 debugstreams_init(false, NULL);
989 infostream<<"logfile = "<<logfile<<std::endl;
991 // Initialize random seed
995 // Initialize HTTP fetcher
996 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1002 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1003 || cmd_args.getFlag("enable-unittests") == true)
1008 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"),argc,argv);
1010 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"));
1019 if(cmd_args.exists("port"))
1020 port = cmd_args.getU16("port");
1021 else if(g_settings->exists("port"))
1022 port = g_settings->getU16("port");
1027 std::string bind_str = g_settings->get("bind_address");
1028 Address bind_addr(0,0,0,0, port);
1030 bind_addr.Resolve(bind_str.c_str());
1031 } catch (ResolveError &e) {
1032 infostream << "Resolving bind address \"" << bind_str
1033 << "\" failed: " << e.what()
1034 << " -- Listening on all addresses." << std::endl;
1036 if (g_settings->getBool("ipv6_server")) {
1037 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1042 std::string commanded_world = "";
1043 if(cmd_args.exists("world"))
1044 commanded_world = cmd_args.get("world");
1045 else if(cmd_args.exists("map-dir"))
1046 commanded_world = cmd_args.get("map-dir");
1047 else if(cmd_args.exists("nonopt0")) // First nameless argument
1048 commanded_world = cmd_args.get("nonopt0");
1049 else if(g_settings->exists("map-dir"))
1050 commanded_world = g_settings->get("map-dir");
1053 std::string commanded_worldname = "";
1054 if(cmd_args.exists("worldname"))
1055 commanded_worldname = cmd_args.get("worldname");
1057 // Strip world.mt from commanded_world
1059 std::string worldmt = "world.mt";
1060 if(commanded_world.size() > worldmt.size() &&
1061 commanded_world.substr(commanded_world.size()-worldmt.size())
1063 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1064 commanded_world = commanded_world.substr(
1065 0, commanded_world.size()-worldmt.size());
1069 // If a world name was specified, convert it to a path
1070 if(commanded_worldname != ""){
1071 // Get information about available worlds
1072 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1074 for(u32 i=0; i<worldspecs.size(); i++){
1075 std::string name = worldspecs[i].name;
1076 if(name == commanded_worldname){
1077 if(commanded_world != ""){
1078 dstream<<_("--worldname takes precedence over previously "
1079 "selected world.")<<std::endl;
1081 commanded_world = worldspecs[i].path;
1087 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1088 "available. Available worlds:")<<std::endl;
1089 print_worldspecs(worldspecs, dstream);
1095 SubgameSpec commanded_gamespec;
1096 if(cmd_args.exists("gameid")){
1097 std::string gameid = cmd_args.get("gameid");
1098 commanded_gamespec = findSubgame(gameid);
1099 if(!commanded_gamespec.isValid()){
1100 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1107 Run dedicated server if asked to or no other option
1110 bool run_dedicated_server = true;
1112 bool run_dedicated_server = cmd_args.getFlag("server");
1114 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1115 if(run_dedicated_server)
1117 DSTACK("Dedicated server branch");
1118 // Create time getter if built with Irrlicht
1120 g_timegetter = new SimpleTimeGetter();
1124 std::string world_path;
1125 verbosestream<<_("Determining world path")<<std::endl;
1126 bool is_legacy_world = false;
1127 // If a world was commanded, use it
1128 if(commanded_world != ""){
1129 world_path = commanded_world;
1130 infostream<<"Using commanded world path ["<<world_path<<"]"
1133 // No world was specified; try to select it automatically
1136 // Get information about available worlds
1137 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1138 // If a world name was specified, select it
1139 if(commanded_worldname != ""){
1141 for(u32 i=0; i<worldspecs.size(); i++){
1142 std::string name = worldspecs[i].name;
1143 if(name == commanded_worldname){
1144 world_path = worldspecs[i].path;
1148 if(world_path == ""){
1149 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1150 "available. Available worlds:")<<std::endl;
1151 print_worldspecs(worldspecs, dstream);
1155 // If there is only a single world, use it
1156 if(worldspecs.size() == 1){
1157 world_path = worldspecs[0].path;
1158 dstream<<_("Automatically selecting world at")<<" ["
1159 <<world_path<<"]"<<std::endl;
1160 // If there are multiple worlds, list them
1161 } else if(worldspecs.size() > 1){
1162 dstream<<_("Multiple worlds are available.")<<std::endl;
1163 dstream<<_("Please select one using --worldname <name>"
1164 " or --world <path>")<<std::endl;
1165 print_worldspecs(worldspecs, dstream);
1167 // If there are no worlds, automatically create a new one
1169 // This is the ultimate default world path
1170 world_path = porting::path_user + DIR_DELIM + "worlds" +
1171 DIR_DELIM + "world";
1172 infostream<<"Creating default world at ["
1173 <<world_path<<"]"<<std::endl;
1177 if(world_path == ""){
1178 errorstream<<"No world path specified or found."<<std::endl;
1181 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1183 // We need a gamespec.
1184 SubgameSpec gamespec;
1185 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1186 // If world doesn't exist
1187 if(!getWorldExists(world_path))
1189 // Try to take gamespec from command line
1190 if(commanded_gamespec.isValid()){
1191 gamespec = commanded_gamespec;
1192 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1194 // Otherwise we will be using "minetest"
1196 gamespec = findSubgame(g_settings->get("default_game"));
1197 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1203 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1204 // If commanded to use a gameid, do so
1205 if(commanded_gamespec.isValid()){
1206 gamespec = commanded_gamespec;
1207 if(commanded_gamespec.id != world_gameid){
1208 errorstream<<"WARNING: Using commanded gameid ["
1209 <<gamespec.id<<"]"<<" instead of world gameid ["
1210 <<world_gameid<<"]"<<std::endl;
1213 // If world contains an embedded game, use it;
1214 // Otherwise find world from local system.
1215 gamespec = findWorldSubgame(world_path);
1216 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1219 if(!gamespec.isValid()){
1220 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1224 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1227 Server server(world_path, gamespec, false);
1229 // Database migration
1230 if (cmd_args.exists("migrate")) {
1231 std::string migrate_to = cmd_args.get("migrate");
1233 bool success = world_mt.readConfigFile((world_path + DIR_DELIM + "world.mt").c_str());
1235 errorstream << "Cannot read world.mt" << std::endl;
1238 if (!world_mt.exists("backend")) {
1239 errorstream << "Please specify your current backend in world.mt file:"
1240 << std::endl << " backend = {sqlite3|leveldb|dummy}" << std::endl;
1243 std::string backend = world_mt.get("backend");
1245 if (backend == migrate_to) {
1246 errorstream << "Cannot migrate: new backend is same as the old one" << std::endl;
1249 if (migrate_to == "sqlite3")
1250 new_db = new Database_SQLite3(&(ServerMap&)server.getMap(), world_path);
1252 else if (migrate_to == "leveldb")
1253 new_db = new Database_LevelDB(&(ServerMap&)server.getMap(), world_path);
1256 errorstream << "Migration to " << migrate_to << " is not supported" << std::endl;
1260 std::list<v3s16> blocks;
1261 ServerMap &old_map = ((ServerMap&)server.getMap());
1262 old_map.listAllLoadableBlocks(blocks);
1264 new_db->beginSave();
1265 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); ++i) {
1266 MapBlock *block = old_map.loadBlock(*i);
1267 new_db->saveBlock(block);
1268 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1269 sector->deleteBlock(block);
1271 if (count % 500 == 0)
1272 actionstream << "Migrated " << count << " blocks "
1273 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1278 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1279 world_mt.set("backend", migrate_to);
1280 if(!world_mt.updateConfigFile((world_path + DIR_DELIM + "world.mt").c_str()))
1281 errorstream<<"Failed to update world.mt!"<<std::endl;
1283 actionstream<<"world.mt updated"<<std::endl;
1288 server.start(bind_addr);
1291 dedicated_server_loop(server, kill);
1296 #ifndef SERVER // Exclude from dedicated server build
1302 std::string address = g_settings->get("address");
1303 if(commanded_world != "")
1305 else if(cmd_args.exists("address"))
1306 address = cmd_args.get("address");
1308 std::string playername = g_settings->get("name");
1309 if(cmd_args.exists("name"))
1310 playername = cmd_args.get("name");
1312 bool skip_main_menu = cmd_args.getFlag("go");
1315 Device initialization
1318 // Resolution selection
1320 bool fullscreen = g_settings->getBool("fullscreen");
1321 u16 screenW = g_settings->getU16("screenW");
1322 u16 screenH = g_settings->getU16("screenH");
1326 bool vsync = g_settings->getBool("vsync");
1327 u16 bits = g_settings->getU16("fullscreen_bpp");
1328 u16 fsaa = g_settings->getU16("fsaa");
1332 video::E_DRIVER_TYPE driverType;
1334 std::string driverstring = g_settings->get("video_driver");
1336 if(driverstring == "null")
1337 driverType = video::EDT_NULL;
1338 else if(driverstring == "software")
1339 driverType = video::EDT_SOFTWARE;
1340 else if(driverstring == "burningsvideo")
1341 driverType = video::EDT_BURNINGSVIDEO;
1342 else if(driverstring == "direct3d8")
1343 driverType = video::EDT_DIRECT3D8;
1344 else if(driverstring == "direct3d9")
1345 driverType = video::EDT_DIRECT3D9;
1346 else if(driverstring == "opengl")
1347 driverType = video::EDT_OPENGL;
1348 #ifdef _IRR_COMPILE_WITH_OGLES1_
1349 else if(driverstring == "ogles1")
1350 driverType = video::EDT_OGLES1;
1352 #ifdef _IRR_COMPILE_WITH_OGLES2_
1353 else if(driverstring == "ogles2")
1354 driverType = video::EDT_OGLES2;
1358 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1359 "to opengl"<<std::endl;
1360 driverType = video::EDT_OPENGL;
1364 List video modes if requested
1367 MyEventReceiver receiver;
1369 if(cmd_args.getFlag("videomodes")){
1370 IrrlichtDevice *nulldevice;
1372 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1373 params.DriverType = video::EDT_NULL;
1374 params.WindowSize = core::dimension2d<u32>(640, 480);
1376 params.AntiAlias = fsaa;
1377 params.Fullscreen = false;
1378 params.Stencilbuffer = false;
1379 params.Vsync = vsync;
1380 params.EventReceiver = &receiver;
1381 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1383 nulldevice = createDeviceEx(params);
1388 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1390 video::IVideoModeList *videomode_list =
1391 nulldevice->getVideoModeList();
1393 if(videomode_list == 0){
1398 s32 videomode_count = videomode_list->getVideoModeCount();
1399 core::dimension2d<u32> videomode_res;
1400 s32 videomode_depth;
1401 for (s32 i = 0; i < videomode_count; ++i){
1402 videomode_res = videomode_list->getVideoModeResolution(i);
1403 videomode_depth = videomode_list->getVideoModeDepth(i);
1404 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1405 <<"x"<<videomode_depth<<std::endl;
1408 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1409 videomode_res = videomode_list->getDesktopResolution();
1410 videomode_depth = videomode_list->getDesktopDepth();
1411 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1412 <<"x"<<videomode_depth<<std::endl;
1420 Create device and exit if creation failed
1423 IrrlichtDevice *device;
1425 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1426 params.DriverType = driverType;
1427 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1429 params.AntiAlias = fsaa;
1430 params.Fullscreen = fullscreen;
1431 params.Stencilbuffer = false;
1432 params.Vsync = vsync;
1433 params.EventReceiver = &receiver;
1434 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1436 device = createDeviceEx(params);
1439 return 1; // could not create selected driver.
1442 Continue initialization
1445 video::IVideoDriver* driver = device->getVideoDriver();
1448 This changes the minimum allowed number of vertices in a VBO.
1451 //driver->setMinHardwareBufferVertexCount(50);
1453 // Create time getter
1454 g_timegetter = new IrrlichtTimeGetter(device);
1456 // Create game callback for menus
1457 g_gamecallback = new MainGameCallback(device);
1460 Speed tests (done after irrlicht is loaded to get timer)
1462 if(cmd_args.getFlag("speedtests"))
1464 dstream<<"Running speed tests"<<std::endl;
1470 device->setResizable(true);
1472 bool random_input = g_settings->getBool("random_input")
1473 || cmd_args.getFlag("random-input");
1474 InputHandler *input = NULL;
1476 input = new RandomInputHandler();
1478 input = new RealInputHandler(device, &receiver);
1480 scene::ISceneManager* smgr = device->getSceneManager();
1482 guienv = device->getGUIEnvironment();
1483 gui::IGUISkin* skin = guienv->getSkin();
1484 std::string font_path = g_settings->get("font_path");
1485 gui::IGUIFont *font;
1487 bool use_freetype = g_settings->getBool("freetype");
1489 std::string fallback;
1490 if (is_yes(gettext("needs_fallback_font")))
1491 fallback = "fallback_";
1492 u16 font_size = g_settings->getU16(fallback + "font_size");
1493 font_path = g_settings->get(fallback + "font_path");
1494 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1495 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1496 font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size, true, true, font_shadow, font_shadow_alpha);
1498 font = guienv->getFont(font_path.c_str());
1501 font = guienv->getFont(font_path.c_str());
1504 skin->setFont(font);
1506 errorstream<<"WARNING: Font file was not found."
1507 " Using default font."<<std::endl;
1508 // If font was not found, this will get us one
1509 font = skin->getFont();
1512 u32 text_height = font->getDimension(L"Hello, world!").Height;
1513 infostream<<"text_height="<<text_height<<std::endl;
1515 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1516 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1517 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1518 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1519 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1520 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1521 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1522 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1524 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1525 // Irrlicht 1.8 input colours
1526 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1527 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1531 // Create the menu clouds
1532 if (!g_menucloudsmgr)
1533 g_menucloudsmgr = smgr->createNewSceneManager();
1535 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1536 g_menucloudsmgr, -1, rand(), 100);
1537 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1538 scene::ICameraSceneNode* camera;
1539 camera = g_menucloudsmgr->addCameraSceneNode(0,
1540 v3f(0,0,0), v3f(0, 60, 100));
1541 camera->setFarValue(10000);
1547 ChatBackend chat_backend;
1550 If an error occurs, this is set to something and the
1551 menu-game loop is restarted. It is then displayed before
1554 std::wstring error_message = L"";
1556 // The password entered during the menu screen,
1557 std::string password;
1559 bool first_loop = true;
1564 while(device->run() && kill == false)
1566 // Set the window caption
1567 wchar_t* text = wgettext("Main Menu");
1568 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1571 // This is used for catching disconnects
1576 Clear everything from the GUIEnvironment
1581 We need some kind of a root node to be able to add
1582 custom gui elements directly on the screen.
1583 Otherwise they won't be automatically drawn.
1585 guiroot = guienv->addStaticText(L"",
1586 core::rect<s32>(0, 0, 10000, 10000));
1588 SubgameSpec gamespec;
1589 WorldSpec worldspec;
1590 bool simple_singleplayer_mode = false;
1592 // These are set up based on the menu and other things
1593 std::string current_playername = "inv£lid";
1594 std::string current_password = "";
1595 std::string current_address = "does-not-exist";
1596 int current_port = 0;
1599 Out-of-game menu loop.
1601 Loop quits when menu returns proper parameters.
1603 while(kill == false)
1605 // If skip_main_menu, only go through here once
1606 if(skip_main_menu && !first_loop){
1612 // Cursor can be non-visible when coming from the game
1613 device->getCursorControl()->setVisible(true);
1614 // Some stuff are left to scene manager when coming from the game
1618 // Initialize menu data
1619 MainMenuData menudata;
1620 menudata.address = address;
1621 menudata.name = playername;
1622 menudata.port = itos(port);
1623 menudata.errormessage = wide_to_narrow(error_message);
1624 error_message = L"";
1625 if(cmd_args.exists("password"))
1626 menudata.password = cmd_args.get("password");
1628 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1630 menudata.enable_public = g_settings->getBool("server_announce");
1632 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1634 // If a world was commanded, append and select it
1635 if(commanded_world != ""){
1637 std::string gameid = getWorldGameId(commanded_world, true);
1638 std::string name = _("[--world parameter]");
1640 gameid = g_settings->get("default_game");
1643 //TODO find within worldspecs and set config
1646 if(skip_main_menu == false)
1648 video::IVideoDriver* driver = device->getVideoDriver();
1650 infostream<<"Waiting for other menus"<<std::endl;
1651 while(device->run() && kill == false)
1655 driver->beginScene(true, true,
1656 video::SColor(255,128,128,128));
1659 // On some computers framerate doesn't seem to be
1660 // automatically limited
1663 infostream<<"Waited for other menus"<<std::endl;
1665 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata,kill);
1668 //once finished you'll never end up here
1672 if(menudata.errormessage != ""){
1673 error_message = narrow_to_wide(menudata.errormessage);
1677 //update worldspecs (necessary as new world may have been created)
1678 worldspecs = getAvailableWorlds();
1680 if (menudata.name == "")
1681 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1683 playername = menudata.name;
1685 password = translatePassword(playername, narrow_to_wide(menudata.password));
1686 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1688 address = menudata.address;
1689 int newport = stoi(menudata.port);
1693 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1696 g_settings->set("name", playername);
1698 if((menudata.selected_world >= 0) &&
1699 (menudata.selected_world < (int)worldspecs.size()))
1700 g_settings->set("selected_world_path",
1701 worldspecs[menudata.selected_world].path);
1703 // Break out of menu-game loop to shut down cleanly
1704 if(device->run() == false || kill == true)
1707 current_playername = playername;
1708 current_password = password;
1709 current_address = address;
1710 current_port = port;
1712 // If using simple singleplayer mode, override
1713 if(simple_singleplayer_mode){
1714 current_playername = "singleplayer";
1715 current_password = "";
1716 current_address = "";
1717 current_port = myrand_range(49152, 65535);
1719 else if (address != "")
1721 ServerListSpec server;
1722 server["name"] = menudata.servername;
1723 server["address"] = menudata.address;
1724 server["port"] = menudata.port;
1725 server["description"] = menudata.serverdescription;
1726 ServerList::insert(server);
1729 // Set world path to selected one
1730 if ((menudata.selected_world >= 0) &&
1731 (menudata.selected_world < (int)worldspecs.size())) {
1732 worldspec = worldspecs[menudata.selected_world];
1733 infostream<<"Selected world: "<<worldspec.name
1734 <<" ["<<worldspec.path<<"]"<<std::endl;
1738 if(current_address == "")
1740 if(menudata.selected_world == -1){
1741 error_message = wgettext("No world selected and no address "
1742 "provided. Nothing to do.");
1743 errorstream<<wide_to_narrow(error_message)<<std::endl;
1746 // Load gamespec for required game
1747 gamespec = findWorldSubgame(worldspec.path);
1748 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1749 error_message = wgettext("Could not find or load game \"")
1750 + narrow_to_wide(worldspec.gameid) + L"\"";
1751 errorstream<<wide_to_narrow(error_message)<<std::endl;
1754 if(commanded_gamespec.isValid() &&
1755 commanded_gamespec.id != worldspec.gameid){
1756 errorstream<<"WARNING: Overriding gamespec from \""
1757 <<worldspec.gameid<<"\" to \""
1758 <<commanded_gamespec.id<<"\""<<std::endl;
1759 gamespec = commanded_gamespec;
1762 if(!gamespec.isValid()){
1763 error_message = wgettext("Invalid gamespec.");
1764 error_message += L" (world_gameid="
1765 +narrow_to_wide(worldspec.gameid)+L")";
1766 errorstream<<wide_to_narrow(error_message)<<std::endl;
1775 // Break out of menu-game loop to shut down cleanly
1776 if(device->run() == false || kill == true) {
1777 if(g_settings_path != "") {
1778 g_settings->updateConfigFile(
1779 g_settings_path.c_str());
1801 simple_singleplayer_mode
1806 catch(con::PeerNotFoundException &e)
1808 error_message = wgettext("Connection error (timed out?)");
1809 errorstream<<wide_to_narrow(error_message)<<std::endl;
1812 catch(std::exception &e)
1814 std::string narrow_message = "Some exception: \"";
1815 narrow_message += e.what();
1816 narrow_message += "\"";
1817 errorstream<<narrow_message<<std::endl;
1818 error_message = narrow_to_wide(narrow_message);
1822 // If no main menu, show error and exit
1825 if(error_message != L""){
1826 verbosestream<<"error_message = "
1827 <<wide_to_narrow(error_message)<<std::endl;
1835 g_menuclouds->drop();
1836 g_menucloudsmgr->drop();
1841 In the end, delete the Irrlicht device.
1852 // Update configuration file
1853 if(g_settings_path != "")
1854 g_settings->updateConfigFile(g_settings_path.c_str());
1856 // Print modified quicktune values
1858 bool header_printed = false;
1859 std::vector<std::string> names = getQuicktuneNames();
1860 for(u32 i=0; i<names.size(); i++){
1861 QuicktuneValue val = getQuicktuneValue(names[i]);
1864 if(!header_printed){
1865 dstream<<"Modified quicktune values:"<<std::endl;
1866 header_printed = true;
1868 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1872 // Stop httpfetch thread (if started)
1873 httpfetch_cleanup();
1875 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1877 debugstreams_deinit();