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