3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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 "common_irrlicht.h"
54 #include "constants.h"
57 #include "guiMessageMenu.h"
60 #include "guiMainMenu.h"
65 #include "defaultsettings.h"
71 #include "utility_string.h"
73 #include "quicktune.h"
77 These are loaded from the config file.
79 Settings main_settings;
80 Settings *g_settings = &main_settings;
83 Profiler main_profiler;
84 Profiler *g_profiler = &main_profiler;
91 std::ostream *dout_con_ptr = &dummyout;
92 std::ostream *derr_con_ptr = &verbosestream;
95 std::ostream *dout_server_ptr = &infostream;
96 std::ostream *derr_server_ptr = &errorstream;
99 std::ostream *dout_client_ptr = &infostream;
100 std::ostream *derr_client_ptr = &errorstream;
107 /* mainmenumanager.h */
109 gui::IGUIEnvironment* guienv = NULL;
110 gui::IGUIStaticText *guiroot = NULL;
111 MainMenuManager g_menumgr;
115 return (g_menumgr.menuCount() == 0);
118 // Passed to menus to allow disconnecting and exiting
119 MainGameCallback *g_gamecallback = NULL;
123 gettime.h implementation
130 /* Use imprecise system calls directly (from porting.h) */
131 return porting::getTimeMs();
136 // A small helper class
140 virtual u32 getTime() = 0;
143 // A precise irrlicht one
144 class IrrlichtTimeGetter: public TimeGetter
147 IrrlichtTimeGetter(IrrlichtDevice *device):
154 return m_device->getTimer()->getRealTime();
157 IrrlichtDevice *m_device;
159 // Not so precise one which works without irrlicht
160 class SimpleTimeGetter: public TimeGetter
165 return porting::getTimeMs();
169 // A pointer to a global instance of the time getter
171 TimeGetter *g_timegetter = NULL;
175 if(g_timegetter == NULL)
177 return g_timegetter->getTime();
182 class StderrLogOutput: public ILogOutput
185 /* line: Full line with timestamp, level and thread */
186 void printLog(const std::string &line)
188 std::cerr<<line<<std::endl;
190 } main_stderr_log_out;
192 class DstreamNoStderrLogOutput: public ILogOutput
195 /* line: Full line with timestamp, level and thread */
196 void printLog(const std::string &line)
198 dstream_no_stderr<<line<<std::endl;
200 } main_dstream_no_stderr_log_out;
205 Event handler for Irrlicht
207 NOTE: Everything possible should be moved out from here,
208 probably to InputHandler and the_game
211 class MyEventReceiver : public IEventReceiver
214 // This is the one method that we have to implement
215 virtual bool OnEvent(const SEvent& event)
218 React to nothing here if a menu is active
220 if(noMenuActive() == false)
225 // Remember whether each key is down or up
226 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
228 if(event.KeyInput.PressedDown) {
229 keyIsDown.set(event.KeyInput);
230 keyWasDown.set(event.KeyInput);
232 keyIsDown.unset(event.KeyInput);
236 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
238 if(noMenuActive() == false)
241 middle_active = false;
242 right_active = false;
246 left_active = event.MouseInput.isLeftPressed();
247 middle_active = event.MouseInput.isMiddlePressed();
248 right_active = event.MouseInput.isRightPressed();
250 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
254 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
258 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
262 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
264 rightreleased = true;
266 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
268 mouse_wheel += event.MouseInput.Wheel;
276 bool IsKeyDown(const KeyPress &keyCode) const
278 return keyIsDown[keyCode];
281 // Checks whether a key was down and resets the state
282 bool WasKeyDown(const KeyPress &keyCode)
284 bool b = keyWasDown[keyCode];
286 keyWasDown.unset(keyCode);
303 rightclicked = false;
304 leftreleased = false;
305 rightreleased = false;
308 middle_active = false;
309 right_active = false;
331 IrrlichtDevice *m_device;
333 // The current state of keys
335 // Whether a key has been pressed or not
340 Separated input handler
343 class RealInputHandler : public InputHandler
346 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
351 virtual bool isKeyDown(const KeyPress &keyCode)
353 return m_receiver->IsKeyDown(keyCode);
355 virtual bool wasKeyDown(const KeyPress &keyCode)
357 return m_receiver->WasKeyDown(keyCode);
359 virtual v2s32 getMousePos()
361 return m_device->getCursorControl()->getPosition();
363 virtual void setMousePos(s32 x, s32 y)
365 m_device->getCursorControl()->setPosition(x, y);
368 virtual bool getLeftState()
370 return m_receiver->left_active;
372 virtual bool getRightState()
374 return m_receiver->right_active;
377 virtual bool getLeftClicked()
379 return m_receiver->leftclicked;
381 virtual bool getRightClicked()
383 return m_receiver->rightclicked;
385 virtual void resetLeftClicked()
387 m_receiver->leftclicked = false;
389 virtual void resetRightClicked()
391 m_receiver->rightclicked = false;
394 virtual bool getLeftReleased()
396 return m_receiver->leftreleased;
398 virtual bool getRightReleased()
400 return m_receiver->rightreleased;
402 virtual void resetLeftReleased()
404 m_receiver->leftreleased = false;
406 virtual void resetRightReleased()
408 m_receiver->rightreleased = false;
411 virtual s32 getMouseWheel()
413 return m_receiver->getMouseWheel();
418 m_receiver->clearInput();
421 IrrlichtDevice *m_device;
422 MyEventReceiver *m_receiver;
425 class RandomInputHandler : public InputHandler
433 rightclicked = false;
434 leftreleased = false;
435 rightreleased = false;
438 virtual bool isKeyDown(const KeyPress &keyCode)
440 return keydown[keyCode];
442 virtual bool wasKeyDown(const KeyPress &keyCode)
446 virtual v2s32 getMousePos()
450 virtual void setMousePos(s32 x, s32 y)
452 mousepos = v2s32(x,y);
455 virtual bool getLeftState()
459 virtual bool getRightState()
464 virtual bool getLeftClicked()
468 virtual bool getRightClicked()
472 virtual void resetLeftClicked()
476 virtual void resetRightClicked()
478 rightclicked = false;
481 virtual bool getLeftReleased()
485 virtual bool getRightReleased()
487 return rightreleased;
489 virtual void resetLeftReleased()
491 leftreleased = false;
493 virtual void resetRightReleased()
495 rightreleased = false;
498 virtual s32 getMouseWheel()
503 virtual void step(float dtime)
506 static float counter1 = 0;
510 counter1 = 0.1*Rand(1, 40);
511 keydown.toggle(getKeySetting("keymap_jump"));
515 static float counter1 = 0;
519 counter1 = 0.1*Rand(1, 40);
520 keydown.toggle(getKeySetting("keymap_special1"));
524 static float counter1 = 0;
528 counter1 = 0.1*Rand(1, 40);
529 keydown.toggle(getKeySetting("keymap_forward"));
533 static float counter1 = 0;
537 counter1 = 0.1*Rand(1, 40);
538 keydown.toggle(getKeySetting("keymap_left"));
542 static float counter1 = 0;
546 counter1 = 0.1*Rand(1, 20);
547 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
551 static float counter1 = 0;
555 counter1 = 0.1*Rand(1, 30);
556 leftdown = !leftdown;
564 static float counter1 = 0;
568 counter1 = 0.1*Rand(1, 15);
569 rightdown = !rightdown;
573 rightreleased = true;
576 mousepos += mousespeed;
579 s32 Rand(s32 min, s32 max)
581 return (myrand()%(max-min+1))+min;
595 void drawMenuBackground(video::IVideoDriver* driver)
597 core::dimension2d<u32> screensize = driver->getScreenSize();
599 video::ITexture *bgtexture =
600 driver->getTexture(getTexturePath("menubg.png").c_str());
603 s32 scaledsize = 128;
605 // The important difference between destsize and screensize is
606 // that destsize is rounded to whole scaled pixels.
607 // These formulas use component-wise multiplication and division of v2u32.
608 v2u32 texturesize = bgtexture->getSize();
609 v2u32 sourcesize = texturesize * screensize / scaledsize + v2u32(1,1);
610 v2u32 destsize = scaledsize * sourcesize / texturesize;
612 // Default texture wrapping mode in Irrlicht is ETC_REPEAT.
613 driver->draw2DImage(bgtexture,
614 core::rect<s32>(0, 0, destsize.X, destsize.Y),
615 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
619 video::ITexture *logotexture =
620 driver->getTexture(getTexturePath("menulogo.png").c_str());
623 v2s32 logosize(logotexture->getOriginalSize().Width,
624 logotexture->getOriginalSize().Height);
627 video::SColor bgcolor(255,50,50,50);
628 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
629 screensize.Width, screensize.Height);
630 driver->draw2DRectangle(bgcolor, bgrect, NULL);
632 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
633 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
634 rect -= v2s32(logosize.X/2, 0);
635 driver->draw2DImage(logotexture, rect,
636 core::rect<s32>(core::position2d<s32>(0,0),
637 core::dimension2di(logotexture->getSize())),
644 // These are defined global so that they're not optimized too much.
645 // Can't change them to volatile.
650 std::string tempstring;
651 std::string tempstring2;
656 infostream<<"The following test should take around 20ms."<<std::endl;
657 TimeTaker timer("Testing std::string speed");
658 const u32 jj = 10000;
659 for(u32 j=0; j<jj; j++)
664 for(u32 i=0; i<ii; i++){
665 tempstring2 += "asd";
667 for(u32 i=0; i<ii+1; i++){
669 if(tempstring == tempstring2)
675 infostream<<"All of the following tests should take around 100ms each."
679 TimeTaker timer("Testing floating-point conversion speed");
681 for(u32 i=0; i<4000000; i++){
688 TimeTaker timer("Testing floating-point vector speed");
690 tempv3f1 = v3f(1,2,3);
691 tempv3f2 = v3f(4,5,6);
692 for(u32 i=0; i<10000000; i++){
693 tempf += tempv3f1.dotProduct(tempv3f2);
694 tempv3f2 += v3f(7,8,9);
699 TimeTaker timer("Testing core::map speed");
701 core::map<v2s16, f32> map1;
704 for(s16 y=0; y<ii; y++){
705 for(s16 x=0; x<ii; x++){
706 map1.insert(v2s16(x,y), tempf);
710 for(s16 y=ii-1; y>=0; y--){
711 for(s16 x=0; x<ii; x++){
712 tempf = map1[v2s16(x,y)];
718 infostream<<"Around 5000/ms should do well here."<<std::endl;
719 TimeTaker timer("Testing mutex speed");
733 while(timer.getTime() < 10);
735 u32 dtime = timer.stop();
736 u32 per_ms = n / dtime;
737 infostream<<"Done. "<<dtime<<"ms, "
738 <<per_ms<<"/ms"<<std::endl;
742 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
745 for(u32 i=0; i<worldspecs.size(); i++){
746 std::string name = worldspecs[i].name;
747 std::string path = worldspecs[i].path;
748 if(name.find(" ") != std::string::npos)
749 name = std::string("'") + name + "'";
750 path = std::string("'") + path + "'";
751 name = padStringRight(name, 14);
752 os<<" "<<name<<" "<<path<<std::endl;
756 int main(int argc, char *argv[])
764 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
765 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
767 log_register_thread("main");
769 // Set locale. This is for forcing '.' as the decimal point.
770 std::locale::global(std::locale("C"));
771 // This enables printing all characters in bitmap font
772 setlocale(LC_CTYPE, "en_US");
778 // List all allowed options
779 core::map<std::string, ValueSpec> allowed_options;
780 allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
781 "Show allowed options"));
782 allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
783 "Load configuration from specified file"));
784 allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
785 "Set network port (UDP)"));
786 allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
787 "Disable unit tests"));
788 allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
789 "Enable unit tests"));
790 allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
791 "Same as --world (deprecated)"));
792 allowed_options.insert("world", ValueSpec(VALUETYPE_STRING,
793 "Set world path (implies local game) ('list' lists all)"));
794 allowed_options.insert("worldname", ValueSpec(VALUETYPE_STRING,
795 "Set world by name (implies local game)"));
796 allowed_options.insert("info", ValueSpec(VALUETYPE_FLAG,
797 "Print more information to console"));
798 allowed_options.insert("verbose", ValueSpec(VALUETYPE_FLAG,
799 "Print even more information to console"));
800 allowed_options.insert("trace", ValueSpec(VALUETYPE_FLAG,
801 "Print enormous amounts of information to log and console"));
802 allowed_options.insert("logfile", ValueSpec(VALUETYPE_STRING,
803 "Set logfile path ('' = no logging)"));
804 allowed_options.insert("gameid", ValueSpec(VALUETYPE_STRING,
805 "Set gameid (\"--gameid list\" prints available ones)"));
807 allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
809 allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
810 "Address to connect to. ('' = local game)"));
811 allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
812 "Enable random user input, for testing"));
813 allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
814 "Run dedicated server"));
815 allowed_options.insert("name", ValueSpec(VALUETYPE_STRING,
817 allowed_options.insert("password", ValueSpec(VALUETYPE_STRING,
819 allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG,
820 "Disable main menu"));
825 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
827 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
829 dstream<<"Allowed options:"<<std::endl;
830 for(core::map<std::string, ValueSpec>::Iterator
831 i = allowed_options.getIterator();
832 i.atEnd() == false; i++)
834 std::ostringstream os1(std::ios::binary);
835 os1<<" --"<<i.getNode()->getKey();
836 if(i.getNode()->getValue().type == VALUETYPE_FLAG)
840 dstream<<padStringRight(os1.str(), 24);
842 if(i.getNode()->getValue().help != NULL)
843 dstream<<i.getNode()->getValue().help;
847 return cmd_args.getFlag("help") ? 0 : 1;
851 Low-level initialization
854 // If trace is enabled, enable logging of certain things
855 if(cmd_args.getFlag("trace")){
856 dstream<<"Enabling trace level debug output"<<std::endl;
857 log_trace_level_enabled = true;
858 dout_con_ptr = &verbosestream; // this is somewhat old crap
859 socket_enable_debug_output = true; // socket doesn't use log.h
861 // In certain cases, output info level on stderr
862 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
863 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
864 log_add_output(&main_stderr_log_out, LMT_INFO);
865 // In certain cases, output verbose level on stderr
866 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
867 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
869 porting::signal_handler_init();
870 bool &kill = *porting::signal_handler_killstatus();
872 porting::initializePaths();
874 // Create user data directory
875 fs::CreateDir(porting::path_user);
877 init_gettext((porting::path_share+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
879 // Initialize debug streams
881 std::string logfile = DEBUGFILE;
883 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
885 if(cmd_args.exists("logfile"))
886 logfile = cmd_args.get("logfile");
888 debugstreams_init(false, logfile.c_str());
890 debugstreams_init(false, NULL);
892 infostream<<"logfile = "<<logfile<<std::endl;
893 infostream<<"path_share = "<<porting::path_share<<std::endl;
894 infostream<<"path_user = "<<porting::path_user<<std::endl;
896 // Initialize debug stacks
898 DSTACK(__FUNCTION_NAME);
901 BEGIN_DEBUG_EXCEPTION_HANDLER
903 // List gameids if requested
904 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
906 std::set<std::string> gameids = getAvailableGameIds();
907 for(std::set<std::string>::const_iterator i = gameids.begin();
908 i != gameids.end(); i++)
909 dstream<<(*i)<<std::endl;
913 // List worlds if requested
914 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
915 dstream<<"Available worlds:"<<std::endl;
916 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
917 print_worldspecs(worldspecs, dstream);
921 // Print startup message
922 infostream<<PROJECT_NAME<<
923 " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
931 // Initialize default settings
932 set_default_settings(g_settings);
934 // Initialize sockets
936 atexit(sockets_cleanup);
942 // Path of configuration file in use
943 std::string configpath = "";
945 if(cmd_args.exists("config"))
947 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
950 errorstream<<"Could not read configuration from \""
951 <<cmd_args.get("config")<<"\""<<std::endl;
954 configpath = cmd_args.get("config");
958 core::array<std::string> filenames;
959 filenames.push_back(porting::path_user +
960 DIR_DELIM + "minetest.conf");
961 // Legacy configuration file location
962 filenames.push_back(porting::path_user +
963 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
965 // Try also from a lower level (to aid having the same configuration
966 // for many RUN_IN_PLACE installs)
967 filenames.push_back(porting::path_user +
968 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
971 for(u32 i=0; i<filenames.size(); i++)
973 bool r = g_settings->readConfigFile(filenames[i].c_str());
976 configpath = filenames[i];
981 // If no path found, use the first one (menu creates the file)
983 configpath = filenames[0];
986 // Initialize random seed
994 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
995 || cmd_args.getFlag("enable-unittests") == true)
1006 if(cmd_args.exists("port"))
1007 port = cmd_args.getU16("port");
1008 else if(g_settings->exists("port"))
1009 port = g_settings->getU16("port");
1014 std::string commanded_world = "";
1015 if(cmd_args.exists("world"))
1016 commanded_world = cmd_args.get("world");
1017 else if(cmd_args.exists("map-dir"))
1018 commanded_world = cmd_args.get("map-dir");
1019 else if(cmd_args.exists("nonopt0")) // First nameless argument
1020 commanded_world = cmd_args.get("nonopt0");
1021 else if(g_settings->exists("map-dir"))
1022 commanded_world = g_settings->get("map-dir");
1025 std::string commanded_worldname = "";
1026 if(cmd_args.exists("worldname"))
1027 commanded_worldname = cmd_args.get("worldname");
1029 // Strip world.mt from commanded_world
1031 std::string worldmt = "world.mt";
1032 if(commanded_world.size() > worldmt.size() &&
1033 commanded_world.substr(commanded_world.size()-worldmt.size())
1035 dstream<<"Supplied world.mt file - stripping it off."<<std::endl;
1036 commanded_world = commanded_world.substr(
1037 0, commanded_world.size()-worldmt.size());
1041 // If a world name was specified, convert it to a path
1042 if(commanded_worldname != ""){
1043 // Get information about available worlds
1044 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1046 for(u32 i=0; i<worldspecs.size(); i++){
1047 std::string name = worldspecs[i].name;
1048 if(name == commanded_worldname){
1049 if(commanded_world != ""){
1050 dstream<<"--worldname takes precedence over previously "
1051 <<"selected world."<<std::endl;
1053 commanded_world = worldspecs[i].path;
1059 dstream<<"World '"<<commanded_worldname<<"' not "
1060 <<"available. Available worlds:"<<std::endl;
1061 print_worldspecs(worldspecs, dstream);
1067 SubgameSpec commanded_gamespec;
1068 if(cmd_args.exists("gameid")){
1069 std::string gameid = cmd_args.get("gameid");
1070 commanded_gamespec = findSubgame(gameid);
1071 if(!commanded_gamespec.isValid()){
1072 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1078 Run dedicated server if asked to or no other option
1081 bool run_dedicated_server = true;
1083 bool run_dedicated_server = cmd_args.getFlag("server");
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, configpath, 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;
1260 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1261 "to opengl"<<std::endl;
1262 driverType = video::EDT_OPENGL;
1266 Create device and exit if creation failed
1269 MyEventReceiver receiver;
1271 IrrlichtDevice *device;
1273 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1274 params.DriverType = driverType;
1275 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1277 params.AntiAlias = fsaa;
1278 params.Fullscreen = fullscreen;
1279 params.Stencilbuffer = false;
1280 params.Vsync = vsync;
1281 params.EventReceiver = &receiver;
1283 device = createDeviceEx(params);
1286 return 1; // could not create selected driver.
1289 Continue initialization
1292 video::IVideoDriver* driver = device->getVideoDriver();
1294 // Disable mipmaps (because some of them look ugly)
1295 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1298 This changes the minimum allowed number of vertices in a VBO.
1301 //driver->setMinHardwareBufferVertexCount(50);
1303 // Create time getter
1304 g_timegetter = new IrrlichtTimeGetter(device);
1306 // Create game callback for menus
1307 g_gamecallback = new MainGameCallback(device);
1310 Speed tests (done after irrlicht is loaded to get timer)
1312 if(cmd_args.getFlag("speedtests"))
1314 dstream<<"Running speed tests"<<std::endl;
1319 device->setResizable(true);
1321 bool random_input = g_settings->getBool("random_input")
1322 || cmd_args.getFlag("random-input");
1323 InputHandler *input = NULL;
1325 input = new RandomInputHandler();
1327 input = new RealInputHandler(device, &receiver);
1329 scene::ISceneManager* smgr = device->getSceneManager();
1331 guienv = device->getGUIEnvironment();
1332 gui::IGUISkin* skin = guienv->getSkin();
1333 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1335 skin->setFont(font);
1337 errorstream<<"WARNING: Font file was not found."
1338 " Using default font."<<std::endl;
1339 // If font was not found, this will get us one
1340 font = skin->getFont();
1343 u32 text_height = font->getDimension(L"Hello, world!").Height;
1344 infostream<<"text_height="<<text_height<<std::endl;
1346 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1347 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1348 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1349 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1350 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1351 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1352 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1353 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1359 ChatBackend chat_backend;
1362 If an error occurs, this is set to something and the
1363 menu-game loop is restarted. It is then displayed before
1366 std::wstring error_message = L"";
1368 // The password entered during the menu screen,
1369 std::string password;
1371 bool first_loop = true;
1376 while(device->run() && kill == false)
1378 // Set the window caption
1379 device->setWindowCaption(L"Minetest [Main Menu]");
1381 // This is used for catching disconnects
1386 Clear everything from the GUIEnvironment
1391 We need some kind of a root node to be able to add
1392 custom gui elements directly on the screen.
1393 Otherwise they won't be automatically drawn.
1395 guiroot = guienv->addStaticText(L"",
1396 core::rect<s32>(0, 0, 10000, 10000));
1398 SubgameSpec gamespec;
1399 WorldSpec worldspec;
1400 bool simple_singleplayer_mode = false;
1402 // These are set up based on the menu and other things
1403 std::string current_playername = "inv£lid";
1404 std::string current_password = "";
1405 std::string current_address = "does-not-exist";
1406 int current_port = 0;
1409 Out-of-game menu loop.
1411 Loop quits when menu returns proper parameters.
1413 while(kill == false)
1415 // If skip_main_menu, only go through here once
1416 if(skip_main_menu && !first_loop){
1422 // Cursor can be non-visible when coming from the game
1423 device->getCursorControl()->setVisible(true);
1424 // Some stuff are left to scene manager when coming from the game
1428 // Initialize menu data
1429 MainMenuData menudata;
1430 if(g_settings->exists("selected_mainmenu_tab"))
1431 menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1432 menudata.address = narrow_to_wide(address);
1433 menudata.name = narrow_to_wide(playername);
1434 menudata.port = narrow_to_wide(itos(port));
1435 if(cmd_args.exists("password"))
1436 menudata.password = narrow_to_wide(cmd_args.get("password"));
1437 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1438 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1439 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1440 menudata.opaque_water = g_settings->getBool("opaque_water");
1441 menudata.creative_mode = g_settings->getBool("creative_mode");
1442 menudata.enable_damage = g_settings->getBool("enable_damage");
1443 // Default to selecting nothing
1444 menudata.selected_world = -1;
1445 // Get world listing for the menu
1446 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1447 // If there is only one world, select it
1448 if(worldspecs.size() == 1){
1449 menudata.selected_world = 0;
1451 // Otherwise try to select according to selected_world_path
1452 else if(g_settings->exists("selected_world_path")){
1453 std::string trypath = g_settings->get("selected_world_path");
1454 for(u32 i=0; i<worldspecs.size(); i++){
1455 if(worldspecs[i].path == trypath){
1456 menudata.selected_world = i;
1461 // If a world was commanded, append and select it
1462 if(commanded_world != ""){
1463 std::string gameid = getWorldGameId(commanded_world, true);
1464 std::string name = "[--world parameter]";
1466 gameid = g_settings->get("default_game");
1469 WorldSpec spec(commanded_world, name, gameid);
1470 worldspecs.push_back(spec);
1471 menudata.selected_world = worldspecs.size()-1;
1473 // Copy worldspecs to menu
1474 menudata.worlds = worldspecs;
1476 if(skip_main_menu == false)
1478 video::IVideoDriver* driver = device->getVideoDriver();
1480 infostream<<"Waiting for other menus"<<std::endl;
1481 while(device->run() && kill == false)
1485 driver->beginScene(true, true,
1486 video::SColor(255,128,128,128));
1487 drawMenuBackground(driver);
1490 // On some computers framerate doesn't seem to be
1491 // automatically limited
1494 infostream<<"Waited for other menus"<<std::endl;
1497 new GUIMainMenu(guienv, guiroot, -1,
1498 &g_menumgr, &menudata, g_gamecallback);
1499 menu->allowFocusRemoval(true);
1501 if(error_message != L"")
1503 verbosestream<<"error_message = "
1504 <<wide_to_narrow(error_message)<<std::endl;
1506 GUIMessageMenu *menu2 =
1507 new GUIMessageMenu(guienv, guiroot, -1,
1508 &g_menumgr, error_message.c_str());
1510 error_message = L"";
1513 infostream<<"Created main menu"<<std::endl;
1515 while(device->run() && kill == false)
1517 if(menu->getStatus() == true)
1520 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1521 driver->beginScene(true, true, video::SColor(255,128,128,128));
1523 drawMenuBackground(driver);
1529 // On some computers framerate doesn't seem to be
1530 // automatically limited
1534 infostream<<"Dropping main menu"<<std::endl;
1539 playername = wide_to_narrow(menudata.name);
1540 password = translatePassword(playername, menudata.password);
1541 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1543 address = wide_to_narrow(menudata.address);
1544 int newport = stoi(wide_to_narrow(menudata.port));
1547 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1549 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1550 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1551 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1552 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1553 g_settings->set("opaque_water", itos(menudata.opaque_water));
1554 g_settings->set("creative_mode", itos(menudata.creative_mode));
1555 g_settings->set("enable_damage", itos(menudata.enable_damage));
1556 g_settings->set("name", playername);
1557 g_settings->set("address", address);
1558 g_settings->set("port", itos(port));
1559 if(menudata.selected_world != -1)
1560 g_settings->set("selected_world_path",
1561 worldspecs[menudata.selected_world].path);
1563 // Break out of menu-game loop to shut down cleanly
1564 if(device->run() == false || kill == true)
1567 current_playername = playername;
1568 current_password = password;
1569 current_address = address;
1570 current_port = port;
1572 // If using simple singleplayer mode, override
1573 if(simple_singleplayer_mode){
1574 current_playername = "singleplayer";
1575 current_password = "";
1576 current_address = "";
1577 current_port = 30011;
1580 // Set world path to selected one
1581 if(menudata.selected_world != -1){
1582 worldspec = worldspecs[menudata.selected_world];
1583 infostream<<"Selected world: "<<worldspec.name
1584 <<" ["<<worldspec.path<<"]"<<std::endl;
1587 // Only refresh if so requested
1588 if(menudata.only_refresh){
1589 infostream<<"Refreshing menu"<<std::endl;
1593 // Create new world if requested
1594 if(menudata.create_world_name != L"")
1596 std::string path = porting::path_user + DIR_DELIM
1597 "worlds" + DIR_DELIM
1598 + wide_to_narrow(menudata.create_world_name);
1599 // Create world if it doesn't exist
1600 if(!initializeWorld(path, menudata.create_world_gameid)){
1601 error_message = L"Failed to initialize world";
1602 errorstream<<wide_to_narrow(error_message)<<std::endl;
1605 g_settings->set("selected_world_path", path);
1610 if(current_address == "")
1612 if(menudata.selected_world == -1){
1613 error_message = L"No world selected and no address "
1614 L"provided. Nothing to do.";
1615 errorstream<<wide_to_narrow(error_message)<<std::endl;
1618 // Load gamespec for required game
1619 gamespec = findWorldSubgame(worldspec.path);
1620 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1621 error_message = L"Could not find or load game \""
1622 + narrow_to_wide(worldspec.gameid) + L"\"";
1623 errorstream<<wide_to_narrow(error_message)<<std::endl;
1626 if(commanded_gamespec.isValid() &&
1627 commanded_gamespec.id != worldspec.gameid){
1628 errorstream<<"WARNING: Overriding gamespec from \""
1629 <<worldspec.gameid<<"\" to \""
1630 <<commanded_gamespec.id<<"\""<<std::endl;
1631 gamespec = commanded_gamespec;
1634 if(!gamespec.isValid()){
1635 error_message = L"Invalid gamespec. (world_gameid="
1636 +narrow_to_wide(worldspec.gameid)+L")";
1637 errorstream<<wide_to_narrow(error_message)<<std::endl;
1646 // Break out of menu-game loop to shut down cleanly
1647 if(device->run() == false || kill == true)
1668 simple_singleplayer_mode
1672 catch(con::PeerNotFoundException &e)
1674 error_message = L"Connection error (timed out?)";
1675 errorstream<<wide_to_narrow(error_message)<<std::endl;
1677 catch(ServerError &e)
1679 error_message = narrow_to_wide(e.what());
1680 errorstream<<wide_to_narrow(error_message)<<std::endl;
1684 errorstream<<e.what()<<std::endl;
1685 error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1688 catch(std::exception &e)
1690 std::string narrow_message = "Some exception, what()=\"";
1691 narrow_message += e.what();
1692 narrow_message += "\"";
1693 errorstream<<narrow_message<<std::endl;
1694 error_message = narrow_to_wide(narrow_message);
1698 // If no main menu, show error and exit
1701 if(error_message != L""){
1702 verbosestream<<"error_message = "
1703 <<wide_to_narrow(error_message)<<std::endl;
1713 In the end, delete the Irrlicht device.
1719 // Update configuration file
1720 if(configpath != "")
1721 g_settings->updateConfigFile(configpath.c_str());
1723 // Print modified quicktune values
1725 bool header_printed = false;
1726 std::vector<std::string> names = getQuicktuneNames();
1727 for(u32 i=0; i<names.size(); i++){
1728 QuicktuneValue val = getQuicktuneValue(names[i]);
1731 if(!header_printed){
1732 dstream<<"Modified quicktune values:"<<std::endl;
1733 header_printed = true;
1735 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1739 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1741 debugstreams_deinit();