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