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"
58 #include "guiMessageMenu.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 "guiEngine.h"
83 These are loaded from the config file.
85 Settings main_settings;
86 Settings *g_settings = &main_settings;
87 std::string g_settings_path;
90 Profiler main_profiler;
91 Profiler *g_profiler = &main_profiler;
93 // Menu clouds are created later
94 Clouds *g_menuclouds = 0;
95 irr::scene::ISceneManager *g_menucloudsmgr = 0;
102 std::ostream *dout_con_ptr = &dummyout;
103 std::ostream *derr_con_ptr = &verbosestream;
106 std::ostream *dout_server_ptr = &infostream;
107 std::ostream *derr_server_ptr = &errorstream;
110 std::ostream *dout_client_ptr = &infostream;
111 std::ostream *derr_client_ptr = &errorstream;
118 /* mainmenumanager.h */
120 gui::IGUIEnvironment* guienv = NULL;
121 gui::IGUIStaticText *guiroot = NULL;
122 MainMenuManager g_menumgr;
126 return (g_menumgr.menuCount() == 0);
129 // Passed to menus to allow disconnecting and exiting
130 MainGameCallback *g_gamecallback = NULL;
134 gettime.h implementation
141 /* Use imprecise system calls directly (from porting.h) */
142 return porting::getTime(PRECISION_MILLI);
145 u32 getTime(TimePrecision prec)
147 return porting::getTime(prec);
152 // A small helper class
156 virtual u32 getTime(TimePrecision prec) = 0;
159 // A precise irrlicht one
160 class IrrlichtTimeGetter: public TimeGetter
163 IrrlichtTimeGetter(IrrlichtDevice *device):
166 u32 getTime(TimePrecision prec)
168 if (prec == PRECISION_MILLI) {
171 return m_device->getTimer()->getRealTime();
173 return porting::getTime(prec);
177 IrrlichtDevice *m_device;
179 // Not so precise one which works without irrlicht
180 class SimpleTimeGetter: public TimeGetter
183 u32 getTime(TimePrecision prec)
185 return porting::getTime(prec);
189 // A pointer to a global instance of the time getter
191 TimeGetter *g_timegetter = NULL;
195 if(g_timegetter == NULL)
197 return g_timegetter->getTime(PRECISION_MILLI);
200 u32 getTime(TimePrecision prec) {
201 if (g_timegetter == NULL)
203 return g_timegetter->getTime(prec);
207 class StderrLogOutput: public ILogOutput
210 /* line: Full line with timestamp, level and thread */
211 void printLog(const std::string &line)
213 std::cerr<<line<<std::endl;
215 } main_stderr_log_out;
217 class DstreamNoStderrLogOutput: public ILogOutput
220 /* line: Full line with timestamp, level and thread */
221 void printLog(const std::string &line)
223 dstream_no_stderr<<line<<std::endl;
225 } main_dstream_no_stderr_log_out;
230 Event handler for Irrlicht
232 NOTE: Everything possible should be moved out from here,
233 probably to InputHandler and the_game
236 class MyEventReceiver : public IEventReceiver
239 // This is the one method that we have to implement
240 virtual bool OnEvent(const SEvent& event)
243 React to nothing here if a menu is active
245 if(noMenuActive() == false)
247 return g_menumgr.preprocessEvent(event);
250 // Remember whether each key is down or up
251 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
253 if(event.KeyInput.PressedDown) {
254 keyIsDown.set(event.KeyInput);
255 keyWasDown.set(event.KeyInput);
257 keyIsDown.unset(event.KeyInput);
261 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
263 if(noMenuActive() == false)
266 middle_active = false;
267 right_active = false;
271 left_active = event.MouseInput.isLeftPressed();
272 middle_active = event.MouseInput.isMiddlePressed();
273 right_active = event.MouseInput.isRightPressed();
275 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
279 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
283 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
287 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
289 rightreleased = true;
291 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
293 mouse_wheel += event.MouseInput.Wheel;
301 bool IsKeyDown(const KeyPress &keyCode) const
303 return keyIsDown[keyCode];
306 // Checks whether a key was down and resets the state
307 bool WasKeyDown(const KeyPress &keyCode)
309 bool b = keyWasDown[keyCode];
311 keyWasDown.unset(keyCode);
328 rightclicked = false;
329 leftreleased = false;
330 rightreleased = false;
333 middle_active = false;
334 right_active = false;
356 IrrlichtDevice *m_device;
358 // The current state of keys
360 // Whether a key has been pressed or not
365 Separated input handler
368 class RealInputHandler : public InputHandler
371 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
376 virtual bool isKeyDown(const KeyPress &keyCode)
378 return m_receiver->IsKeyDown(keyCode);
380 virtual bool wasKeyDown(const KeyPress &keyCode)
382 return m_receiver->WasKeyDown(keyCode);
384 virtual v2s32 getMousePos()
386 return m_device->getCursorControl()->getPosition();
388 virtual void setMousePos(s32 x, s32 y)
390 m_device->getCursorControl()->setPosition(x, y);
393 virtual bool getLeftState()
395 return m_receiver->left_active;
397 virtual bool getRightState()
399 return m_receiver->right_active;
402 virtual bool getLeftClicked()
404 return m_receiver->leftclicked;
406 virtual bool getRightClicked()
408 return m_receiver->rightclicked;
410 virtual void resetLeftClicked()
412 m_receiver->leftclicked = false;
414 virtual void resetRightClicked()
416 m_receiver->rightclicked = false;
419 virtual bool getLeftReleased()
421 return m_receiver->leftreleased;
423 virtual bool getRightReleased()
425 return m_receiver->rightreleased;
427 virtual void resetLeftReleased()
429 m_receiver->leftreleased = false;
431 virtual void resetRightReleased()
433 m_receiver->rightreleased = false;
436 virtual s32 getMouseWheel()
438 return m_receiver->getMouseWheel();
443 m_receiver->clearInput();
446 IrrlichtDevice *m_device;
447 MyEventReceiver *m_receiver;
450 class RandomInputHandler : public InputHandler
458 rightclicked = false;
459 leftreleased = false;
460 rightreleased = false;
463 virtual bool isKeyDown(const KeyPress &keyCode)
465 return keydown[keyCode];
467 virtual bool wasKeyDown(const KeyPress &keyCode)
471 virtual v2s32 getMousePos()
475 virtual void setMousePos(s32 x, s32 y)
477 mousepos = v2s32(x,y);
480 virtual bool getLeftState()
484 virtual bool getRightState()
489 virtual bool getLeftClicked()
493 virtual bool getRightClicked()
497 virtual void resetLeftClicked()
501 virtual void resetRightClicked()
503 rightclicked = false;
506 virtual bool getLeftReleased()
510 virtual bool getRightReleased()
512 return rightreleased;
514 virtual void resetLeftReleased()
516 leftreleased = false;
518 virtual void resetRightReleased()
520 rightreleased = false;
523 virtual s32 getMouseWheel()
528 virtual void step(float dtime)
531 static float counter1 = 0;
535 counter1 = 0.1*Rand(1, 40);
536 keydown.toggle(getKeySetting("keymap_jump"));
540 static float counter1 = 0;
544 counter1 = 0.1*Rand(1, 40);
545 keydown.toggle(getKeySetting("keymap_special1"));
549 static float counter1 = 0;
553 counter1 = 0.1*Rand(1, 40);
554 keydown.toggle(getKeySetting("keymap_forward"));
558 static float counter1 = 0;
562 counter1 = 0.1*Rand(1, 40);
563 keydown.toggle(getKeySetting("keymap_left"));
567 static float counter1 = 0;
571 counter1 = 0.1*Rand(1, 20);
572 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
576 static float counter1 = 0;
580 counter1 = 0.1*Rand(1, 30);
581 leftdown = !leftdown;
589 static float counter1 = 0;
593 counter1 = 0.1*Rand(1, 15);
594 rightdown = !rightdown;
598 rightreleased = true;
601 mousepos += mousespeed;
604 s32 Rand(s32 min, s32 max)
606 return (myrand()%(max-min+1))+min;
622 // These are defined global so that they're not optimized too much.
623 // Can't change them to volatile.
628 std::string tempstring;
629 std::string tempstring2;
634 infostream<<"The following test should take around 20ms."<<std::endl;
635 TimeTaker timer("Testing std::string speed");
636 const u32 jj = 10000;
637 for(u32 j=0; j<jj; j++)
642 for(u32 i=0; i<ii; i++){
643 tempstring2 += "asd";
645 for(u32 i=0; i<ii+1; i++){
647 if(tempstring == tempstring2)
653 infostream<<"All of the following tests should take around 100ms each."
657 TimeTaker timer("Testing floating-point conversion speed");
659 for(u32 i=0; i<4000000; i++){
666 TimeTaker timer("Testing floating-point vector speed");
668 tempv3f1 = v3f(1,2,3);
669 tempv3f2 = v3f(4,5,6);
670 for(u32 i=0; i<10000000; i++){
671 tempf += tempv3f1.dotProduct(tempv3f2);
672 tempv3f2 += v3f(7,8,9);
677 TimeTaker timer("Testing std::map speed");
679 std::map<v2s16, f32> map1;
682 for(s16 y=0; y<ii; y++){
683 for(s16 x=0; x<ii; x++){
684 map1[v2s16(x,y)] = tempf;
688 for(s16 y=ii-1; y>=0; y--){
689 for(s16 x=0; x<ii; x++){
690 tempf = map1[v2s16(x,y)];
696 infostream<<"Around 5000/ms should do well here."<<std::endl;
697 TimeTaker timer("Testing mutex speed");
711 while(timer.getTimerTime() < 10);
713 u32 dtime = timer.stop();
714 u32 per_ms = n / dtime;
715 infostream<<"Done. "<<dtime<<"ms, "
716 <<per_ms<<"/ms"<<std::endl;
720 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
723 for(u32 i=0; i<worldspecs.size(); i++){
724 std::string name = worldspecs[i].name;
725 std::string path = worldspecs[i].path;
726 if(name.find(" ") != std::string::npos)
727 name = std::string("'") + name + "'";
728 path = std::string("'") + path + "'";
729 name = padStringRight(name, 14);
730 os<<" "<<name<<" "<<path<<std::endl;
734 int main(int argc, char *argv[])
742 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
743 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
745 log_register_thread("main");
747 // This enables internatonal characters input
748 if( setlocale(LC_ALL, "") == NULL )
750 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
753 // Set locale. This is for forcing '.' as the decimal point.
755 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
756 setlocale(LC_NUMERIC, "C");
757 } catch (const std::exception& ex) {
758 errorstream<<"Could not set numeric locale to C"<<std::endl;
764 // List all allowed options
765 std::map<std::string, ValueSpec> allowed_options;
766 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
767 _("Show allowed options"))));
768 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
769 _("Load configuration from specified file"))));
770 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
771 _("Set network port (UDP)"))));
772 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
773 _("Disable unit tests"))));
774 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
775 _("Enable unit tests"))));
776 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
777 _("Same as --world (deprecated)"))));
778 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
779 _("Set world path (implies local game) ('list' lists all)"))));
780 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
781 _("Set world by name (implies local game)"))));
782 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
783 _("Print more information to console"))));
784 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
785 _("Print even more information to console"))));
786 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
787 _("Print enormous amounts of information to log and console"))));
788 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
789 _("Set logfile path ('' = no logging)"))));
790 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
791 _("Set gameid (\"--gameid list\" prints available ones)"))));
793 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
794 _("Show available video modes"))));
795 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
796 _("Run speed tests"))));
797 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
798 _("Address to connect to. ('' = local game)"))));
799 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
800 _("Enable random user input, for testing"))));
801 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
802 _("Run dedicated server"))));
803 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
804 _("Set player name"))));
805 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
806 _("Set password"))));
807 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
808 _("Disable main menu"))));
813 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
815 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
817 dstream<<_("Allowed options:")<<std::endl;
818 for(std::map<std::string, ValueSpec>::iterator
819 i = allowed_options.begin();
820 i != allowed_options.end(); ++i)
822 std::ostringstream os1(std::ios::binary);
823 os1<<" --"<<i->first;
824 if(i->second.type == VALUETYPE_FLAG)
828 dstream<<padStringRight(os1.str(), 24);
830 if(i->second.help != NULL)
831 dstream<<i->second.help;
835 return cmd_args.getFlag("help") ? 0 : 1;
839 Low-level initialization
842 // If trace is enabled, enable logging of certain things
843 if(cmd_args.getFlag("trace")){
844 dstream<<_("Enabling trace level debug output")<<std::endl;
845 log_trace_level_enabled = true;
846 dout_con_ptr = &verbosestream; // this is somewhat old crap
847 socket_enable_debug_output = true; // socket doesn't use log.h
849 // In certain cases, output info level on stderr
850 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
851 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
852 log_add_output(&main_stderr_log_out, LMT_INFO);
853 // In certain cases, output verbose level on stderr
854 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
855 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
857 porting::signal_handler_init();
858 bool &kill = *porting::signal_handler_killstatus();
860 porting::initializePaths();
862 // Create user data directory
863 fs::CreateDir(porting::path_user);
865 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
867 infostream<<"path_share = "<<porting::path_share<<std::endl;
868 infostream<<"path_user = "<<porting::path_user<<std::endl;
870 // Initialize debug stacks
872 DSTACK(__FUNCTION_NAME);
875 BEGIN_DEBUG_EXCEPTION_HANDLER
877 // List gameids if requested
878 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
880 std::set<std::string> gameids = getAvailableGameIds();
881 for(std::set<std::string>::const_iterator i = gameids.begin();
882 i != gameids.end(); i++)
883 dstream<<(*i)<<std::endl;
887 // List worlds if requested
888 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
889 dstream<<_("Available worlds:")<<std::endl;
890 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
891 print_worldspecs(worldspecs, dstream);
895 // Print startup message
896 infostream<<PROJECT_NAME<<
897 " "<<_("with")<<" SER_FMT_VER_HIGHEST_READ="<<(int)SER_FMT_VER_HIGHEST_READ
905 // Initialize default settings
906 set_default_settings(g_settings);
908 // Initialize sockets
910 atexit(sockets_cleanup);
916 // Path of configuration file in use
917 g_settings_path = "";
919 if(cmd_args.exists("config"))
921 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
924 errorstream<<"Could not read configuration from \""
925 <<cmd_args.get("config")<<"\""<<std::endl;
928 g_settings_path = cmd_args.get("config");
932 std::vector<std::string> filenames;
933 filenames.push_back(porting::path_user +
934 DIR_DELIM + "minetest.conf");
935 // Legacy configuration file location
936 filenames.push_back(porting::path_user +
937 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
939 // Try also from a lower level (to aid having the same configuration
940 // for many RUN_IN_PLACE installs)
941 filenames.push_back(porting::path_user +
942 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
945 for(u32 i=0; i<filenames.size(); i++)
947 bool r = g_settings->readConfigFile(filenames[i].c_str());
950 g_settings_path = filenames[i];
955 // If no path found, use the first one (menu creates the file)
956 if(g_settings_path == "")
957 g_settings_path = filenames[0];
960 // Initialize debug streams
961 #define DEBUGFILE "debug.txt"
963 std::string logfile = DEBUGFILE;
965 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
967 if(cmd_args.exists("logfile"))
968 logfile = cmd_args.get("logfile");
970 log_remove_output(&main_dstream_no_stderr_log_out);
971 int loglevel = g_settings->getS32("debug_log_level");
973 if (loglevel == 0) //no logging
975 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
976 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
979 debugstreams_init(false, logfile.c_str());
981 debugstreams_init(false, NULL);
983 infostream<<"logfile = "<<logfile<<std::endl;
985 // Initialize random seed
993 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
994 || cmd_args.getFlag("enable-unittests") == true)
1005 if(cmd_args.exists("port"))
1006 port = cmd_args.getU16("port");
1007 else if(g_settings->exists("port"))
1008 port = g_settings->getU16("port");
1013 std::string commanded_world = "";
1014 if(cmd_args.exists("world"))
1015 commanded_world = cmd_args.get("world");
1016 else if(cmd_args.exists("map-dir"))
1017 commanded_world = cmd_args.get("map-dir");
1018 else if(cmd_args.exists("nonopt0")) // First nameless argument
1019 commanded_world = cmd_args.get("nonopt0");
1020 else if(g_settings->exists("map-dir"))
1021 commanded_world = g_settings->get("map-dir");
1024 std::string commanded_worldname = "";
1025 if(cmd_args.exists("worldname"))
1026 commanded_worldname = cmd_args.get("worldname");
1028 // Strip world.mt from commanded_world
1030 std::string worldmt = "world.mt";
1031 if(commanded_world.size() > worldmt.size() &&
1032 commanded_world.substr(commanded_world.size()-worldmt.size())
1034 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1035 commanded_world = commanded_world.substr(
1036 0, commanded_world.size()-worldmt.size());
1040 // If a world name was specified, convert it to a path
1041 if(commanded_worldname != ""){
1042 // Get information about available worlds
1043 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1045 for(u32 i=0; i<worldspecs.size(); i++){
1046 std::string name = worldspecs[i].name;
1047 if(name == commanded_worldname){
1048 if(commanded_world != ""){
1049 dstream<<_("--worldname takes precedence over previously "
1050 "selected world.")<<std::endl;
1052 commanded_world = worldspecs[i].path;
1058 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1059 "available. Available worlds:")<<std::endl;
1060 print_worldspecs(worldspecs, dstream);
1066 SubgameSpec commanded_gamespec;
1067 if(cmd_args.exists("gameid")){
1068 std::string gameid = cmd_args.get("gameid");
1069 commanded_gamespec = findSubgame(gameid);
1070 if(!commanded_gamespec.isValid()){
1071 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1077 Run dedicated server if asked to or no other option
1080 bool run_dedicated_server = true;
1082 bool run_dedicated_server = cmd_args.getFlag("server");
1084 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1085 if(run_dedicated_server)
1087 DSTACK("Dedicated server branch");
1088 // Create time getter if built with Irrlicht
1090 g_timegetter = new SimpleTimeGetter();
1094 std::string world_path;
1095 verbosestream<<_("Determining world path")<<std::endl;
1096 bool is_legacy_world = false;
1097 // If a world was commanded, use it
1098 if(commanded_world != ""){
1099 world_path = commanded_world;
1100 infostream<<"Using commanded world path ["<<world_path<<"]"
1103 // No world was specified; try to select it automatically
1106 // Get information about available worlds
1107 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1108 // If a world name was specified, select it
1109 if(commanded_worldname != ""){
1111 for(u32 i=0; i<worldspecs.size(); i++){
1112 std::string name = worldspecs[i].name;
1113 if(name == commanded_worldname){
1114 world_path = worldspecs[i].path;
1118 if(world_path == ""){
1119 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1120 "available. Available worlds:")<<std::endl;
1121 print_worldspecs(worldspecs, dstream);
1125 // If there is only a single world, use it
1126 if(worldspecs.size() == 1){
1127 world_path = worldspecs[0].path;
1128 dstream<<_("Automatically selecting world at")<<" ["
1129 <<world_path<<"]"<<std::endl;
1130 // If there are multiple worlds, list them
1131 } else if(worldspecs.size() > 1){
1132 dstream<<_("Multiple worlds are available.")<<std::endl;
1133 dstream<<_("Please select one using --worldname <name>"
1134 " or --world <path>")<<std::endl;
1135 print_worldspecs(worldspecs, dstream);
1137 // If there are no worlds, automatically create a new one
1139 // This is the ultimate default world path
1140 world_path = porting::path_user + DIR_DELIM + "worlds" +
1141 DIR_DELIM + "world";
1142 infostream<<"Creating default world at ["
1143 <<world_path<<"]"<<std::endl;
1147 if(world_path == ""){
1148 errorstream<<"No world path specified or found."<<std::endl;
1151 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1153 // We need a gamespec.
1154 SubgameSpec gamespec;
1155 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1156 // If world doesn't exist
1157 if(!getWorldExists(world_path))
1159 // Try to take gamespec from command line
1160 if(commanded_gamespec.isValid()){
1161 gamespec = commanded_gamespec;
1162 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1164 // Otherwise we will be using "minetest"
1166 gamespec = findSubgame(g_settings->get("default_game"));
1167 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1173 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1174 // If commanded to use a gameid, do so
1175 if(commanded_gamespec.isValid()){
1176 gamespec = commanded_gamespec;
1177 if(commanded_gamespec.id != world_gameid){
1178 errorstream<<"WARNING: Using commanded gameid ["
1179 <<gamespec.id<<"]"<<" instead of world gameid ["
1180 <<world_gameid<<"]"<<std::endl;
1183 // If world contains an embedded game, use it;
1184 // Otherwise find world from local system.
1185 gamespec = findWorldSubgame(world_path);
1186 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1189 if(!gamespec.isValid()){
1190 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1194 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1197 Server server(world_path, gamespec, false);
1201 dedicated_server_loop(server, kill);
1206 #ifndef SERVER // Exclude from dedicated server build
1212 std::string address = g_settings->get("address");
1213 if(commanded_world != "")
1215 else if(cmd_args.exists("address"))
1216 address = cmd_args.get("address");
1218 std::string playername = g_settings->get("name");
1219 if(cmd_args.exists("name"))
1220 playername = cmd_args.get("name");
1222 bool skip_main_menu = cmd_args.getFlag("go");
1225 Device initialization
1228 // Resolution selection
1230 bool fullscreen = g_settings->getBool("fullscreen");
1231 u16 screenW = g_settings->getU16("screenW");
1232 u16 screenH = g_settings->getU16("screenH");
1236 bool vsync = g_settings->getBool("vsync");
1237 u16 bits = g_settings->getU16("fullscreen_bpp");
1238 u16 fsaa = g_settings->getU16("fsaa");
1242 video::E_DRIVER_TYPE driverType;
1244 std::string driverstring = g_settings->get("video_driver");
1246 if(driverstring == "null")
1247 driverType = video::EDT_NULL;
1248 else if(driverstring == "software")
1249 driverType = video::EDT_SOFTWARE;
1250 else if(driverstring == "burningsvideo")
1251 driverType = video::EDT_BURNINGSVIDEO;
1252 else if(driverstring == "direct3d8")
1253 driverType = video::EDT_DIRECT3D8;
1254 else if(driverstring == "direct3d9")
1255 driverType = video::EDT_DIRECT3D9;
1256 else if(driverstring == "opengl")
1257 driverType = video::EDT_OPENGL;
1258 #ifdef _IRR_COMPILE_WITH_OGLES1_
1259 else if(driverstring == "ogles1")
1260 driverType = video::EDT_OGLES1;
1262 #ifdef _IRR_COMPILE_WITH_OGLES2_
1263 else if(driverstring == "ogles2")
1264 driverType = video::EDT_OGLES2;
1268 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1269 "to opengl"<<std::endl;
1270 driverType = video::EDT_OPENGL;
1274 List video modes if requested
1277 MyEventReceiver receiver;
1279 if(cmd_args.getFlag("videomodes")){
1280 IrrlichtDevice *nulldevice;
1282 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1283 params.DriverType = video::EDT_NULL;
1284 params.WindowSize = core::dimension2d<u32>(640, 480);
1286 params.AntiAlias = fsaa;
1287 params.Fullscreen = false;
1288 params.Stencilbuffer = false;
1289 params.Vsync = vsync;
1290 params.EventReceiver = &receiver;
1292 nulldevice = createDeviceEx(params);
1297 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1299 video::IVideoModeList *videomode_list =
1300 nulldevice->getVideoModeList();
1302 if(videomode_list == 0){
1307 s32 videomode_count = videomode_list->getVideoModeCount();
1308 core::dimension2d<u32> videomode_res;
1309 s32 videomode_depth;
1310 for (s32 i = 0; i < videomode_count; ++i){
1311 videomode_res = videomode_list->getVideoModeResolution(i);
1312 videomode_depth = videomode_list->getVideoModeDepth(i);
1313 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1314 <<"x"<<videomode_depth<<std::endl;
1317 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1318 videomode_res = videomode_list->getDesktopResolution();
1319 videomode_depth = videomode_list->getDesktopDepth();
1320 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1321 <<"x"<<videomode_depth<<std::endl;
1329 Create device and exit if creation failed
1332 IrrlichtDevice *device;
1334 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1335 params.DriverType = driverType;
1336 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1338 params.AntiAlias = fsaa;
1339 params.Fullscreen = fullscreen;
1340 params.Stencilbuffer = false;
1341 params.Vsync = vsync;
1342 params.EventReceiver = &receiver;
1344 device = createDeviceEx(params);
1347 return 1; // could not create selected driver.
1350 Continue initialization
1353 video::IVideoDriver* driver = device->getVideoDriver();
1356 This changes the minimum allowed number of vertices in a VBO.
1359 //driver->setMinHardwareBufferVertexCount(50);
1361 // Create time getter
1362 g_timegetter = new IrrlichtTimeGetter(device);
1364 // Create game callback for menus
1365 g_gamecallback = new MainGameCallback(device);
1368 Speed tests (done after irrlicht is loaded to get timer)
1370 if(cmd_args.getFlag("speedtests"))
1372 dstream<<"Running speed tests"<<std::endl;
1378 device->setResizable(true);
1380 bool random_input = g_settings->getBool("random_input")
1381 || cmd_args.getFlag("random-input");
1382 InputHandler *input = NULL;
1384 input = new RandomInputHandler();
1386 input = new RealInputHandler(device, &receiver);
1388 scene::ISceneManager* smgr = device->getSceneManager();
1390 guienv = device->getGUIEnvironment();
1391 gui::IGUISkin* skin = guienv->getSkin();
1392 std::string font_path = g_settings->get("font_path");
1393 gui::IGUIFont *font;
1394 bool use_freetype = g_settings->getBool("freetype");
1397 u16 font_size = g_settings->getU16("font_size");
1398 font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1400 font = guienv->getFont(font_path.c_str());
1403 font = guienv->getFont(font_path.c_str());
1406 skin->setFont(font);
1408 errorstream<<"WARNING: Font file was not found."
1409 " Using default font."<<std::endl;
1410 // If font was not found, this will get us one
1411 font = skin->getFont();
1414 u32 text_height = font->getDimension(L"Hello, world!").Height;
1415 infostream<<"text_height="<<text_height<<std::endl;
1417 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1418 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1419 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1420 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1421 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1422 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1423 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1424 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1426 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1427 // Irrlicht 1.8 input colours
1428 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1429 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1433 // Create the menu clouds
1434 if (!g_menucloudsmgr)
1435 g_menucloudsmgr = smgr->createNewSceneManager();
1437 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1438 g_menucloudsmgr, -1, rand(), 100);
1439 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1440 scene::ICameraSceneNode* camera;
1441 camera = g_menucloudsmgr->addCameraSceneNode(0,
1442 v3f(0,0,0), v3f(0, 60, 100));
1443 camera->setFarValue(10000);
1449 ChatBackend chat_backend;
1452 If an error occurs, this is set to something and the
1453 menu-game loop is restarted. It is then displayed before
1456 std::wstring error_message = L"";
1458 // The password entered during the menu screen,
1459 std::string password;
1461 bool first_loop = true;
1466 while(device->run() && kill == false)
1468 // Set the window caption
1469 wchar_t* text = wgettext("Main Menu");
1470 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1473 // This is used for catching disconnects
1478 Clear everything from the GUIEnvironment
1483 We need some kind of a root node to be able to add
1484 custom gui elements directly on the screen.
1485 Otherwise they won't be automatically drawn.
1487 guiroot = guienv->addStaticText(L"",
1488 core::rect<s32>(0, 0, 10000, 10000));
1490 SubgameSpec gamespec;
1491 WorldSpec worldspec;
1492 bool simple_singleplayer_mode = false;
1494 // These are set up based on the menu and other things
1495 std::string current_playername = "inv£lid";
1496 std::string current_password = "";
1497 std::string current_address = "does-not-exist";
1498 int current_port = 0;
1501 Out-of-game menu loop.
1503 Loop quits when menu returns proper parameters.
1505 while(kill == false)
1507 // If skip_main_menu, only go through here once
1508 if(skip_main_menu && !first_loop){
1514 // Cursor can be non-visible when coming from the game
1515 device->getCursorControl()->setVisible(true);
1516 // Some stuff are left to scene manager when coming from the game
1520 // Initialize menu data
1521 MainMenuData menudata;
1522 menudata.kill = kill;
1523 menudata.address = address;
1524 menudata.name = playername;
1525 menudata.port = itos(port);
1526 menudata.errormessage = wide_to_narrow(error_message);
1527 error_message = L"";
1528 if(cmd_args.exists("password"))
1529 menudata.password = cmd_args.get("password");
1531 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1533 menudata.enable_public = g_settings->getBool("server_announce");
1535 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1537 // If a world was commanded, append and select it
1538 if(commanded_world != ""){
1540 std::string gameid = getWorldGameId(commanded_world, true);
1541 std::string name = _("[--world parameter]");
1543 gameid = g_settings->get("default_game");
1546 //TODO find within worldspecs and set config
1549 if(skip_main_menu == false)
1551 video::IVideoDriver* driver = device->getVideoDriver();
1553 infostream<<"Waiting for other menus"<<std::endl;
1554 while(device->run() && kill == false)
1558 driver->beginScene(true, true,
1559 video::SColor(255,128,128,128));
1562 // On some computers framerate doesn't seem to be
1563 // automatically limited
1566 infostream<<"Waited for other menus"<<std::endl;
1568 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata);
1571 //once finished you'll never end up here
1573 kill = menudata.kill;
1577 if(menudata.errormessage != ""){
1578 error_message = narrow_to_wide(menudata.errormessage);
1582 //update worldspecs (necessary as new world may have been created)
1583 worldspecs = getAvailableWorlds();
1585 if (menudata.name == "")
1586 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1588 playername = menudata.name;
1590 password = translatePassword(playername, narrow_to_wide(menudata.password));
1591 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1593 address = menudata.address;
1594 int newport = stoi(menudata.port);
1598 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1601 g_settings->set("name", playername);
1602 g_settings->set("address", address);
1603 g_settings->set("port", itos(port));
1605 if((menudata.selected_world >= 0) &&
1606 (menudata.selected_world < worldspecs.size()))
1607 g_settings->set("selected_world_path",
1608 worldspecs[menudata.selected_world].path);
1610 // Break out of menu-game loop to shut down cleanly
1611 if(device->run() == false || kill == true)
1614 current_playername = playername;
1615 current_password = password;
1616 current_address = address;
1617 current_port = port;
1619 // If using simple singleplayer mode, override
1620 if(simple_singleplayer_mode){
1621 current_playername = "singleplayer";
1622 current_password = "";
1623 current_address = "";
1624 current_port = myrand_range(49152, 65535);
1626 else if (address != "")
1628 ServerListSpec server;
1629 server["name"] = menudata.servername;
1630 server["address"] = menudata.address;
1631 server["port"] = menudata.port;
1632 server["description"] = menudata.serverdescription;
1633 ServerList::insert(server);
1636 // Set world path to selected one
1637 if ((menudata.selected_world >= 0) &&
1638 (menudata.selected_world < worldspecs.size())) {
1639 worldspec = worldspecs[menudata.selected_world];
1640 infostream<<"Selected world: "<<worldspec.name
1641 <<" ["<<worldspec.path<<"]"<<std::endl;
1645 if(current_address == "")
1647 if(menudata.selected_world == -1){
1648 error_message = wgettext("No world selected and no address "
1649 "provided. Nothing to do.");
1650 errorstream<<wide_to_narrow(error_message)<<std::endl;
1653 // Load gamespec for required game
1654 gamespec = findWorldSubgame(worldspec.path);
1655 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1656 error_message = wgettext("Could not find or load game \"")
1657 + narrow_to_wide(worldspec.gameid) + L"\"";
1658 errorstream<<wide_to_narrow(error_message)<<std::endl;
1661 if(commanded_gamespec.isValid() &&
1662 commanded_gamespec.id != worldspec.gameid){
1663 errorstream<<"WARNING: Overriding gamespec from \""
1664 <<worldspec.gameid<<"\" to \""
1665 <<commanded_gamespec.id<<"\""<<std::endl;
1666 gamespec = commanded_gamespec;
1669 if(!gamespec.isValid()){
1670 error_message = wgettext("Invalid gamespec.");
1671 error_message += L" (world_gameid="
1672 +narrow_to_wide(worldspec.gameid)+L")";
1673 errorstream<<wide_to_narrow(error_message)<<std::endl;
1682 // Break out of menu-game loop to shut down cleanly
1683 if(device->run() == false || kill == true) {
1684 if(g_settings_path != "") {
1685 g_settings->updateConfigFile(
1686 g_settings_path.c_str());
1708 simple_singleplayer_mode
1713 catch(con::PeerNotFoundException &e)
1715 error_message = wgettext("Connection error (timed out?)");
1716 errorstream<<wide_to_narrow(error_message)<<std::endl;
1719 catch(std::exception &e)
1721 std::string narrow_message = "Some exception: \"";
1722 narrow_message += e.what();
1723 narrow_message += "\"";
1724 errorstream<<narrow_message<<std::endl;
1725 error_message = narrow_to_wide(narrow_message);
1729 // If no main menu, show error and exit
1732 if(error_message != L""){
1733 verbosestream<<"error_message = "
1734 <<wide_to_narrow(error_message)<<std::endl;
1742 g_menuclouds->drop();
1743 g_menucloudsmgr->drop();
1748 In the end, delete the Irrlicht device.
1759 // Update configuration file
1760 if(g_settings_path != "")
1761 g_settings->updateConfigFile(g_settings_path.c_str());
1763 // Print modified quicktune values
1765 bool header_printed = false;
1766 std::vector<std::string> names = getQuicktuneNames();
1767 for(u32 i=0; i<names.size(); i++){
1768 QuicktuneValue val = getQuicktuneValue(names[i]);
1771 if(!header_printed){
1772 dstream<<"Modified quicktune values:"<<std::endl;
1773 header_printed = true;
1775 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1779 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1781 debugstreams_deinit();