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