]> git.lizzy.rs Git - dragonfireclient.git/blob - src/main.cpp
Fullscreen, vsync, fullscreen_bpp and fsaa options in the config; fsaa is experimenta...
[dragonfireclient.git] / src / main.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #ifdef NDEBUG
21         /*#ifdef _WIN32
22                 #pragma message ("Disabling unit tests")
23         #else
24                 #warning "Disabling unit tests"
25         #endif*/
26         // Disable unit tests
27         #define ENABLE_TESTS 0
28 #else
29         // Enable unit tests
30         #define ENABLE_TESTS 1
31 #endif
32
33 #ifdef _MSC_VER
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")
38 #endif
39         #pragma comment(lib, "zlibwapi.lib")
40         #pragma comment(lib, "Shell32.lib")
41 #endif
42
43 #include "irrlicht.h" // createDevice
44
45 #include "main.h"
46 #include "mainmenumanager.h"
47 #include <iostream>
48 #include <fstream>
49 #include <locale.h>
50 #include "common_irrlicht.h"
51 #include "debug.h"
52 #include "test.h"
53 #include "server.h"
54 #include "constants.h"
55 #include "porting.h"
56 #include "gettime.h"
57 #include "guiMessageMenu.h"
58 #include "filesys.h"
59 #include "config.h"
60 #include "guiMainMenu.h"
61 #include "game.h"
62 #include "keycode.h"
63 #include "tile.h"
64 #include "chat.h"
65 #include "defaultsettings.h"
66 #include "gettext.h"
67 #include "settings.h"
68 #include "profiler.h"
69 #include "log.h"
70 #include "mods.h"
71 #include "utility_string.h"
72 #include "subgame.h"
73 #include "quicktune.h"
74
75 /*
76         Settings.
77         These are loaded from the config file.
78 */
79 Settings main_settings;
80 Settings *g_settings = &main_settings;
81
82 // Global profiler
83 Profiler main_profiler;
84 Profiler *g_profiler = &main_profiler;
85
86 /*
87         Debug streams
88 */
89
90 // Connection
91 std::ostream *dout_con_ptr = &dummyout;
92 std::ostream *derr_con_ptr = &verbosestream;
93
94 // Server
95 std::ostream *dout_server_ptr = &infostream;
96 std::ostream *derr_server_ptr = &errorstream;
97
98 // Client
99 std::ostream *dout_client_ptr = &infostream;
100 std::ostream *derr_client_ptr = &errorstream;
101
102 #ifndef SERVER
103 /*
104         Random stuff
105 */
106
107 /* mainmenumanager.h */
108
109 gui::IGUIEnvironment* guienv = NULL;
110 gui::IGUIStaticText *guiroot = NULL;
111 MainMenuManager g_menumgr;
112
113 bool noMenuActive()
114 {
115         return (g_menumgr.menuCount() == 0);
116 }
117
118 // Passed to menus to allow disconnecting and exiting
119 MainGameCallback *g_gamecallback = NULL;
120 #endif
121
122 /*
123         gettime.h implementation
124 */
125
126 #ifdef SERVER
127
128 u32 getTimeMs()
129 {
130         /* Use imprecise system calls directly (from porting.h) */
131         return porting::getTimeMs();
132 }
133
134 #else
135
136 // A small helper class
137 class TimeGetter
138 {
139 public:
140         virtual u32 getTime() = 0;
141 };
142
143 // A precise irrlicht one
144 class IrrlichtTimeGetter: public TimeGetter
145 {
146 public:
147         IrrlichtTimeGetter(IrrlichtDevice *device):
148                 m_device(device)
149         {}
150         u32 getTime()
151         {
152                 if(m_device == NULL)
153                         return 0;
154                 return m_device->getTimer()->getRealTime();
155         }
156 private:
157         IrrlichtDevice *m_device;
158 };
159 // Not so precise one which works without irrlicht
160 class SimpleTimeGetter: public TimeGetter
161 {
162 public:
163         u32 getTime()
164         {
165                 return porting::getTimeMs();
166         }
167 };
168
169 // A pointer to a global instance of the time getter
170 // TODO: why?
171 TimeGetter *g_timegetter = NULL;
172
173 u32 getTimeMs()
174 {
175         if(g_timegetter == NULL)
176                 return 0;
177         return g_timegetter->getTime();
178 }
179
180 #endif
181
182 class StderrLogOutput: public ILogOutput
183 {
184 public:
185         /* line: Full line with timestamp, level and thread */
186         void printLog(const std::string &line)
187         {
188                 std::cerr<<line<<std::endl;
189         }
190 } main_stderr_log_out;
191
192 class DstreamNoStderrLogOutput: public ILogOutput
193 {
194 public:
195         /* line: Full line with timestamp, level and thread */
196         void printLog(const std::string &line)
197         {
198                 dstream_no_stderr<<line<<std::endl;
199         }
200 } main_dstream_no_stderr_log_out;
201
202 #ifndef SERVER
203
204 /*
205         Event handler for Irrlicht
206
207         NOTE: Everything possible should be moved out from here,
208               probably to InputHandler and the_game
209 */
210
211 class MyEventReceiver : public IEventReceiver
212 {
213 public:
214         // This is the one method that we have to implement
215         virtual bool OnEvent(const SEvent& event)
216         {
217                 /*
218                         React to nothing here if a menu is active
219                 */
220                 if(noMenuActive() == false)
221                 {
222                         return false;
223                 }
224
225                 // Remember whether each key is down or up
226                 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
227                 {
228                         if(event.KeyInput.PressedDown) {
229                                 keyIsDown.set(event.KeyInput);
230                                 keyWasDown.set(event.KeyInput);
231                         } else {
232                                 keyIsDown.unset(event.KeyInput);
233                         }
234                 }
235
236                 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
237                 {
238                         if(noMenuActive() == false)
239                         {
240                                 left_active = false;
241                                 middle_active = false;
242                                 right_active = false;
243                         }
244                         else
245                         {
246                                 left_active = event.MouseInput.isLeftPressed();
247                                 middle_active = event.MouseInput.isMiddlePressed();
248                                 right_active = event.MouseInput.isRightPressed();
249
250                                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
251                                 {
252                                         leftclicked = true;
253                                 }
254                                 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
255                                 {
256                                         rightclicked = true;
257                                 }
258                                 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
259                                 {
260                                         leftreleased = true;
261                                 }
262                                 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
263                                 {
264                                         rightreleased = true;
265                                 }
266                                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
267                                 {
268                                         mouse_wheel += event.MouseInput.Wheel;
269                                 }
270                         }
271                 }
272
273                 return false;
274         }
275
276         bool IsKeyDown(const KeyPress &keyCode) const
277         {
278                 return keyIsDown[keyCode];
279         }
280         
281         // Checks whether a key was down and resets the state
282         bool WasKeyDown(const KeyPress &keyCode)
283         {
284                 bool b = keyWasDown[keyCode];
285                 if (b)
286                         keyWasDown.unset(keyCode);
287                 return b;
288         }
289
290         s32 getMouseWheel()
291         {
292                 s32 a = mouse_wheel;
293                 mouse_wheel = 0;
294                 return a;
295         }
296
297         void clearInput()
298         {
299                 keyIsDown.clear();
300                 keyWasDown.clear();
301
302                 leftclicked = false;
303                 rightclicked = false;
304                 leftreleased = false;
305                 rightreleased = false;
306
307                 left_active = false;
308                 middle_active = false;
309                 right_active = false;
310
311                 mouse_wheel = 0;
312         }
313
314         MyEventReceiver()
315         {
316                 clearInput();
317         }
318
319         bool leftclicked;
320         bool rightclicked;
321         bool leftreleased;
322         bool rightreleased;
323
324         bool left_active;
325         bool middle_active;
326         bool right_active;
327
328         s32 mouse_wheel;
329
330 private:
331         IrrlichtDevice *m_device;
332         
333         // The current state of keys
334         KeyList keyIsDown;
335         // Whether a key has been pressed or not
336         KeyList keyWasDown;
337 };
338
339 /*
340         Separated input handler
341 */
342
343 class RealInputHandler : public InputHandler
344 {
345 public:
346         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
347                 m_device(device),
348                 m_receiver(receiver)
349         {
350         }
351         virtual bool isKeyDown(const KeyPress &keyCode)
352         {
353                 return m_receiver->IsKeyDown(keyCode);
354         }
355         virtual bool wasKeyDown(const KeyPress &keyCode)
356         {
357                 return m_receiver->WasKeyDown(keyCode);
358         }
359         virtual v2s32 getMousePos()
360         {
361                 return m_device->getCursorControl()->getPosition();
362         }
363         virtual void setMousePos(s32 x, s32 y)
364         {
365                 m_device->getCursorControl()->setPosition(x, y);
366         }
367
368         virtual bool getLeftState()
369         {
370                 return m_receiver->left_active;
371         }
372         virtual bool getRightState()
373         {
374                 return m_receiver->right_active;
375         }
376         
377         virtual bool getLeftClicked()
378         {
379                 return m_receiver->leftclicked;
380         }
381         virtual bool getRightClicked()
382         {
383                 return m_receiver->rightclicked;
384         }
385         virtual void resetLeftClicked()
386         {
387                 m_receiver->leftclicked = false;
388         }
389         virtual void resetRightClicked()
390         {
391                 m_receiver->rightclicked = false;
392         }
393
394         virtual bool getLeftReleased()
395         {
396                 return m_receiver->leftreleased;
397         }
398         virtual bool getRightReleased()
399         {
400                 return m_receiver->rightreleased;
401         }
402         virtual void resetLeftReleased()
403         {
404                 m_receiver->leftreleased = false;
405         }
406         virtual void resetRightReleased()
407         {
408                 m_receiver->rightreleased = false;
409         }
410
411         virtual s32 getMouseWheel()
412         {
413                 return m_receiver->getMouseWheel();
414         }
415
416         void clear()
417         {
418                 m_receiver->clearInput();
419         }
420 private:
421         IrrlichtDevice *m_device;
422         MyEventReceiver *m_receiver;
423 };
424
425 class RandomInputHandler : public InputHandler
426 {
427 public:
428         RandomInputHandler()
429         {
430                 leftdown = false;
431                 rightdown = false;
432                 leftclicked = false;
433                 rightclicked = false;
434                 leftreleased = false;
435                 rightreleased = false;
436                 keydown.clear();
437         }
438         virtual bool isKeyDown(const KeyPress &keyCode)
439         {
440                 return keydown[keyCode];
441         }
442         virtual bool wasKeyDown(const KeyPress &keyCode)
443         {
444                 return false;
445         }
446         virtual v2s32 getMousePos()
447         {
448                 return mousepos;
449         }
450         virtual void setMousePos(s32 x, s32 y)
451         {
452                 mousepos = v2s32(x,y);
453         }
454
455         virtual bool getLeftState()
456         {
457                 return leftdown;
458         }
459         virtual bool getRightState()
460         {
461                 return rightdown;
462         }
463
464         virtual bool getLeftClicked()
465         {
466                 return leftclicked;
467         }
468         virtual bool getRightClicked()
469         {
470                 return rightclicked;
471         }
472         virtual void resetLeftClicked()
473         {
474                 leftclicked = false;
475         }
476         virtual void resetRightClicked()
477         {
478                 rightclicked = false;
479         }
480
481         virtual bool getLeftReleased()
482         {
483                 return leftreleased;
484         }
485         virtual bool getRightReleased()
486         {
487                 return rightreleased;
488         }
489         virtual void resetLeftReleased()
490         {
491                 leftreleased = false;
492         }
493         virtual void resetRightReleased()
494         {
495                 rightreleased = false;
496         }
497
498         virtual s32 getMouseWheel()
499         {
500                 return 0;
501         }
502
503         virtual void step(float dtime)
504         {
505                 {
506                         static float counter1 = 0;
507                         counter1 -= dtime;
508                         if(counter1 < 0.0)
509                         {
510                                 counter1 = 0.1*Rand(1, 40);
511                                 keydown.toggle(getKeySetting("keymap_jump"));
512                         }
513                 }
514                 {
515                         static float counter1 = 0;
516                         counter1 -= dtime;
517                         if(counter1 < 0.0)
518                         {
519                                 counter1 = 0.1*Rand(1, 40);
520                                 keydown.toggle(getKeySetting("keymap_special1"));
521                         }
522                 }
523                 {
524                         static float counter1 = 0;
525                         counter1 -= dtime;
526                         if(counter1 < 0.0)
527                         {
528                                 counter1 = 0.1*Rand(1, 40);
529                                 keydown.toggle(getKeySetting("keymap_forward"));
530                         }
531                 }
532                 {
533                         static float counter1 = 0;
534                         counter1 -= dtime;
535                         if(counter1 < 0.0)
536                         {
537                                 counter1 = 0.1*Rand(1, 40);
538                                 keydown.toggle(getKeySetting("keymap_left"));
539                         }
540                 }
541                 {
542                         static float counter1 = 0;
543                         counter1 -= dtime;
544                         if(counter1 < 0.0)
545                         {
546                                 counter1 = 0.1*Rand(1, 20);
547                                 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
548                         }
549                 }
550                 {
551                         static float counter1 = 0;
552                         counter1 -= dtime;
553                         if(counter1 < 0.0)
554                         {
555                                 counter1 = 0.1*Rand(1, 30);
556                                 leftdown = !leftdown;
557                                 if(leftdown)
558                                         leftclicked = true;
559                                 if(!leftdown)
560                                         leftreleased = true;
561                         }
562                 }
563                 {
564                         static float counter1 = 0;
565                         counter1 -= dtime;
566                         if(counter1 < 0.0)
567                         {
568                                 counter1 = 0.1*Rand(1, 15);
569                                 rightdown = !rightdown;
570                                 if(rightdown)
571                                         rightclicked = true;
572                                 if(!rightdown)
573                                         rightreleased = true;
574                         }
575                 }
576                 mousepos += mousespeed;
577         }
578
579         s32 Rand(s32 min, s32 max)
580         {
581                 return (myrand()%(max-min+1))+min;
582         }
583 private:
584         KeyList keydown;
585         v2s32 mousepos;
586         v2s32 mousespeed;
587         bool leftdown;
588         bool rightdown;
589         bool leftclicked;
590         bool rightclicked;
591         bool leftreleased;
592         bool rightreleased;
593 };
594
595 void drawMenuBackground(video::IVideoDriver* driver)
596 {
597         core::dimension2d<u32> screensize = driver->getScreenSize();
598                 
599         video::ITexture *bgtexture =
600                         driver->getTexture(getTexturePath("menubg.png").c_str());
601         if(bgtexture)
602         {
603                 s32 scaledsize = 128;
604                 
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;
611                 
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),
616                         NULL, NULL, true);
617         }
618         
619         video::ITexture *logotexture =
620                         driver->getTexture(getTexturePath("menulogo.png").c_str());
621         if(logotexture)
622         {
623                 v2s32 logosize(logotexture->getOriginalSize().Width,
624                                 logotexture->getOriginalSize().Height);
625                 logosize *= 4;
626
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);
631
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())),
638                         NULL, NULL, true);
639         }
640 }
641
642 #endif
643
644 // These are defined global so that they're not optimized too much.
645 // Can't change them to volatile.
646 s16 temp16;
647 f32 tempf;
648 v3f tempv3f1;
649 v3f tempv3f2;
650 std::string tempstring;
651 std::string tempstring2;
652
653 void SpeedTests()
654 {
655         {
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++)
660                 {
661                         tempstring = "";
662                         tempstring2 = "";
663                         const u32 ii = 10;
664                         for(u32 i=0; i<ii; i++){
665                                 tempstring2 += "asd";
666                         }
667                         for(u32 i=0; i<ii+1; i++){
668                                 tempstring += "asd";
669                                 if(tempstring == tempstring2)
670                                         break;
671                         }
672                 }
673         }
674         
675         infostream<<"All of the following tests should take around 100ms each."
676                         <<std::endl;
677
678         {
679                 TimeTaker timer("Testing floating-point conversion speed");
680                 tempf = 0.001;
681                 for(u32 i=0; i<4000000; i++){
682                         temp16 += tempf;
683                         tempf += 0.001;
684                 }
685         }
686         
687         {
688                 TimeTaker timer("Testing floating-point vector speed");
689
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);
695                 }
696         }
697
698         {
699                 TimeTaker timer("Testing core::map speed");
700                 
701                 core::map<v2s16, f32> map1;
702                 tempf = -324;
703                 const s16 ii=300;
704                 for(s16 y=0; y<ii; y++){
705                         for(s16 x=0; x<ii; x++){
706                                 map1.insert(v2s16(x,y), tempf);
707                                 tempf += 1;
708                         }
709                 }
710                 for(s16 y=ii-1; y>=0; y--){
711                         for(s16 x=0; x<ii; x++){
712                                 tempf = map1[v2s16(x,y)];
713                         }
714                 }
715         }
716
717         {
718                 infostream<<"Around 5000/ms should do well here."<<std::endl;
719                 TimeTaker timer("Testing mutex speed");
720                 
721                 JMutex m;
722                 m.Init();
723                 u32 n = 0;
724                 u32 i = 0;
725                 do{
726                         n += 10000;
727                         for(; i<n; i++){
728                                 m.Lock();
729                                 m.Unlock();
730                         }
731                 }
732                 // Do at least 10ms
733                 while(timer.getTime() < 10);
734
735                 u32 dtime = timer.stop();
736                 u32 per_ms = n / dtime;
737                 infostream<<"Done. "<<dtime<<"ms, "
738                                 <<per_ms<<"/ms"<<std::endl;
739         }
740 }
741
742 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
743                 std::ostream &os)
744 {
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;
753         }
754 }
755
756 int main(int argc, char *argv[])
757 {
758         int retval = 0;
759
760         /*
761                 Initialization
762         */
763
764         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
765         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
766
767         log_register_thread("main");
768
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");
773
774         /*
775                 Parse command line
776         */
777         
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)"));
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)"));
806 #ifndef SERVER
807         allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
808                         "Run speed tests"));
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,
816                         "Set player name"));
817         allowed_options.insert("password", ValueSpec(VALUETYPE_STRING,
818                         "Set password"));
819         allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG,
820                         "Disable main menu"));
821 #endif
822
823         Settings cmd_args;
824         
825         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
826
827         if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
828         {
829                 dstream<<"Allowed options:"<<std::endl;
830                 for(core::map<std::string, ValueSpec>::Iterator
831                                 i = allowed_options.getIterator();
832                                 i.atEnd() == false; i++)
833                 {
834                         std::ostringstream os1(std::ios::binary);
835                         os1<<"  --"<<i.getNode()->getKey();
836                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
837                                 {}
838                         else
839                                 os1<<" <value>";
840                         dstream<<padStringRight(os1.str(), 24);
841
842                         if(i.getNode()->getValue().help != NULL)
843                                 dstream<<i.getNode()->getValue().help;
844                         dstream<<std::endl;
845                 }
846
847                 return cmd_args.getFlag("help") ? 0 : 1;
848         }
849         
850         /*
851                 Low-level initialization
852         */
853         
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                 dout_con_ptr = &verbosestream;
858                 socket_enable_debug_output = true;
859         }
860         // In certain cases, output info level on stderr
861         if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
862                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
863                 log_add_output(&main_stderr_log_out, LMT_INFO);
864         // In certain cases, output verbose level on stderr
865         if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
866                 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
867
868         porting::signal_handler_init();
869         bool &kill = *porting::signal_handler_killstatus();
870         
871         porting::initializePaths();
872
873         // Create user data directory
874         fs::CreateDir(porting::path_user);
875
876         init_gettext((porting::path_share+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
877         
878         // Initialize debug streams
879 #ifdef RUN_IN_PLACE
880         std::string logfile = DEBUGFILE;
881 #else
882         std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
883 #endif
884         if(cmd_args.exists("logfile"))
885                 logfile = cmd_args.get("logfile");
886         if(logfile != "")
887                 debugstreams_init(false, logfile.c_str());
888         else
889                 debugstreams_init(false, NULL);
890
891         infostream<<"logfile    = "<<logfile<<std::endl;
892         infostream<<"path_share = "<<porting::path_share<<std::endl;
893         infostream<<"path_user  = "<<porting::path_user<<std::endl;
894
895         // Initialize debug stacks
896         debug_stacks_init();
897         DSTACK(__FUNCTION_NAME);
898
899         // Debug handler
900         BEGIN_DEBUG_EXCEPTION_HANDLER
901         
902         // List gameids if requested
903         if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
904         {
905                 std::set<std::string> gameids = getAvailableGameIds();
906                 for(std::set<std::string>::const_iterator i = gameids.begin();
907                                 i != gameids.end(); i++)
908                         dstream<<(*i)<<std::endl;
909                 return 0;
910         }
911         
912         // Print startup message
913         infostream<<PROJECT_NAME<<
914                         " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
915                         <<", "<<BUILD_INFO
916                         <<std::endl;
917         
918         /*
919                 Basic initialization
920         */
921
922         // Initialize default settings
923         set_default_settings(g_settings);
924         
925         // Initialize sockets
926         sockets_init();
927         atexit(sockets_cleanup);
928         
929         /*
930                 Read config file
931         */
932         
933         // Path of configuration file in use
934         std::string configpath = "";
935         
936         if(cmd_args.exists("config"))
937         {
938                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
939                 if(r == false)
940                 {
941                         errorstream<<"Could not read configuration from \""
942                                         <<cmd_args.get("config")<<"\""<<std::endl;
943                         return 1;
944                 }
945                 configpath = cmd_args.get("config");
946         }
947         else
948         {
949                 core::array<std::string> filenames;
950                 filenames.push_back(porting::path_user +
951                                 DIR_DELIM + "minetest.conf");
952                 // Legacy configuration file location
953                 filenames.push_back(porting::path_user +
954                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
955 #ifdef RUN_IN_PLACE
956                 // Try also from a lower level (to aid having the same configuration
957                 // for many RUN_IN_PLACE installs)
958                 filenames.push_back(porting::path_user +
959                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
960 #endif
961
962                 for(u32 i=0; i<filenames.size(); i++)
963                 {
964                         bool r = g_settings->readConfigFile(filenames[i].c_str());
965                         if(r)
966                         {
967                                 configpath = filenames[i];
968                                 break;
969                         }
970                 }
971                 
972                 // If no path found, use the first one (menu creates the file)
973                 if(configpath == "")
974                         configpath = filenames[0];
975         }
976
977         // Initialize random seed
978         srand(time(0));
979         mysrand(time(0));
980
981         /*
982                 Run unit tests
983         */
984
985         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
986                         || cmd_args.getFlag("enable-unittests") == true)
987         {
988                 run_tests();
989         }
990         
991         /*
992                 Game parameters
993         */
994
995         // Port
996         u16 port = 30000;
997         if(cmd_args.exists("port"))
998                 port = cmd_args.getU16("port");
999         else if(g_settings->exists("port"))
1000                 port = g_settings->getU16("port");
1001         if(port == 0)
1002                 port = 30000;
1003         
1004         // World directory
1005         std::string commanded_world = "";
1006         if(cmd_args.exists("world"))
1007                 commanded_world = cmd_args.get("world");
1008         else if(cmd_args.exists("map-dir"))
1009                 commanded_world = cmd_args.get("map-dir");
1010         else if(cmd_args.exists("nonopt0")) // First nameless argument
1011                 commanded_world = cmd_args.get("nonopt0");
1012         else if(g_settings->exists("map-dir"))
1013                 commanded_world = g_settings->get("map-dir");
1014         
1015         // World name
1016         std::string commanded_worldname = "";
1017         if(cmd_args.exists("worldname"))
1018                 commanded_worldname = cmd_args.get("worldname");
1019         
1020         // Strip world.mt from commanded_world
1021         {
1022                 std::string worldmt = "world.mt";
1023                 if(commanded_world.size() > worldmt.size() &&
1024                                 commanded_world.substr(commanded_world.size()-worldmt.size())
1025                                 == worldmt){
1026                         dstream<<"Supplied world.mt file - stripping it off."<<std::endl;
1027                         commanded_world = commanded_world.substr(
1028                                         0, commanded_world.size()-worldmt.size());
1029                 }
1030         }
1031         
1032         // Gamespec
1033         SubgameSpec commanded_gamespec;
1034         if(cmd_args.exists("gameid")){
1035                 std::string gameid = cmd_args.get("gameid");
1036                 commanded_gamespec = findSubgame(gameid);
1037                 if(!commanded_gamespec.isValid()){
1038                         errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1039                         return 1;
1040                 }
1041         }
1042
1043         /*
1044                 Run dedicated server if asked to or no other option
1045         */
1046 #ifdef SERVER
1047         bool run_dedicated_server = true;
1048 #else
1049         bool run_dedicated_server = cmd_args.getFlag("server");
1050 #endif
1051         if(run_dedicated_server)
1052         {
1053                 DSTACK("Dedicated server branch");
1054                 // Create time getter if built with Irrlicht
1055 #ifndef SERVER
1056                 g_timegetter = new SimpleTimeGetter();
1057 #endif
1058
1059                 // World directory
1060                 std::string world_path;
1061                 verbosestream<<"Determining world path"<<std::endl;
1062                 bool is_legacy_world = false;
1063                 // If a world was commanded, use it
1064                 if(commanded_world != ""){
1065                         world_path = commanded_world;
1066                         infostream<<"Using commanded world path ["<<world_path<<"]"
1067                                         <<std::endl;
1068                 }
1069                 // If a world name was specified, select it
1070                 else if(commanded_worldname != ""){
1071                         // Get information about available worlds
1072                         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1073                         world_path = "";
1074                         for(u32 i=0; i<worldspecs.size(); i++){
1075                                 std::string name = worldspecs[i].name;
1076                                 if(name == commanded_worldname){
1077                                         world_path = worldspecs[i].path;
1078                                         break;
1079                                 }
1080                         }
1081                         if(world_path == ""){
1082                                 dstream<<"World '"<<commanded_worldname<<"' not "
1083                                                 <<"available. Available worlds:"<<std::endl;
1084                                 print_worldspecs(worldspecs, dstream);
1085                                 return 1;
1086                         }
1087                 }
1088                 // No world was specified; try to select it automatically
1089                 else
1090                 {
1091                         // Get information about available worlds
1092                         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1093                         // If a world name was specified, select it
1094                         if(commanded_worldname != ""){
1095                                 world_path = "";
1096                                 for(u32 i=0; i<worldspecs.size(); i++){
1097                                         std::string name = worldspecs[i].name;
1098                                         if(name == commanded_worldname){
1099                                                 world_path = worldspecs[i].path;
1100                                                 break;
1101                                         }
1102                                 }
1103                                 if(world_path == ""){
1104                                         dstream<<"World '"<<commanded_worldname<<"' not "
1105                                                         <<"available. Available worlds:"<<std::endl;
1106                                         print_worldspecs(worldspecs, dstream);
1107                                         return 1;
1108                                 }
1109                         }
1110                         // If there is only a single world, use it
1111                         if(worldspecs.size() == 1){
1112                                 world_path = worldspecs[0].path;
1113                                 dstream<<"Automatically selecting world at ["
1114                                                 <<world_path<<"]"<<std::endl;
1115                         // If there are multiple worlds, list them
1116                         } else if(worldspecs.size() > 1){
1117                                 dstream<<"Multiple worlds are available."<<std::endl;
1118                                 dstream<<"Please select one using --worldname <name>"
1119                                                 <<" or --world <path>"<<std::endl;
1120                                 print_worldspecs(worldspecs, dstream);
1121                                 return 1;
1122                         // If there are no worlds, automatically create a new one
1123                         } else {
1124                                 // This is the ultimate default world path
1125                                 world_path = porting::path_user + DIR_DELIM + "worlds" +
1126                                                 DIR_DELIM + "world";
1127                                 infostream<<"Creating default world at ["
1128                                                 <<world_path<<"]"<<std::endl;
1129                         }
1130                 }
1131
1132                 if(world_path == ""){
1133                         errorstream<<"No world path specified or found."<<std::endl;
1134                         return 1;
1135                 }
1136                 verbosestream<<"Using world path ["<<world_path<<"]"<<std::endl;
1137
1138                 // We need a gameid.
1139                 std::string gameid;
1140                 verbosestream<<"Determining gameid"<<std::endl;
1141                 // If world doesn't exist
1142                 if(!getWorldExists(world_path))
1143                 {
1144                         // Try to take gamespec from command line
1145                         if(commanded_gamespec.isValid()){
1146                                 gameid = commanded_gamespec.id;
1147                                 infostream<<"Using commanded gameid ["<<gameid<<"]"<<std::endl;
1148                         }
1149                         // Otherwise we will be using "minetest"
1150                         else{
1151                                 gameid = g_settings->get("default_game");
1152                                 infostream<<"Using default gameid ["<<gameid<<"]"<<std::endl;
1153                         }
1154                 }
1155                 // If world exists
1156                 else
1157                 {
1158                         // Otherwise read from the world
1159                         std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1160                         gameid = world_gameid;
1161                         if(commanded_gamespec.isValid() &&
1162                                         commanded_gamespec.id != world_gameid){
1163                                 gameid = commanded_gamespec.id;
1164                                 errorstream<<"WARNING: Using commanded gameid ["<<gameid<<"]"
1165                                                 <<" instead of world gameid ["<<world_gameid
1166                                                 <<"]"<<std::endl;
1167                         } else{
1168                                 infostream<<"Using world gameid ["<<gameid<<"]"<<std::endl;
1169                         }
1170                 }
1171                 verbosestream<<"Finding subgame ["<<gameid<<"]"<<std::endl;
1172                 SubgameSpec gamespec = findSubgame(gameid);
1173                 if(!gamespec.isValid()){
1174                         errorstream<<"Subgame ["<<gameid<<"] could not be found."
1175                                         <<std::endl;
1176                         return 1;
1177                 }
1178                 verbosestream<<"Using gameid ["<<gamespec.id<<"]"<<std::endl;
1179
1180                 // Create server
1181                 Server server(world_path, configpath, gamespec, false);
1182                 server.start(port);
1183                 
1184                 // Run server
1185                 dedicated_server_loop(server, kill);
1186
1187                 return 0;
1188         }
1189
1190 #ifndef SERVER // Exclude from dedicated server build
1191
1192         /*
1193                 More parameters
1194         */
1195         
1196         std::string address = g_settings->get("address");
1197         if(commanded_world != "")
1198                 address = "";
1199         else if(cmd_args.exists("address"))
1200                 address = cmd_args.get("address");
1201         else if(cmd_args.exists("world"))
1202                 address = "";
1203         
1204         std::string playername = g_settings->get("name");
1205         if(cmd_args.exists("name"))
1206                 playername = cmd_args.get("name");
1207         
1208         bool skip_main_menu = cmd_args.getFlag("go");
1209
1210         /*
1211                 Device initialization
1212         */
1213
1214         // Resolution selection
1215         
1216         bool fullscreen = g_settings->getBool("fullscreen");
1217         u16 screenW = g_settings->getU16("screenW");
1218         u16 screenH = g_settings->getU16("screenH");
1219
1220         // bpp, fsaa, vsync
1221
1222         bool vsync = g_settings->getBool("vsync");
1223         u16 bits = g_settings->getU16("fullscreen_bpp");
1224         u16 fsaa = g_settings->getU16("fsaa");
1225
1226         // Determine driver
1227
1228         video::E_DRIVER_TYPE driverType;
1229         
1230         std::string driverstring = g_settings->get("video_driver");
1231
1232         if(driverstring == "null")
1233                 driverType = video::EDT_NULL;
1234         else if(driverstring == "software")
1235                 driverType = video::EDT_SOFTWARE;
1236         else if(driverstring == "burningsvideo")
1237                 driverType = video::EDT_BURNINGSVIDEO;
1238         else if(driverstring == "direct3d8")
1239                 driverType = video::EDT_DIRECT3D8;
1240         else if(driverstring == "direct3d9")
1241                 driverType = video::EDT_DIRECT3D9;
1242         else if(driverstring == "opengl")
1243                 driverType = video::EDT_OPENGL;
1244         else
1245         {
1246                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1247                                 "to opengl"<<std::endl;
1248                 driverType = video::EDT_OPENGL;
1249         }
1250
1251         /*
1252                 Create device and exit if creation failed
1253         */
1254
1255         MyEventReceiver receiver;
1256
1257         IrrlichtDevice *device;
1258
1259         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1260         params.DriverType    = driverType;
1261         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
1262         params.Bits          = bits;
1263         params.AntiAlias     = fsaa;
1264         params.Fullscreen    = fullscreen;
1265         params.Stencilbuffer = false;
1266         params.Vsync         = vsync;
1267         params.EventReceiver = &receiver;
1268
1269         device = createDeviceEx(params);
1270
1271         if (device == 0)
1272                 return 1; // could not create selected driver.
1273         
1274         /*
1275                 Continue initialization
1276         */
1277
1278         video::IVideoDriver* driver = device->getVideoDriver();
1279
1280         // Disable mipmaps (because some of them look ugly)
1281         driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1282
1283         /*
1284                 This changes the minimum allowed number of vertices in a VBO.
1285                 Default is 500.
1286         */
1287         //driver->setMinHardwareBufferVertexCount(50);
1288
1289         // Create time getter
1290         g_timegetter = new IrrlichtTimeGetter(device);
1291         
1292         // Create game callback for menus
1293         g_gamecallback = new MainGameCallback(device);
1294         
1295         /*
1296                 Speed tests (done after irrlicht is loaded to get timer)
1297         */
1298         if(cmd_args.getFlag("speedtests"))
1299         {
1300                 dstream<<"Running speed tests"<<std::endl;
1301                 SpeedTests();
1302                 return 0;
1303         }
1304         
1305         device->setResizable(true);
1306
1307         bool random_input = g_settings->getBool("random_input")
1308                         || cmd_args.getFlag("random-input");
1309         InputHandler *input = NULL;
1310         if(random_input)
1311                 input = new RandomInputHandler();
1312         else
1313                 input = new RealInputHandler(device, &receiver);
1314         
1315         scene::ISceneManager* smgr = device->getSceneManager();
1316
1317         guienv = device->getGUIEnvironment();
1318         gui::IGUISkin* skin = guienv->getSkin();
1319         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1320         if(font)
1321                 skin->setFont(font);
1322         else
1323                 errorstream<<"WARNING: Font file was not found."
1324                                 " Using default font."<<std::endl;
1325         // If font was not found, this will get us one
1326         font = skin->getFont();
1327         assert(font);
1328         
1329         u32 text_height = font->getDimension(L"Hello, world!").Height;
1330         infostream<<"text_height="<<text_height<<std::endl;
1331
1332         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1333         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1334         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1335         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1336         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1337         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1338         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1339         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1340         
1341         /*
1342                 GUI stuff
1343         */
1344
1345         ChatBackend chat_backend;
1346
1347         /*
1348                 If an error occurs, this is set to something and the
1349                 menu-game loop is restarted. It is then displayed before
1350                 the menu.
1351         */
1352         std::wstring error_message = L"";
1353
1354         // The password entered during the menu screen,
1355         std::string password;
1356
1357         bool first_loop = true;
1358
1359         /*
1360                 Menu-game loop
1361         */
1362         while(device->run() && kill == false)
1363         {
1364                 // Set the window caption
1365                 device->setWindowCaption(L"Minetest [Main Menu]");
1366
1367                 // This is used for catching disconnects
1368                 try
1369                 {
1370
1371                         /*
1372                                 Clear everything from the GUIEnvironment
1373                         */
1374                         guienv->clear();
1375                         
1376                         /*
1377                                 We need some kind of a root node to be able to add
1378                                 custom gui elements directly on the screen.
1379                                 Otherwise they won't be automatically drawn.
1380                         */
1381                         guiroot = guienv->addStaticText(L"",
1382                                         core::rect<s32>(0, 0, 10000, 10000));
1383                         
1384                         SubgameSpec gamespec;
1385                         WorldSpec worldspec;
1386                         bool simple_singleplayer_mode = false;
1387
1388                         // These are set up based on the menu and other things
1389                         std::string current_playername = "inv£lid";
1390                         std::string current_password = "";
1391                         std::string current_address = "does-not-exist";
1392                         int current_port = 0;
1393
1394                         /*
1395                                 Out-of-game menu loop.
1396
1397                                 Loop quits when menu returns proper parameters.
1398                         */
1399                         while(kill == false)
1400                         {
1401                                 // If skip_main_menu, only go through here once
1402                                 if(skip_main_menu && !first_loop){
1403                                         kill = true;
1404                                         break;
1405                                 }
1406                                 first_loop = false;
1407                                 
1408                                 // Cursor can be non-visible when coming from the game
1409                                 device->getCursorControl()->setVisible(true);
1410                                 // Some stuff are left to scene manager when coming from the game
1411                                 // (map at least?)
1412                                 smgr->clear();
1413                                 
1414                                 // Initialize menu data
1415                                 MainMenuData menudata;
1416                                 if(g_settings->exists("selected_mainmenu_tab"))
1417                                         menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1418                                 menudata.address = narrow_to_wide(address);
1419                                 menudata.name = narrow_to_wide(playername);
1420                                 menudata.port = narrow_to_wide(itos(port));
1421                                 if(cmd_args.exists("password"))
1422                                         menudata.password = narrow_to_wide(cmd_args.get("password"));
1423                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1424                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1425                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1426                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1427                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1428                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1429                                 // Default to selecting nothing
1430                                 menudata.selected_world = -1;
1431                                 // Get world listing for the menu
1432                                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1433                                 // If there is only one world, select it
1434                                 if(worldspecs.size() == 1){
1435                                         menudata.selected_world = 0;
1436                                 }
1437                                 // Otherwise try to select according to selected_world_path
1438                                 else if(g_settings->exists("selected_world_path")){
1439                                         std::string trypath = g_settings->get("selected_world_path");
1440                                         for(u32 i=0; i<worldspecs.size(); i++){
1441                                                 if(worldspecs[i].path == trypath){
1442                                                         menudata.selected_world = i;
1443                                                         break;
1444                                                 }
1445                                         }
1446                                 }
1447                                 // If a world was commanded, append and select it
1448                                 if(commanded_world != ""){
1449                                         std::string gameid = getWorldGameId(commanded_world, true);
1450                                         std::string name = "[--world parameter]";
1451                                         if(gameid == ""){
1452                                                 gameid = g_settings->get("default_game");
1453                                                 name += " [new]";
1454                                         }
1455                                         WorldSpec spec(commanded_world, name, gameid);
1456                                         worldspecs.push_back(spec);
1457                                         menudata.selected_world = worldspecs.size()-1;
1458                                 }
1459                                 // Copy worldspecs to menu
1460                                 menudata.worlds = worldspecs;
1461
1462                                 if(skip_main_menu == false)
1463                                 {
1464                                         video::IVideoDriver* driver = device->getVideoDriver();
1465                                         
1466                                         infostream<<"Waiting for other menus"<<std::endl;
1467                                         while(device->run() && kill == false)
1468                                         {
1469                                                 if(noMenuActive())
1470                                                         break;
1471                                                 driver->beginScene(true, true,
1472                                                                 video::SColor(255,128,128,128));
1473                                                 drawMenuBackground(driver);
1474                                                 guienv->drawAll();
1475                                                 driver->endScene();
1476                                                 // On some computers framerate doesn't seem to be
1477                                                 // automatically limited
1478                                                 sleep_ms(25);
1479                                         }
1480                                         infostream<<"Waited for other menus"<<std::endl;
1481
1482                                         GUIMainMenu *menu =
1483                                                         new GUIMainMenu(guienv, guiroot, -1, 
1484                                                                 &g_menumgr, &menudata, g_gamecallback);
1485                                         menu->allowFocusRemoval(true);
1486
1487                                         if(error_message != L"")
1488                                         {
1489                                                 verbosestream<<"error_message = "
1490                                                                 <<wide_to_narrow(error_message)<<std::endl;
1491
1492                                                 GUIMessageMenu *menu2 =
1493                                                                 new GUIMessageMenu(guienv, guiroot, -1, 
1494                                                                         &g_menumgr, error_message.c_str());
1495                                                 menu2->drop();
1496                                                 error_message = L"";
1497                                         }
1498
1499                                         infostream<<"Created main menu"<<std::endl;
1500
1501                                         while(device->run() && kill == false)
1502                                         {
1503                                                 if(menu->getStatus() == true)
1504                                                         break;
1505
1506                                                 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1507                                                 driver->beginScene(true, true, video::SColor(255,128,128,128));
1508
1509                                                 drawMenuBackground(driver);
1510
1511                                                 guienv->drawAll();
1512                                                 
1513                                                 driver->endScene();
1514                                                 
1515                                                 // On some computers framerate doesn't seem to be
1516                                                 // automatically limited
1517                                                 sleep_ms(25);
1518                                         }
1519                                         
1520                                         infostream<<"Dropping main menu"<<std::endl;
1521
1522                                         menu->drop();
1523                                 }
1524
1525                                 playername = wide_to_narrow(menudata.name);
1526                                 password = translatePassword(playername, menudata.password);
1527                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1528
1529                                 address = wide_to_narrow(menudata.address);
1530                                 int newport = stoi(wide_to_narrow(menudata.port));
1531                                 if(newport != 0)
1532                                         port = newport;
1533                                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1534                                 // Save settings
1535                                 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1536                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1537                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1538                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1539                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1540                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1541                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1542                                 g_settings->set("name", playername);
1543                                 g_settings->set("address", address);
1544                                 g_settings->set("port", itos(port));
1545                                 if(menudata.selected_world != -1)
1546                                         g_settings->set("selected_world_path",
1547                                                         worldspecs[menudata.selected_world].path);
1548                                 
1549                                 // Break out of menu-game loop to shut down cleanly
1550                                 if(device->run() == false || kill == true)
1551                                         break;
1552                                 
1553                                 current_playername = playername;
1554                                 current_password = password;
1555                                 current_address = address;
1556                                 current_port = port;
1557
1558                                 // If using simple singleplayer mode, override
1559                                 if(simple_singleplayer_mode){
1560                                         current_playername = "singleplayer";
1561                                         current_password = "";
1562                                         current_address = "";
1563                                         current_port = 30011;
1564                                 }
1565                                 
1566                                 // Set world path to selected one
1567                                 if(menudata.selected_world != -1){
1568                                         worldspec = worldspecs[menudata.selected_world];
1569                                         infostream<<"Selected world: "<<worldspec.name
1570                                                         <<" ["<<worldspec.path<<"]"<<std::endl;
1571                                 }
1572
1573                                 // Only refresh if so requested
1574                                 if(menudata.only_refresh){
1575                                         infostream<<"Refreshing menu"<<std::endl;
1576                                         continue;
1577                                 }
1578                                 
1579                                 // Create new world if requested
1580                                 if(menudata.create_world_name != L"")
1581                                 {
1582                                         std::string path = porting::path_user + DIR_DELIM
1583                                                         "worlds" + DIR_DELIM
1584                                                         + wide_to_narrow(menudata.create_world_name);
1585                                         // Create world if it doesn't exist
1586                                         if(!initializeWorld(path, menudata.create_world_gameid)){
1587                                                 error_message = L"Failed to initialize world";
1588                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1589                                                 continue;
1590                                         }
1591                                         g_settings->set("selected_world_path", path);
1592                                         continue;
1593                                 }
1594
1595                                 // If local game
1596                                 if(current_address == "")
1597                                 {
1598                                         if(menudata.selected_world == -1){
1599                                                 error_message = L"No world selected and no address "
1600                                                                 L"provided. Nothing to do.";
1601                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1602                                                 continue;
1603                                         }
1604                                         // Load gamespec for required game
1605                                         gamespec = findSubgame(worldspec.gameid);
1606                                         if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1607                                                 error_message = L"Could not find or load game \""
1608                                                                 + narrow_to_wide(worldspec.gameid) + L"\"";
1609                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1610                                                 continue;
1611                                         }
1612                                         if(commanded_gamespec.isValid() &&
1613                                                         commanded_gamespec.id != worldspec.gameid){
1614                                                 errorstream<<"WARNING: Overriding gamespec from \""
1615                                                                 <<worldspec.gameid<<"\" to \""
1616                                                                 <<commanded_gamespec.id<<"\""<<std::endl;
1617                                                 gamespec = commanded_gamespec;
1618                                         }
1619
1620                                         if(!gamespec.isValid()){
1621                                                 error_message = L"Invalid gamespec. (world_gameid="
1622                                                                 +narrow_to_wide(worldspec.gameid)+L")";
1623                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1624                                                 continue;
1625                                         }
1626                                 }
1627
1628                                 // Continue to game
1629                                 break;
1630                         }
1631                         
1632                         // Break out of menu-game loop to shut down cleanly
1633                         if(device->run() == false || kill == true)
1634                                 break;
1635
1636                         /*
1637                                 Run game
1638                         */
1639                         the_game(
1640                                 kill,
1641                                 random_input,
1642                                 input,
1643                                 device,
1644                                 font,
1645                                 worldspec.path,
1646                                 current_playername,
1647                                 current_password,
1648                                 current_address,
1649                                 current_port,
1650                                 error_message,
1651                                 configpath,
1652                                 chat_backend,
1653                                 gamespec,
1654                                 simple_singleplayer_mode
1655                         );
1656
1657                 } //try
1658                 catch(con::PeerNotFoundException &e)
1659                 {
1660                         error_message = L"Connection error (timed out?)";
1661                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1662                 }
1663                 catch(ServerError &e)
1664                 {
1665                         error_message = narrow_to_wide(e.what());
1666                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1667                 }
1668                 catch(ModError &e)
1669                 {
1670                         errorstream<<e.what()<<std::endl;
1671                         error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1672                 }
1673 #ifdef NDEBUG
1674                 catch(std::exception &e)
1675                 {
1676                         std::string narrow_message = "Some exception, what()=\"";
1677                         narrow_message += e.what();
1678                         narrow_message += "\"";
1679                         errorstream<<narrow_message<<std::endl;
1680                         error_message = narrow_to_wide(narrow_message);
1681                 }
1682 #endif
1683
1684                 // If no main menu, show error and exit
1685                 if(skip_main_menu)
1686                 {
1687                         if(error_message != L""){
1688                                 verbosestream<<"error_message = "
1689                                                 <<wide_to_narrow(error_message)<<std::endl;
1690                                 retval = 1;
1691                         }
1692                         break;
1693                 }
1694         } // Menu-game loop
1695         
1696         delete input;
1697
1698         /*
1699                 In the end, delete the Irrlicht device.
1700         */
1701         device->drop();
1702
1703 #endif // !SERVER
1704         
1705         // Update configuration file
1706         if(configpath != "")
1707                 g_settings->updateConfigFile(configpath.c_str());
1708         
1709         // Print modified quicktune values
1710         {
1711                 bool header_printed = false;
1712                 std::vector<std::string> names = getQuicktuneNames();
1713                 for(u32 i=0; i<names.size(); i++){
1714                         QuicktuneValue val = getQuicktuneValue(names[i]);
1715                         if(!val.modified)
1716                                 continue;
1717                         if(!header_printed){
1718                                 dstream<<"Modified quicktune values:"<<std::endl;
1719                                 header_printed = true;
1720                         }
1721                         dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1722                 }
1723         }
1724
1725         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1726         
1727         debugstreams_deinit();
1728         
1729         return retval;
1730 }
1731
1732 //END
1733