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;
93 //std::ostream *dout_con_ptr = &infostream;
94 //std::ostream *derr_con_ptr = &errorstream;
97 std::ostream *dout_server_ptr = &infostream;
98 std::ostream *derr_server_ptr = &errorstream;
101 std::ostream *dout_client_ptr = &infostream;
102 std::ostream *derr_client_ptr = &errorstream;
109 /* mainmenumanager.h */
111 gui::IGUIEnvironment* guienv = NULL;
112 gui::IGUIStaticText *guiroot = NULL;
113 MainMenuManager g_menumgr;
117 return (g_menumgr.menuCount() == 0);
120 // Passed to menus to allow disconnecting and exiting
121 MainGameCallback *g_gamecallback = NULL;
125 gettime.h implementation
132 /* Use imprecise system calls directly (from porting.h) */
133 return porting::getTimeMs();
138 // A small helper class
142 virtual u32 getTime() = 0;
145 // A precise irrlicht one
146 class IrrlichtTimeGetter: public TimeGetter
149 IrrlichtTimeGetter(IrrlichtDevice *device):
156 return m_device->getTimer()->getRealTime();
159 IrrlichtDevice *m_device;
161 // Not so precise one which works without irrlicht
162 class SimpleTimeGetter: public TimeGetter
167 return porting::getTimeMs();
171 // A pointer to a global instance of the time getter
173 TimeGetter *g_timegetter = NULL;
177 if(g_timegetter == NULL)
179 return g_timegetter->getTime();
184 class StderrLogOutput: public ILogOutput
187 /* line: Full line with timestamp, level and thread */
188 void printLog(const std::string &line)
190 std::cerr<<line<<std::endl;
192 } main_stderr_log_out;
194 class DstreamNoStderrLogOutput: public ILogOutput
197 /* line: Full line with timestamp, level and thread */
198 void printLog(const std::string &line)
200 dstream_no_stderr<<line<<std::endl;
202 } main_dstream_no_stderr_log_out;
207 Event handler for Irrlicht
209 NOTE: Everything possible should be moved out from here,
210 probably to InputHandler and the_game
213 class MyEventReceiver : public IEventReceiver
216 // This is the one method that we have to implement
217 virtual bool OnEvent(const SEvent& event)
220 React to nothing here if a menu is active
222 if(noMenuActive() == false)
227 // Remember whether each key is down or up
228 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
230 if(event.KeyInput.PressedDown) {
231 keyIsDown.set(event.KeyInput);
232 keyWasDown.set(event.KeyInput);
234 keyIsDown.unset(event.KeyInput);
238 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
240 if(noMenuActive() == false)
243 middle_active = false;
244 right_active = false;
248 left_active = event.MouseInput.isLeftPressed();
249 middle_active = event.MouseInput.isMiddlePressed();
250 right_active = event.MouseInput.isRightPressed();
252 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
256 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
260 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
264 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
266 rightreleased = true;
268 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
270 mouse_wheel += event.MouseInput.Wheel;
278 bool IsKeyDown(const KeyPress &keyCode) const
280 return keyIsDown[keyCode];
283 // Checks whether a key was down and resets the state
284 bool WasKeyDown(const KeyPress &keyCode)
286 bool b = keyWasDown[keyCode];
288 keyWasDown.unset(keyCode);
305 rightclicked = false;
306 leftreleased = false;
307 rightreleased = false;
310 middle_active = false;
311 right_active = false;
333 IrrlichtDevice *m_device;
335 // The current state of keys
337 // Whether a key has been pressed or not
342 Separated input handler
345 class RealInputHandler : public InputHandler
348 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
353 virtual bool isKeyDown(const KeyPress &keyCode)
355 return m_receiver->IsKeyDown(keyCode);
357 virtual bool wasKeyDown(const KeyPress &keyCode)
359 return m_receiver->WasKeyDown(keyCode);
361 virtual v2s32 getMousePos()
363 return m_device->getCursorControl()->getPosition();
365 virtual void setMousePos(s32 x, s32 y)
367 m_device->getCursorControl()->setPosition(x, y);
370 virtual bool getLeftState()
372 return m_receiver->left_active;
374 virtual bool getRightState()
376 return m_receiver->right_active;
379 virtual bool getLeftClicked()
381 return m_receiver->leftclicked;
383 virtual bool getRightClicked()
385 return m_receiver->rightclicked;
387 virtual void resetLeftClicked()
389 m_receiver->leftclicked = false;
391 virtual void resetRightClicked()
393 m_receiver->rightclicked = false;
396 virtual bool getLeftReleased()
398 return m_receiver->leftreleased;
400 virtual bool getRightReleased()
402 return m_receiver->rightreleased;
404 virtual void resetLeftReleased()
406 m_receiver->leftreleased = false;
408 virtual void resetRightReleased()
410 m_receiver->rightreleased = false;
413 virtual s32 getMouseWheel()
415 return m_receiver->getMouseWheel();
420 m_receiver->clearInput();
423 IrrlichtDevice *m_device;
424 MyEventReceiver *m_receiver;
427 class RandomInputHandler : public InputHandler
435 rightclicked = false;
436 leftreleased = false;
437 rightreleased = false;
440 virtual bool isKeyDown(const KeyPress &keyCode)
442 return keydown[keyCode];
444 virtual bool wasKeyDown(const KeyPress &keyCode)
448 virtual v2s32 getMousePos()
452 virtual void setMousePos(s32 x, s32 y)
454 mousepos = v2s32(x,y);
457 virtual bool getLeftState()
461 virtual bool getRightState()
466 virtual bool getLeftClicked()
470 virtual bool getRightClicked()
474 virtual void resetLeftClicked()
478 virtual void resetRightClicked()
480 rightclicked = false;
483 virtual bool getLeftReleased()
487 virtual bool getRightReleased()
489 return rightreleased;
491 virtual void resetLeftReleased()
493 leftreleased = false;
495 virtual void resetRightReleased()
497 rightreleased = false;
500 virtual s32 getMouseWheel()
505 virtual void step(float dtime)
508 static float counter1 = 0;
512 counter1 = 0.1*Rand(1, 40);
513 keydown.toggle(getKeySetting("keymap_jump"));
517 static float counter1 = 0;
521 counter1 = 0.1*Rand(1, 40);
522 keydown.toggle(getKeySetting("keymap_special1"));
526 static float counter1 = 0;
530 counter1 = 0.1*Rand(1, 40);
531 keydown.toggle(getKeySetting("keymap_forward"));
535 static float counter1 = 0;
539 counter1 = 0.1*Rand(1, 40);
540 keydown.toggle(getKeySetting("keymap_left"));
544 static float counter1 = 0;
548 counter1 = 0.1*Rand(1, 20);
549 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
553 static float counter1 = 0;
557 counter1 = 0.1*Rand(1, 30);
558 leftdown = !leftdown;
566 static float counter1 = 0;
570 counter1 = 0.1*Rand(1, 15);
571 rightdown = !rightdown;
575 rightreleased = true;
578 mousepos += mousespeed;
581 s32 Rand(s32 min, s32 max)
583 return (myrand()%(max-min+1))+min;
597 void drawMenuBackground(video::IVideoDriver* driver)
599 core::dimension2d<u32> screensize = driver->getScreenSize();
601 video::ITexture *bgtexture =
602 driver->getTexture(getTexturePath("menubg.png").c_str());
605 s32 scaledsize = 128;
607 // The important difference between destsize and screensize is
608 // that destsize is rounded to whole scaled pixels.
609 // These formulas use component-wise multiplication and division of v2u32.
610 v2u32 texturesize = bgtexture->getSize();
611 v2u32 sourcesize = texturesize * screensize / scaledsize + v2u32(1,1);
612 v2u32 destsize = scaledsize * sourcesize / texturesize;
614 // Default texture wrapping mode in Irrlicht is ETC_REPEAT.
615 driver->draw2DImage(bgtexture,
616 core::rect<s32>(0, 0, destsize.X, destsize.Y),
617 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
621 video::ITexture *logotexture =
622 driver->getTexture(getTexturePath("menulogo.png").c_str());
625 v2s32 logosize(logotexture->getOriginalSize().Width,
626 logotexture->getOriginalSize().Height);
629 video::SColor bgcolor(255,50,50,50);
630 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
631 screensize.Width, screensize.Height);
632 driver->draw2DRectangle(bgcolor, bgrect, NULL);
634 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
635 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
636 rect -= v2s32(logosize.X/2, 0);
637 driver->draw2DImage(logotexture, rect,
638 core::rect<s32>(core::position2d<s32>(0,0),
639 core::dimension2di(logotexture->getSize())),
646 // These are defined global so that they're not optimized too much.
647 // Can't change them to volatile.
652 std::string tempstring;
653 std::string tempstring2;
658 infostream<<"The following test should take around 20ms."<<std::endl;
659 TimeTaker timer("Testing std::string speed");
660 const u32 jj = 10000;
661 for(u32 j=0; j<jj; j++)
666 for(u32 i=0; i<ii; i++){
667 tempstring2 += "asd";
669 for(u32 i=0; i<ii+1; i++){
671 if(tempstring == tempstring2)
677 infostream<<"All of the following tests should take around 100ms each."
681 TimeTaker timer("Testing floating-point conversion speed");
683 for(u32 i=0; i<4000000; i++){
690 TimeTaker timer("Testing floating-point vector speed");
692 tempv3f1 = v3f(1,2,3);
693 tempv3f2 = v3f(4,5,6);
694 for(u32 i=0; i<10000000; i++){
695 tempf += tempv3f1.dotProduct(tempv3f2);
696 tempv3f2 += v3f(7,8,9);
701 TimeTaker timer("Testing core::map speed");
703 core::map<v2s16, f32> map1;
706 for(s16 y=0; y<ii; y++){
707 for(s16 x=0; x<ii; x++){
708 map1.insert(v2s16(x,y), tempf);
712 for(s16 y=ii-1; y>=0; y--){
713 for(s16 x=0; x<ii; x++){
714 tempf = map1[v2s16(x,y)];
720 infostream<<"Around 5000/ms should do well here."<<std::endl;
721 TimeTaker timer("Testing mutex speed");
735 while(timer.getTime() < 10);
737 u32 dtime = timer.stop();
738 u32 per_ms = n / dtime;
739 infostream<<"Done. "<<dtime<<"ms, "
740 <<per_ms<<"/ms"<<std::endl;
744 int main(int argc, char *argv[])
752 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
753 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
755 log_register_thread("main");
757 // Set locale. This is for forcing '.' as the decimal point.
758 std::locale::global(std::locale("C"));
759 // This enables printing all characters in bitmap font
760 setlocale(LC_CTYPE, "en_US");
766 // List all allowed options
767 core::map<std::string, ValueSpec> allowed_options;
768 allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
769 "Show allowed options"));
770 allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
771 "Load configuration from specified file"));
772 allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
773 "Set network port (UDP)"));
774 allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
775 "Disable unit tests"));
776 allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
777 "Enable unit tests"));
778 allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
779 "Same as --world (deprecated)"));
780 allowed_options.insert("world", ValueSpec(VALUETYPE_STRING,
781 "Set world path (implies local game)"));
782 allowed_options.insert("verbose", ValueSpec(VALUETYPE_FLAG,
783 "Print more information to console"));
784 allowed_options.insert("logfile", ValueSpec(VALUETYPE_STRING,
785 "Set logfile path ('' = no logging)"));
786 allowed_options.insert("gameid", ValueSpec(VALUETYPE_STRING,
787 "Set gameid (\"--gameid list\" prints available ones)"));
789 allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
791 allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
792 "Address to connect to. ('' = local game)"));
793 allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
794 "Enable random user input, for testing"));
795 allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
796 "Run dedicated server"));
797 allowed_options.insert("name", ValueSpec(VALUETYPE_STRING,
799 allowed_options.insert("password", ValueSpec(VALUETYPE_STRING,
801 allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG,
802 "Disable main menu"));
807 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
809 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
811 dstream<<"Allowed options:"<<std::endl;
812 for(core::map<std::string, ValueSpec>::Iterator
813 i = allowed_options.getIterator();
814 i.atEnd() == false; i++)
816 std::ostringstream os1(std::ios::binary);
817 os1<<" --"<<i.getNode()->getKey();
818 if(i.getNode()->getValue().type == VALUETYPE_FLAG)
822 dstream<<padStringRight(os1.str(), 24);
824 if(i.getNode()->getValue().help != NULL)
825 dstream<<i.getNode()->getValue().help;
829 return cmd_args.getFlag("help") ? 0 : 1;
833 Low-level initialization
836 // In certain cases, output info level on stderr
837 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("speedtests"))
838 log_add_output(&main_stderr_log_out, LMT_INFO);
840 porting::signal_handler_init();
841 bool &kill = *porting::signal_handler_killstatus();
843 porting::initializePaths();
845 // Create user data directory
846 fs::CreateDir(porting::path_user);
848 init_gettext((porting::path_share+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
850 // Initialize debug streams
852 std::string logfile = DEBUGFILE;
854 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
856 if(cmd_args.exists("logfile"))
857 logfile = cmd_args.get("logfile");
859 debugstreams_init(false, logfile.c_str());
861 debugstreams_init(false, NULL);
863 infostream<<"logfile = "<<logfile<<std::endl;
864 infostream<<"path_share = "<<porting::path_share<<std::endl;
865 infostream<<"path_user = "<<porting::path_user<<std::endl;
867 // Initialize debug stacks
869 DSTACK(__FUNCTION_NAME);
872 BEGIN_DEBUG_EXCEPTION_HANDLER
874 // List gameids if requested
875 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
877 std::set<std::string> gameids = getAvailableGameIds();
878 for(std::set<std::string>::const_iterator i = gameids.begin();
879 i != gameids.end(); i++)
880 dstream<<(*i)<<std::endl;
884 // Print startup message
885 actionstream<<PROJECT_NAME<<
886 " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
894 // Initialize default settings
895 set_default_settings(g_settings);
897 // Initialize sockets
899 atexit(sockets_cleanup);
905 // Path of configuration file in use
906 std::string configpath = "";
908 if(cmd_args.exists("config"))
910 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
913 errorstream<<"Could not read configuration from \""
914 <<cmd_args.get("config")<<"\""<<std::endl;
917 configpath = cmd_args.get("config");
921 core::array<std::string> filenames;
922 filenames.push_back(porting::path_user +
923 DIR_DELIM + "minetest.conf");
924 // Legacy configuration file location
925 filenames.push_back(porting::path_user +
926 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
928 // Try also from a lower level (to aid having the same configuration
929 // for many RUN_IN_PLACE installs)
930 filenames.push_back(porting::path_user +
931 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
934 for(u32 i=0; i<filenames.size(); i++)
936 bool r = g_settings->readConfigFile(filenames[i].c_str());
939 configpath = filenames[i];
944 // If no path found, use the first one (menu creates the file)
946 configpath = filenames[0];
949 // Initialize random seed
957 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
958 || cmd_args.getFlag("enable-unittests") == true)
969 if(cmd_args.exists("port"))
970 port = cmd_args.getU16("port");
971 else if(g_settings->exists("port"))
972 port = g_settings->getU16("port");
977 std::string commanded_world = "";
978 if(cmd_args.exists("world"))
979 commanded_world = cmd_args.get("world");
980 else if(cmd_args.exists("map-dir"))
981 commanded_world = cmd_args.get("map-dir");
982 else if(cmd_args.exists("nonopt0"))
983 commanded_world = cmd_args.get("nonopt0");
984 else if(g_settings->exists("map-dir"))
985 commanded_world = g_settings->get("map-dir");
987 // Strip world.mt from commanded_world
989 std::string worldmt = "world.mt";
990 if(commanded_world.size() > worldmt.size() &&
991 commanded_world.substr(commanded_world.size()-worldmt.size())
993 dstream<<"Supplied world.mt file - stripping it off."<<std::endl;
994 commanded_world = commanded_world.substr(
995 0, commanded_world.size()-worldmt.size());
1000 SubgameSpec commanded_gamespec;
1001 if(cmd_args.exists("gameid")){
1002 std::string gameid = cmd_args.get("gameid");
1003 commanded_gamespec = findSubgame(gameid);
1004 if(!commanded_gamespec.isValid()){
1005 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1011 Run dedicated server if asked to or no other option
1014 bool run_dedicated_server = true;
1016 bool run_dedicated_server = cmd_args.getFlag("server");
1018 if(run_dedicated_server)
1020 DSTACK("Dedicated server branch");
1021 // Create time getter if built with Irrlicht
1023 g_timegetter = new SimpleTimeGetter();
1027 std::string world_path;
1028 bool is_legacy_world = false;
1029 if(commanded_world != ""){
1030 world_path = commanded_world;
1033 // No specific world was commanded
1034 // Check if the world is found from the default directory, and if
1035 // not, see if the legacy world directory exists.
1036 world_path = porting::path_user + DIR_DELIM + "server" + DIR_DELIM + "worlds" + DIR_DELIM + "world";
1037 std::string legacy_world_path = porting::path_user+DIR_DELIM+".."+DIR_DELIM+"world";
1038 if(!fs::PathExists(world_path) && fs::PathExists(legacy_world_path)){
1039 errorstream<<"Warning: Using legacy world directory \""
1040 <<legacy_world_path<<"\""<<std::endl;
1041 world_path = legacy_world_path;
1042 is_legacy_world = true;
1047 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1048 SubgameSpec gamespec = findSubgame(world_gameid);
1049 if(commanded_gamespec.isValid() &&
1050 commanded_gamespec.id != world_gameid){
1051 errorstream<<"WARNING: Overriding gameid from \""
1052 <<world_gameid<<"\" to \""
1053 <<commanded_gamespec.id<<"\""<<std::endl;
1054 gamespec = commanded_gamespec;
1057 if(!gamespec.isValid()){
1058 errorstream<<"Invalid gamespec. (world_gameid="
1059 <<world_gameid<<")"<<std::endl;
1063 infostream<<"Using gamespec \""<<gamespec.id<<"\""<<std::endl;
1066 Server server(world_path, configpath, gamespec);
1070 dedicated_server_loop(server, kill);
1075 #ifndef SERVER // Exclude from dedicated server build
1081 std::string address = g_settings->get("address");
1082 if(commanded_world != "")
1084 else if(cmd_args.exists("address"))
1085 address = cmd_args.get("address");
1086 else if(cmd_args.exists("world"))
1089 std::string playername = g_settings->get("name");
1090 if(cmd_args.exists("name"))
1091 playername = cmd_args.get("name");
1093 bool skip_main_menu = cmd_args.getFlag("go");
1096 Device initialization
1099 // Resolution selection
1101 bool fullscreen = false;
1102 u16 screenW = g_settings->getU16("screenW");
1103 u16 screenH = g_settings->getU16("screenH");
1107 video::E_DRIVER_TYPE driverType;
1109 std::string driverstring = g_settings->get("video_driver");
1111 if(driverstring == "null")
1112 driverType = video::EDT_NULL;
1113 else if(driverstring == "software")
1114 driverType = video::EDT_SOFTWARE;
1115 else if(driverstring == "burningsvideo")
1116 driverType = video::EDT_BURNINGSVIDEO;
1117 else if(driverstring == "direct3d8")
1118 driverType = video::EDT_DIRECT3D8;
1119 else if(driverstring == "direct3d9")
1120 driverType = video::EDT_DIRECT3D9;
1121 else if(driverstring == "opengl")
1122 driverType = video::EDT_OPENGL;
1125 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1126 "to opengl"<<std::endl;
1127 driverType = video::EDT_OPENGL;
1131 Create device and exit if creation failed
1134 MyEventReceiver receiver;
1136 IrrlichtDevice *device;
1137 device = createDevice(driverType,
1138 core::dimension2d<u32>(screenW, screenH),
1139 16, fullscreen, false, false, &receiver);
1142 return 1; // could not create selected driver.
1145 Continue initialization
1148 video::IVideoDriver* driver = device->getVideoDriver();
1150 // Disable mipmaps (because some of them look ugly)
1151 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1154 This changes the minimum allowed number of vertices in a VBO.
1157 //driver->setMinHardwareBufferVertexCount(50);
1159 // Create time getter
1160 g_timegetter = new IrrlichtTimeGetter(device);
1162 // Create game callback for menus
1163 g_gamecallback = new MainGameCallback(device);
1166 Speed tests (done after irrlicht is loaded to get timer)
1168 if(cmd_args.getFlag("speedtests"))
1170 dstream<<"Running speed tests"<<std::endl;
1175 device->setResizable(true);
1177 bool random_input = g_settings->getBool("random_input")
1178 || cmd_args.getFlag("random-input");
1179 InputHandler *input = NULL;
1181 input = new RandomInputHandler();
1183 input = new RealInputHandler(device, &receiver);
1185 scene::ISceneManager* smgr = device->getSceneManager();
1187 guienv = device->getGUIEnvironment();
1188 gui::IGUISkin* skin = guienv->getSkin();
1189 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1191 skin->setFont(font);
1193 errorstream<<"WARNING: Font file was not found."
1194 " Using default font."<<std::endl;
1195 // If font was not found, this will get us one
1196 font = skin->getFont();
1199 u32 text_height = font->getDimension(L"Hello, world!").Height;
1200 infostream<<"text_height="<<text_height<<std::endl;
1202 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1203 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1204 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1205 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1206 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1207 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1208 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1209 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1215 ChatBackend chat_backend;
1218 If an error occurs, this is set to something and the
1219 menu-game loop is restarted. It is then displayed before
1222 std::wstring error_message = L"";
1224 // The password entered during the menu screen,
1225 std::string password;
1227 bool first_loop = true;
1232 while(device->run() && kill == false)
1234 // Set the window caption
1235 device->setWindowCaption(L"Minetest [Main Menu]");
1237 // This is used for catching disconnects
1242 Clear everything from the GUIEnvironment
1247 We need some kind of a root node to be able to add
1248 custom gui elements directly on the screen.
1249 Otherwise they won't be automatically drawn.
1251 guiroot = guienv->addStaticText(L"",
1252 core::rect<s32>(0, 0, 10000, 10000));
1254 SubgameSpec gamespec;
1255 WorldSpec worldspec;
1258 Out-of-game menu loop.
1260 Loop quits when menu returns proper parameters.
1262 while(kill == false)
1264 // If skip_main_menu, only go through here once
1265 if(skip_main_menu && !first_loop){
1271 // Cursor can be non-visible when coming from the game
1272 device->getCursorControl()->setVisible(true);
1273 // Some stuff are left to scene manager when coming from the game
1277 // Initialize menu data
1278 MainMenuData menudata;
1279 menudata.address = narrow_to_wide(address);
1280 menudata.name = narrow_to_wide(playername);
1281 menudata.port = narrow_to_wide(itos(port));
1282 if(cmd_args.exists("password"))
1283 menudata.password = narrow_to_wide(cmd_args.get("password"));
1284 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1285 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1286 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1287 menudata.opaque_water = g_settings->getBool("opaque_water");
1288 menudata.creative_mode = g_settings->getBool("creative_mode");
1289 menudata.enable_damage = g_settings->getBool("enable_damage");
1290 // Default to selecting nothing
1291 menudata.selected_world = -1;
1292 // Get world listing for the menu
1293 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1294 // If there is only one world, select it
1295 if(worldspecs.size() == 1){
1296 menudata.selected_world = 0;
1298 // Otherwise try to select according to selected_world_path
1299 else if(g_settings->exists("selected_world_path")){
1300 std::string trypath = g_settings->get("selected_world_path");
1301 for(u32 i=0; i<worldspecs.size(); i++){
1302 if(worldspecs[i].path == trypath){
1303 menudata.selected_world = i;
1308 // If a world was commanded, append and select it
1309 if(commanded_world != ""){
1310 std::string gameid = getWorldGameId(commanded_world, true);
1312 gameid = g_settings->get("default_game");
1313 WorldSpec spec(commanded_world, "[--world parameter]",
1315 worldspecs.push_back(spec);
1316 menudata.selected_world = worldspecs.size()-1;
1318 // Copy worldspecs to menu
1319 menudata.worlds = worldspecs;
1321 if(skip_main_menu == false)
1324 new GUIMainMenu(guienv, guiroot, -1,
1325 &g_menumgr, &menudata, g_gamecallback);
1326 menu->allowFocusRemoval(true);
1328 if(error_message != L"")
1330 verbosestream<<"error_message = "
1331 <<wide_to_narrow(error_message)<<std::endl;
1333 GUIMessageMenu *menu2 =
1334 new GUIMessageMenu(guienv, guiroot, -1,
1335 &g_menumgr, error_message.c_str());
1337 error_message = L"";
1340 video::IVideoDriver* driver = device->getVideoDriver();
1342 infostream<<"Created main menu"<<std::endl;
1344 while(device->run() && kill == false)
1346 if(menu->getStatus() == true)
1349 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1350 driver->beginScene(true, true, video::SColor(255,128,128,128));
1352 drawMenuBackground(driver);
1358 // On some computers framerate doesn't seem to be
1359 // automatically limited
1363 // Break out of menu-game loop to shut down cleanly
1364 if(device->run() == false || kill == true)
1367 infostream<<"Dropping main menu"<<std::endl;
1372 // Set world path to selected one
1373 if(menudata.selected_world != -1){
1374 worldspec = worldspecs[menudata.selected_world];
1375 infostream<<"Selected world: "<<worldspec.name
1376 <<" ["<<worldspec.path<<"]"<<std::endl;
1379 // Delete world if requested
1380 if(menudata.delete_world_spec.isValid())
1382 bool r = fs::RecursiveDeleteContent(
1383 menudata.delete_world_spec.path);
1385 error_message = L"World delete failed";
1386 errorstream<<wide_to_narrow(error_message)<<std::endl;
1391 // Create new world if requested
1392 if(menudata.create_world_name != L"")
1394 std::string path = porting::path_user + DIR_DELIM
1395 + "server" + DIR_DELIM + "worlds" + DIR_DELIM
1396 + wide_to_narrow(menudata.create_world_name);
1397 // Create world if it doesn't exist
1398 if(!initializeWorld(path, menudata.create_world_gameid)){
1399 error_message = L"Failed to initialize world";
1400 errorstream<<wide_to_narrow(error_message)<<std::endl;
1403 g_settings->set("selected_world_path", path);
1407 playername = wide_to_narrow(menudata.name);
1408 password = translatePassword(playername, menudata.password);
1409 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1411 address = wide_to_narrow(menudata.address);
1412 int newport = stoi(wide_to_narrow(menudata.port));
1416 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1417 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1418 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1419 g_settings->set("opaque_water", itos(menudata.opaque_water));
1420 g_settings->set("creative_mode", itos(menudata.creative_mode));
1421 g_settings->set("enable_damage", itos(menudata.enable_damage));
1422 g_settings->set("name", playername);
1423 g_settings->set("address", address);
1424 g_settings->set("port", itos(port));
1425 if(menudata.selected_world != -1)
1426 g_settings->set("selected_world_path",
1427 worldspecs[menudata.selected_world].path);
1428 // Update configuration file
1429 if(configpath != "")
1430 g_settings->updateConfigFile(configpath.c_str());
1435 if(menudata.selected_world == -1){
1436 error_message = L"No world selected and no address "
1437 L"provided. Nothing to do.";
1438 errorstream<<wide_to_narrow(error_message)<<std::endl;
1441 // Load gamespec for required game
1442 gamespec = findSubgame(worldspec.gameid);
1443 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1444 error_message = L"Could not find or load game \""
1445 + narrow_to_wide(worldspec.gameid) + L"\"";
1446 errorstream<<wide_to_narrow(error_message)<<std::endl;
1449 if(commanded_gamespec.isValid() &&
1450 commanded_gamespec.id != worldspec.gameid){
1451 errorstream<<"WARNING: Overriding gamespec from \""
1452 <<worldspec.gameid<<"\" to \""
1453 <<commanded_gamespec.id<<"\""<<std::endl;
1454 gamespec = commanded_gamespec;
1457 if(!gamespec.isValid()){
1458 error_message = L"Invalid gamespec. (world_gameid="
1459 +narrow_to_wide(worldspec.gameid)+L")";
1460 errorstream<<wide_to_narrow(error_message)<<std::endl;
1469 // Break out of menu-game loop to shut down cleanly
1470 if(device->run() == false || kill == true)
1494 catch(con::PeerNotFoundException &e)
1496 error_message = L"Connection error (timed out?)";
1497 errorstream<<wide_to_narrow(error_message)<<std::endl;
1499 catch(ServerError &e)
1501 error_message = narrow_to_wide(e.what());
1502 errorstream<<wide_to_narrow(error_message)<<std::endl;
1506 errorstream<<e.what()<<std::endl;
1507 error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1510 catch(std::exception &e)
1512 std::string narrow_message = "Some exception, what()=\"";
1513 narrow_message += e.what();
1514 narrow_message += "\"";
1515 errorstream<<narrow_message<<std::endl;
1516 error_message = narrow_to_wide(narrow_message);
1520 // If no main menu, show error and exit
1523 if(error_message != L""){
1524 verbosestream<<"error_message = "
1525 <<wide_to_narrow(error_message)<<std::endl;
1535 In the end, delete the Irrlicht device.
1541 // Update configuration file
1542 if(configpath != "")
1543 g_settings->updateConfigFile(configpath.c_str());
1545 // Print modified quicktune values
1547 bool header_printed = false;
1548 std::vector<std::string> names = getQuicktuneNames();
1549 for(u32 i=0; i<names.size(); i++){
1550 QuicktuneValue val = getQuicktuneValue(names[i]);
1553 if(!header_printed){
1554 dstream<<"Modified quicktune values:"<<std::endl;
1555 header_printed = true;
1557 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1561 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1563 debugstreams_deinit();