Fix itemdef drop on NULL texture
[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 //Draw the tiled menu background
616 void drawMenuBackground(video::IVideoDriver* driver) {
617         core::dimension2d<u32> screensize = driver->getScreenSize();
618
619         std::string path = getTexturePath("menubg.png");
620         if (path[0]) {
621                 static const video::ITexture *bgtexture =
622                         driver->getTexture(path.c_str());
623
624                 if (bgtexture) {
625                         s32 scaledsize = 128;
626                 
627                         // The important difference between destsize and screensize is
628                         // that destsize is rounded to whole scaled pixels.
629                         // These formulas use component-wise multiplication and division of v2u32.
630                         v2u32 texturesize = bgtexture->getSize();
631                         v2u32 sourcesize = texturesize * screensize / scaledsize + v2u32(1,1);
632                         v2u32 destsize = scaledsize * sourcesize / texturesize;
633                 
634                         // Default texture wrapping mode in Irrlicht is ETC_REPEAT.
635                         driver->draw2DImage(bgtexture,
636                                 core::rect<s32>(0, 0, destsize.X, destsize.Y),
637                                 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
638                                 NULL, NULL, true);
639                 }
640         }
641 }
642
643 //Draw the footer at the bottom of the window
644 void drawMenuFooter(video::IVideoDriver* driver, bool clouds) {
645         core::dimension2d<u32> screensize = driver->getScreenSize();
646         std::string path = getTexturePath(clouds ?
647                                                 "menufooter_clouds.png" : "menufooter.png");
648         if (path[0]) {
649                 static const video::ITexture *footertexture =
650                         driver->getTexture(path.c_str());
651
652                 if (footertexture) {
653                         f32 mult = (((f32)screensize.Width)) /
654                                 ((f32)footertexture->getOriginalSize().Width);
655
656                         v2s32 footersize(((f32)footertexture->getOriginalSize().Width) * mult,
657                                         ((f32)footertexture->getOriginalSize().Height) * mult);
658
659                         // Don't draw the footer if there isn't enough room
660                         s32 free_space = (((s32)screensize.Height)-320)/2;
661                         if (free_space > footersize.Y) {
662                                 core::rect<s32> rect(0,0,footersize.X,footersize.Y);
663                                 rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y);
664                                 rect -= v2s32(footersize.X/2, 0);
665
666                                 driver->draw2DImage(footertexture, rect,
667                                         core::rect<s32>(core::position2d<s32>(0,0),
668                                         core::dimension2di(footertexture->getSize())),
669                                         NULL, NULL, true);
670                         }
671                 }
672         }
673 }
674
675 // Draw the Header over the main menu
676 void drawMenuHeader(video::IVideoDriver* driver) {
677         core::dimension2d<u32> screensize = driver->getScreenSize();
678
679         std::string path = getTexturePath("menuheader.png");
680         if (path[0]) {
681                 static const video::ITexture *splashtexture =
682                 driver->getTexture(path.c_str());
683
684                 if(splashtexture) {
685                         f32 mult = (((f32)screensize.Width / 2)) /
686                                 ((f32)splashtexture->getOriginalSize().Width);
687
688                         v2s32 splashsize(((f32)splashtexture->getOriginalSize().Width) * mult,
689                                         ((f32)splashtexture->getOriginalSize().Height) * mult);
690
691                         // Don't draw the header is there isn't enough room
692                         s32 free_space = (((s32)screensize.Height)-320)/2;
693                         if (free_space > splashsize.Y) {
694                                 core::rect<s32> splashrect(0, 0, splashsize.X, splashsize.Y);
695                                 splashrect += v2s32((screensize.Width/2)-(splashsize.X/2),
696                                         ((free_space/2)-splashsize.Y/2)+10);
697
698                                 video::SColor bgcolor(255,50,50,50);
699
700                                 driver->draw2DImage(splashtexture, splashrect,
701                                         core::rect<s32>(core::position2d<s32>(0,0),
702                                         core::dimension2di(splashtexture->getSize())),
703                                         NULL, NULL, true);
704                         }
705                 }
706         }
707 }
708
709 // Draw the Splash over the clouds and under the main menu
710 void drawMenuSplash(video::IVideoDriver* driver) {
711         core::dimension2d<u32> screensize = driver->getScreenSize();
712         std::string path = getTexturePath("menusplash.png");
713         if (path[0]) {
714                 static const video::ITexture *splashtexture =
715                         driver->getTexture(path.c_str());
716
717                 if(splashtexture) {
718                         core::rect<s32> splashrect(0, 0, screensize.Width, screensize.Height);
719
720                         video::SColor bgcolor(255,50,50,50);
721
722                         driver->draw2DImage(splashtexture, splashrect,
723                                 core::rect<s32>(core::position2d<s32>(0,0),
724                                 core::dimension2di(splashtexture->getSize())),
725                                 NULL, NULL, true);
726                 }
727         }
728 }
729
730 #endif
731
732 // These are defined global so that they're not optimized too much.
733 // Can't change them to volatile.
734 s16 temp16;
735 f32 tempf;
736 v3f tempv3f1;
737 v3f tempv3f2;
738 std::string tempstring;
739 std::string tempstring2;
740
741 void SpeedTests()
742 {
743         {
744                 infostream<<"The following test should take around 20ms."<<std::endl;
745                 TimeTaker timer("Testing std::string speed");
746                 const u32 jj = 10000;
747                 for(u32 j=0; j<jj; j++)
748                 {
749                         tempstring = "";
750                         tempstring2 = "";
751                         const u32 ii = 10;
752                         for(u32 i=0; i<ii; i++){
753                                 tempstring2 += "asd";
754                         }
755                         for(u32 i=0; i<ii+1; i++){
756                                 tempstring += "asd";
757                                 if(tempstring == tempstring2)
758                                         break;
759                         }
760                 }
761         }
762         
763         infostream<<"All of the following tests should take around 100ms each."
764                         <<std::endl;
765
766         {
767                 TimeTaker timer("Testing floating-point conversion speed");
768                 tempf = 0.001;
769                 for(u32 i=0; i<4000000; i++){
770                         temp16 += tempf;
771                         tempf += 0.001;
772                 }
773         }
774         
775         {
776                 TimeTaker timer("Testing floating-point vector speed");
777
778                 tempv3f1 = v3f(1,2,3);
779                 tempv3f2 = v3f(4,5,6);
780                 for(u32 i=0; i<10000000; i++){
781                         tempf += tempv3f1.dotProduct(tempv3f2);
782                         tempv3f2 += v3f(7,8,9);
783                 }
784         }
785
786         {
787                 TimeTaker timer("Testing std::map speed");
788                 
789                 std::map<v2s16, f32> map1;
790                 tempf = -324;
791                 const s16 ii=300;
792                 for(s16 y=0; y<ii; y++){
793                         for(s16 x=0; x<ii; x++){
794                                 map1[v2s16(x,y)] =  tempf;
795                                 tempf += 1;
796                         }
797                 }
798                 for(s16 y=ii-1; y>=0; y--){
799                         for(s16 x=0; x<ii; x++){
800                                 tempf = map1[v2s16(x,y)];
801                         }
802                 }
803         }
804
805         {
806                 infostream<<"Around 5000/ms should do well here."<<std::endl;
807                 TimeTaker timer("Testing mutex speed");
808                 
809                 JMutex m;
810                 m.Init();
811                 u32 n = 0;
812                 u32 i = 0;
813                 do{
814                         n += 10000;
815                         for(; i<n; i++){
816                                 m.Lock();
817                                 m.Unlock();
818                         }
819                 }
820                 // Do at least 10ms
821                 while(timer.getTimerTime() < 10);
822
823                 u32 dtime = timer.stop();
824                 u32 per_ms = n / dtime;
825                 infostream<<"Done. "<<dtime<<"ms, "
826                                 <<per_ms<<"/ms"<<std::endl;
827         }
828 }
829
830 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
831                 std::ostream &os)
832 {
833         for(u32 i=0; i<worldspecs.size(); i++){
834                 std::string name = worldspecs[i].name;
835                 std::string path = worldspecs[i].path;
836                 if(name.find(" ") != std::string::npos)
837                         name = std::string("'") + name + "'";
838                 path = std::string("'") + path + "'";
839                 name = padStringRight(name, 14);
840                 os<<"  "<<name<<" "<<path<<std::endl;
841         }
842 }
843
844 int main(int argc, char *argv[])
845 {
846         int retval = 0;
847
848         /*
849                 Initialization
850         */
851
852         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
853         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
854
855         log_register_thread("main");
856
857         // This enables internatonal characters input
858         if( setlocale(LC_ALL, "") == NULL )
859         {
860                 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
861         }
862
863         // Set locale. This is for forcing '.' as the decimal point.
864         try {
865                 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
866                 setlocale(LC_NUMERIC, "C");
867         } catch (const std::exception& ex) {
868                 errorstream<<"Could not set numeric locale to C"<<std::endl;
869         }
870         /*
871                 Parse command line
872         */
873         
874         // List all allowed options
875         std::map<std::string, ValueSpec> allowed_options;
876         allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
877                         _("Show allowed options"))));
878         allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
879                         _("Load configuration from specified file"))));
880         allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
881                         _("Set network port (UDP)"))));
882         allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
883                         _("Disable unit tests"))));
884         allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
885                         _("Enable unit tests"))));
886         allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
887                         _("Same as --world (deprecated)"))));
888         allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
889                         _("Set world path (implies local game) ('list' lists all)"))));
890         allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
891                         _("Set world by name (implies local game)"))));
892         allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
893                         _("Print more information to console"))));
894         allowed_options.insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
895                         _("Print even more information to console"))));
896         allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
897                         _("Print enormous amounts of information to log and console"))));
898         allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
899                         _("Set logfile path ('' = no logging)"))));
900         allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
901                         _("Set gameid (\"--gameid list\" prints available ones)"))));
902 #ifndef SERVER
903         allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
904                         _("Run speed tests"))));
905         allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
906                         _("Address to connect to. ('' = local game)"))));
907         allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
908                         _("Enable random user input, for testing"))));
909         allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
910                         _("Run dedicated server"))));
911         allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
912                         _("Set player name"))));
913         allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
914                         _("Set password"))));
915         allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
916                         _("Disable main menu"))));
917 #endif
918
919         Settings cmd_args;
920         
921         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
922
923         if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
924         {
925                 dstream<<_("Allowed options:")<<std::endl;
926                 for(std::map<std::string, ValueSpec>::iterator
927                                 i = allowed_options.begin();
928                                 i != allowed_options.end(); ++i)
929                 {
930                         std::ostringstream os1(std::ios::binary);
931                         os1<<"  --"<<i->first;
932                         if(i->second.type == VALUETYPE_FLAG)
933                                 {}
934                         else
935                                 os1<<_(" <value>");
936                         dstream<<padStringRight(os1.str(), 24);
937
938                         if(i->second.help != NULL)
939                                 dstream<<i->second.help;
940                         dstream<<std::endl;
941                 }
942
943                 return cmd_args.getFlag("help") ? 0 : 1;
944         }
945         
946         /*
947                 Low-level initialization
948         */
949         
950         // If trace is enabled, enable logging of certain things
951         if(cmd_args.getFlag("trace")){
952                 dstream<<_("Enabling trace level debug output")<<std::endl;
953                 log_trace_level_enabled = true;
954                 dout_con_ptr = &verbosestream; // this is somewhat old crap
955                 socket_enable_debug_output = true; // socket doesn't use log.h
956         }
957         // In certain cases, output info level on stderr
958         if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
959                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
960                 log_add_output(&main_stderr_log_out, LMT_INFO);
961         // In certain cases, output verbose level on stderr
962         if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
963                 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
964
965         porting::signal_handler_init();
966         bool &kill = *porting::signal_handler_killstatus();
967         
968         porting::initializePaths();
969
970         // Create user data directory
971         fs::CreateDir(porting::path_user);
972
973         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
974
975         infostream<<"path_share = "<<porting::path_share<<std::endl;
976         infostream<<"path_user  = "<<porting::path_user<<std::endl;
977
978         // Initialize debug stacks
979         debug_stacks_init();
980         DSTACK(__FUNCTION_NAME);
981
982         // Debug handler
983         BEGIN_DEBUG_EXCEPTION_HANDLER
984         
985         // List gameids if requested
986         if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
987         {
988                 std::set<std::string> gameids = getAvailableGameIds();
989                 for(std::set<std::string>::const_iterator i = gameids.begin();
990                                 i != gameids.end(); i++)
991                         dstream<<(*i)<<std::endl;
992                 return 0;
993         }
994         
995         // List worlds if requested
996         if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
997                 dstream<<_("Available worlds:")<<std::endl;
998                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
999                 print_worldspecs(worldspecs, dstream);
1000                 return 0;
1001         }
1002         
1003         // Print startup message
1004         infostream<<PROJECT_NAME<<
1005                         " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1006                         <<", "<<BUILD_INFO
1007                         <<std::endl;
1008         
1009         /*
1010                 Basic initialization
1011         */
1012
1013         // Initialize default settings
1014         set_default_settings(g_settings);
1015         
1016         // Initialize sockets
1017         sockets_init();
1018         atexit(sockets_cleanup);
1019         
1020         /*
1021                 Read config file
1022         */
1023         
1024         // Path of configuration file in use
1025         std::string configpath = "";
1026         
1027         if(cmd_args.exists("config"))
1028         {
1029                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1030                 if(r == false)
1031                 {
1032                         errorstream<<"Could not read configuration from \""
1033                                         <<cmd_args.get("config")<<"\""<<std::endl;
1034                         return 1;
1035                 }
1036                 configpath = cmd_args.get("config");
1037         }
1038         else
1039         {
1040                 std::vector<std::string> filenames;
1041                 filenames.push_back(porting::path_user +
1042                                 DIR_DELIM + "minetest.conf");
1043                 // Legacy configuration file location
1044                 filenames.push_back(porting::path_user +
1045                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1046 #if RUN_IN_PLACE
1047                 // Try also from a lower level (to aid having the same configuration
1048                 // for many RUN_IN_PLACE installs)
1049                 filenames.push_back(porting::path_user +
1050                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1051 #endif
1052
1053                 for(u32 i=0; i<filenames.size(); i++)
1054                 {
1055                         bool r = g_settings->readConfigFile(filenames[i].c_str());
1056                         if(r)
1057                         {
1058                                 configpath = filenames[i];
1059                                 break;
1060                         }
1061                 }
1062                 
1063                 // If no path found, use the first one (menu creates the file)
1064                 if(configpath == "")
1065                         configpath = filenames[0];
1066         }
1067         
1068         // Initialize debug streams
1069 #define DEBUGFILE "debug.txt"
1070 #if RUN_IN_PLACE
1071         std::string logfile = DEBUGFILE;
1072 #else
1073         std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
1074 #endif
1075         if(cmd_args.exists("logfile"))
1076                 logfile = cmd_args.get("logfile");
1077         
1078         log_remove_output(&main_dstream_no_stderr_log_out);
1079         int loglevel = g_settings->getS32("debug_log_level");
1080
1081         if (loglevel == 0) //no logging
1082                 logfile = "";
1083         else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
1084                 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
1085
1086         if(logfile != "")
1087                 debugstreams_init(false, logfile.c_str());
1088         else
1089                 debugstreams_init(false, NULL);
1090                 
1091         infostream<<"logfile    = "<<logfile<<std::endl;
1092
1093         // Initialize random seed
1094         srand(time(0));
1095         mysrand(time(0));
1096
1097         /*
1098                 Run unit tests
1099         */
1100
1101         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1102                         || cmd_args.getFlag("enable-unittests") == true)
1103         {
1104                 run_tests();
1105         }
1106         
1107         /*
1108                 Game parameters
1109         */
1110
1111         // Port
1112         u16 port = 30000;
1113         if(cmd_args.exists("port"))
1114                 port = cmd_args.getU16("port");
1115         else if(g_settings->exists("port"))
1116                 port = g_settings->getU16("port");
1117         if(port == 0)
1118                 port = 30000;
1119         
1120         // World directory
1121         std::string commanded_world = "";
1122         if(cmd_args.exists("world"))
1123                 commanded_world = cmd_args.get("world");
1124         else if(cmd_args.exists("map-dir"))
1125                 commanded_world = cmd_args.get("map-dir");
1126         else if(cmd_args.exists("nonopt0")) // First nameless argument
1127                 commanded_world = cmd_args.get("nonopt0");
1128         else if(g_settings->exists("map-dir"))
1129                 commanded_world = g_settings->get("map-dir");
1130         
1131         // World name
1132         std::string commanded_worldname = "";
1133         if(cmd_args.exists("worldname"))
1134                 commanded_worldname = cmd_args.get("worldname");
1135         
1136         // Strip world.mt from commanded_world
1137         {
1138                 std::string worldmt = "world.mt";
1139                 if(commanded_world.size() > worldmt.size() &&
1140                                 commanded_world.substr(commanded_world.size()-worldmt.size())
1141                                 == worldmt){
1142                         dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1143                         commanded_world = commanded_world.substr(
1144                                         0, commanded_world.size()-worldmt.size());
1145                 }
1146         }
1147         
1148         // If a world name was specified, convert it to a path
1149         if(commanded_worldname != ""){
1150                 // Get information about available worlds
1151                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1152                 bool found = false;
1153                 for(u32 i=0; i<worldspecs.size(); i++){
1154                         std::string name = worldspecs[i].name;
1155                         if(name == commanded_worldname){
1156                                 if(commanded_world != ""){
1157                                         dstream<<_("--worldname takes precedence over previously "
1158                                                         "selected world.")<<std::endl;
1159                                 }
1160                                 commanded_world = worldspecs[i].path;
1161                                 found = true;
1162                                 break;
1163                         }
1164                 }
1165                 if(!found){
1166                         dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1167                                         "available. Available worlds:")<<std::endl;
1168                         print_worldspecs(worldspecs, dstream);
1169                         return 1;
1170                 }
1171         }
1172
1173         // Gamespec
1174         SubgameSpec commanded_gamespec;
1175         if(cmd_args.exists("gameid")){
1176                 std::string gameid = cmd_args.get("gameid");
1177                 commanded_gamespec = findSubgame(gameid);
1178                 if(!commanded_gamespec.isValid()){
1179                         errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1180                         return 1;
1181                 }
1182         }
1183
1184         /*
1185                 Run dedicated server if asked to or no other option
1186         */
1187 #ifdef SERVER
1188         bool run_dedicated_server = true;
1189 #else
1190         bool run_dedicated_server = cmd_args.getFlag("server");
1191 #endif
1192         g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1193         if(run_dedicated_server)
1194         {
1195                 DSTACK("Dedicated server branch");
1196                 // Create time getter if built with Irrlicht
1197 #ifndef SERVER
1198                 g_timegetter = new SimpleTimeGetter();
1199 #endif
1200
1201                 // World directory
1202                 std::string world_path;
1203                 verbosestream<<_("Determining world path")<<std::endl;
1204                 bool is_legacy_world = false;
1205                 // If a world was commanded, use it
1206                 if(commanded_world != ""){
1207                         world_path = commanded_world;
1208                         infostream<<"Using commanded world path ["<<world_path<<"]"
1209                                         <<std::endl;
1210                 }
1211                 // No world was specified; try to select it automatically
1212                 else
1213                 {
1214                         // Get information about available worlds
1215                         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1216                         // If a world name was specified, select it
1217                         if(commanded_worldname != ""){
1218                                 world_path = "";
1219                                 for(u32 i=0; i<worldspecs.size(); i++){
1220                                         std::string name = worldspecs[i].name;
1221                                         if(name == commanded_worldname){
1222                                                 world_path = worldspecs[i].path;
1223                                                 break;
1224                                         }
1225                                 }
1226                                 if(world_path == ""){
1227                                         dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1228                                                         "available. Available worlds:")<<std::endl;
1229                                         print_worldspecs(worldspecs, dstream);
1230                                         return 1;
1231                                 }
1232                         }
1233                         // If there is only a single world, use it
1234                         if(worldspecs.size() == 1){
1235                                 world_path = worldspecs[0].path;
1236                                 dstream<<_("Automatically selecting world at")<<" ["
1237                                                 <<world_path<<"]"<<std::endl;
1238                         // If there are multiple worlds, list them
1239                         } else if(worldspecs.size() > 1){
1240                                 dstream<<_("Multiple worlds are available.")<<std::endl;
1241                                 dstream<<_("Please select one using --worldname <name>"
1242                                                 " or --world <path>")<<std::endl;
1243                                 print_worldspecs(worldspecs, dstream);
1244                                 return 1;
1245                         // If there are no worlds, automatically create a new one
1246                         } else {
1247                                 // This is the ultimate default world path
1248                                 world_path = porting::path_user + DIR_DELIM + "worlds" +
1249                                                 DIR_DELIM + "world";
1250                                 infostream<<"Creating default world at ["
1251                                                 <<world_path<<"]"<<std::endl;
1252                         }
1253                 }
1254
1255                 if(world_path == ""){
1256                         errorstream<<"No world path specified or found."<<std::endl;
1257                         return 1;
1258                 }
1259                 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1260
1261                 // We need a gamespec.
1262                 SubgameSpec gamespec;
1263                 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1264                 // If world doesn't exist
1265                 if(!getWorldExists(world_path))
1266                 {
1267                         // Try to take gamespec from command line
1268                         if(commanded_gamespec.isValid()){
1269                                 gamespec = commanded_gamespec;
1270                                 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1271                         }
1272                         // Otherwise we will be using "minetest"
1273                         else{
1274                                 gamespec = findSubgame(g_settings->get("default_game"));
1275                                 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1276                         }
1277                 }
1278                 // World exists
1279                 else
1280                 {
1281                         std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1282                         // If commanded to use a gameid, do so
1283                         if(commanded_gamespec.isValid()){
1284                                 gamespec = commanded_gamespec;
1285                                 if(commanded_gamespec.id != world_gameid){
1286                                         errorstream<<"WARNING: Using commanded gameid ["
1287                                                         <<gamespec.id<<"]"<<" instead of world gameid ["
1288                                                         <<world_gameid<<"]"<<std::endl;
1289                                 }
1290                         } else{
1291                                 // If world contains an embedded game, use it;
1292                                 // Otherwise find world from local system.
1293                                 gamespec = findWorldSubgame(world_path);
1294                                 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1295                         }
1296                 }
1297                 if(!gamespec.isValid()){
1298                         errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1299                                         <<std::endl;
1300                         return 1;
1301                 }
1302                 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1303
1304                 // Create server
1305                 Server server(world_path, configpath, gamespec, false);
1306                 server.start(port);
1307                 
1308                 // Run server
1309                 dedicated_server_loop(server, kill);
1310
1311                 return 0;
1312         }
1313
1314 #ifndef SERVER // Exclude from dedicated server build
1315
1316         /*
1317                 More parameters
1318         */
1319         
1320         std::string address = g_settings->get("address");
1321         if(commanded_world != "")
1322                 address = "";
1323         else if(cmd_args.exists("address"))
1324                 address = cmd_args.get("address");
1325         
1326         std::string playername = g_settings->get("name");
1327         if(cmd_args.exists("name"))
1328                 playername = cmd_args.get("name");
1329         
1330         bool skip_main_menu = cmd_args.getFlag("go");
1331
1332         /*
1333                 Device initialization
1334         */
1335
1336         // Resolution selection
1337         
1338         bool fullscreen = g_settings->getBool("fullscreen");
1339         u16 screenW = g_settings->getU16("screenW");
1340         u16 screenH = g_settings->getU16("screenH");
1341
1342         // bpp, fsaa, vsync
1343
1344         bool vsync = g_settings->getBool("vsync");
1345         u16 bits = g_settings->getU16("fullscreen_bpp");
1346         u16 fsaa = g_settings->getU16("fsaa");
1347
1348         // Determine driver
1349
1350         video::E_DRIVER_TYPE driverType;
1351         
1352         std::string driverstring = g_settings->get("video_driver");
1353
1354         if(driverstring == "null")
1355                 driverType = video::EDT_NULL;
1356         else if(driverstring == "software")
1357                 driverType = video::EDT_SOFTWARE;
1358         else if(driverstring == "burningsvideo")
1359                 driverType = video::EDT_BURNINGSVIDEO;
1360         else if(driverstring == "direct3d8")
1361                 driverType = video::EDT_DIRECT3D8;
1362         else if(driverstring == "direct3d9")
1363                 driverType = video::EDT_DIRECT3D9;
1364         else if(driverstring == "opengl")
1365                 driverType = video::EDT_OPENGL;
1366 #ifdef _IRR_COMPILE_WITH_OGLES1_
1367         else if(driverstring == "ogles1")
1368                 driverType = video::EDT_OGLES1;
1369 #endif
1370 #ifdef _IRR_COMPILE_WITH_OGLES2_
1371         else if(driverstring == "ogles2")
1372                 driverType = video::EDT_OGLES2;
1373 #endif
1374         else
1375         {
1376                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1377                                 "to opengl"<<std::endl;
1378                 driverType = video::EDT_OPENGL;
1379         }
1380
1381         /*
1382                 Create device and exit if creation failed
1383         */
1384
1385         MyEventReceiver receiver;
1386
1387         IrrlichtDevice *device;
1388
1389         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1390         params.DriverType    = driverType;
1391         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
1392         params.Bits          = bits;
1393         params.AntiAlias     = fsaa;
1394         params.Fullscreen    = fullscreen;
1395         params.Stencilbuffer = false;
1396         params.Vsync         = vsync;
1397         params.EventReceiver = &receiver;
1398
1399         device = createDeviceEx(params);
1400
1401         if (device == 0)
1402                 return 1; // could not create selected driver.
1403         
1404         /*
1405                 Continue initialization
1406         */
1407
1408         video::IVideoDriver* driver = device->getVideoDriver();
1409
1410         /*
1411                 This changes the minimum allowed number of vertices in a VBO.
1412                 Default is 500.
1413         */
1414         //driver->setMinHardwareBufferVertexCount(50);
1415
1416         // Create time getter
1417         g_timegetter = new IrrlichtTimeGetter(device);
1418         
1419         // Create game callback for menus
1420         g_gamecallback = new MainGameCallback(device);
1421         
1422         /*
1423                 Speed tests (done after irrlicht is loaded to get timer)
1424         */
1425         if(cmd_args.getFlag("speedtests"))
1426         {
1427                 dstream<<"Running speed tests"<<std::endl;
1428                 SpeedTests();
1429                 return 0;
1430         }
1431         
1432         device->setResizable(true);
1433
1434         bool random_input = g_settings->getBool("random_input")
1435                         || cmd_args.getFlag("random-input");
1436         InputHandler *input = NULL;
1437         if(random_input)
1438                 input = new RandomInputHandler();
1439         else
1440                 input = new RealInputHandler(device, &receiver);
1441         
1442         scene::ISceneManager* smgr = device->getSceneManager();
1443
1444         guienv = device->getGUIEnvironment();
1445         gui::IGUISkin* skin = guienv->getSkin();
1446         #if USE_FREETYPE
1447         std::string font_path = g_settings->get("font_path");
1448         u16 font_size = g_settings->getU16("font_size");
1449         gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1450         #else
1451         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1452         #endif
1453         if(font)
1454                 skin->setFont(font);
1455         else
1456                 errorstream<<"WARNING: Font file was not found."
1457                                 " Using default font."<<std::endl;
1458         // If font was not found, this will get us one
1459         font = skin->getFont();
1460         assert(font);
1461         
1462         u32 text_height = font->getDimension(L"Hello, world!").Height;
1463         infostream<<"text_height="<<text_height<<std::endl;
1464
1465         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1466         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1467         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1468         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1469         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1470         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1471         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1472         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1473
1474 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1475         // Irrlicht 1.8 input colours
1476         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1477         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1478 #endif
1479
1480         /*
1481                 GUI stuff
1482         */
1483
1484         ChatBackend chat_backend;
1485
1486         /*
1487                 If an error occurs, this is set to something and the
1488                 menu-game loop is restarted. It is then displayed before
1489                 the menu.
1490         */
1491         std::wstring error_message = L"";
1492
1493         // The password entered during the menu screen,
1494         std::string password;
1495
1496         bool first_loop = true;
1497
1498         /*
1499                 Menu-game loop
1500         */
1501         while(device->run() && kill == false)
1502         {
1503                 // Set the window caption
1504                 wchar_t* text = wgettext("Main Menu");
1505                 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1506                 delete[] text;
1507
1508                 // This is used for catching disconnects
1509                 try
1510                 {
1511
1512                         /*
1513                                 Clear everything from the GUIEnvironment
1514                         */
1515                         guienv->clear();
1516                         
1517                         /*
1518                                 We need some kind of a root node to be able to add
1519                                 custom gui elements directly on the screen.
1520                                 Otherwise they won't be automatically drawn.
1521                         */
1522                         guiroot = guienv->addStaticText(L"",
1523                                         core::rect<s32>(0, 0, 10000, 10000));
1524                         
1525                         SubgameSpec gamespec;
1526                         WorldSpec worldspec;
1527                         bool simple_singleplayer_mode = false;
1528
1529                         // These are set up based on the menu and other things
1530                         std::string current_playername = "inv£lid";
1531                         std::string current_password = "";
1532                         std::string current_address = "does-not-exist";
1533                         int current_port = 0;
1534
1535                         /*
1536                                 Out-of-game menu loop.
1537
1538                                 Loop quits when menu returns proper parameters.
1539                         */
1540                         while(kill == false)
1541                         {
1542                                 // If skip_main_menu, only go through here once
1543                                 if(skip_main_menu && !first_loop){
1544                                         kill = true;
1545                                         break;
1546                                 }
1547                                 first_loop = false;
1548                                 
1549                                 // Cursor can be non-visible when coming from the game
1550                                 device->getCursorControl()->setVisible(true);
1551                                 // Some stuff are left to scene manager when coming from the game
1552                                 // (map at least?)
1553                                 smgr->clear();
1554                                 
1555                                 // Initialize menu data
1556                                 MainMenuData menudata;
1557                                 if(g_settings->exists("selected_mainmenu_tab"))
1558                                         menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1559                                 if(g_settings->exists("selected_serverlist"))
1560                                         menudata.selected_serverlist = g_settings->getS32("selected_serverlist");
1561                                 menudata.address = narrow_to_wide(address);
1562                                 menudata.name = narrow_to_wide(playername);
1563                                 menudata.port = narrow_to_wide(itos(port));
1564                                 if(cmd_args.exists("password"))
1565                                         menudata.password = narrow_to_wide(cmd_args.get("password"));
1566                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1567                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1568                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1569                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1570                                 menudata.mip_map = g_settings->getBool("mip_map");
1571                                 menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter");
1572                                 menudata.bilinear_filter = g_settings->getBool("bilinear_filter");
1573                                 menudata.trilinear_filter = g_settings->getBool("trilinear_filter");
1574                                 menudata.enable_shaders = g_settings->getS32("enable_shaders");
1575                                 menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals");
1576                                 menudata.enable_particles = g_settings->getBool("enable_particles");
1577                                 menudata.liquid_finite = g_settings->getBool("liquid_finite");
1578                                 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map);
1579                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1580                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1581                                 menudata.enable_public = g_settings->getBool("server_announce");
1582                                 // Default to selecting nothing
1583                                 menudata.selected_world = -1;
1584                                 // Get world listing for the menu
1585                                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1586                                 // If there is only one world, select it
1587                                 if(worldspecs.size() == 1){
1588                                         menudata.selected_world = 0;
1589                                 }
1590                                 // Otherwise try to select according to selected_world_path
1591                                 else if(g_settings->exists("selected_world_path")){
1592                                         std::string trypath = g_settings->get("selected_world_path");
1593                                         for(u32 i=0; i<worldspecs.size(); i++){
1594                                                 if(worldspecs[i].path == trypath){
1595                                                         menudata.selected_world = i;
1596                                                         break;
1597                                                 }
1598                                         }
1599                                 }
1600                                 // If a world was commanded, append and select it
1601                                 if(commanded_world != ""){
1602                                         std::string gameid = getWorldGameId(commanded_world, true);
1603                                         std::string name = _("[--world parameter]");
1604                                         if(gameid == ""){
1605                                                 gameid = g_settings->get("default_game");
1606                                                 name += " [new]";
1607                                         }
1608                                         WorldSpec spec(commanded_world, name, gameid);
1609                                         worldspecs.push_back(spec);
1610                                         menudata.selected_world = worldspecs.size()-1;
1611                                 }
1612                                 // Copy worldspecs to menu
1613                                 menudata.worlds = worldspecs;
1614
1615                                 if(skip_main_menu == false)
1616                                 {
1617                                         video::IVideoDriver* driver = device->getVideoDriver();
1618                                         float fps_max = g_settings->getFloat("fps_max");
1619                                         infostream<<"Waiting for other menus"<<std::endl;
1620                                         while(device->run() && kill == false)
1621                                         {
1622                                                 if(noMenuActive())
1623                                                         break;
1624                                                 driver->beginScene(true, true,
1625                                                                 video::SColor(255,128,128,128));
1626                                                 drawMenuBackground(driver);
1627                                                 guienv->drawAll();
1628                                                 driver->endScene();
1629                                                 // On some computers framerate doesn't seem to be
1630                                                 // automatically limited
1631                                                 sleep_ms(25);
1632                                         }
1633                                         infostream<<"Waited for other menus"<<std::endl;
1634
1635                                         GUIMainMenu *menu =
1636                                                         new GUIMainMenu(guienv, guiroot, -1, 
1637                                                                 &g_menumgr, &menudata, g_gamecallback);
1638                                         menu->allowFocusRemoval(true);
1639
1640                                         // Clouds for the main menu
1641                                         bool cloud_menu_background = false;
1642                                         Clouds *clouds = NULL;
1643                                         if (g_settings->getBool("menu_clouds")) {
1644                                                 cloud_menu_background = true;
1645                                                 clouds = new Clouds(smgr->getRootSceneNode(),
1646                                                                                         smgr, -1, rand(), 100);
1647                                                 clouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1648
1649                                                 // A camera to see the clouds
1650                                                 scene::ICameraSceneNode* camera;
1651                                                 camera = smgr->addCameraSceneNode(0,
1652                                                                         v3f(0,0,0), v3f(0, 60, 100));
1653                                                 camera->setFarValue(10000);
1654                                         }
1655
1656                                         if(error_message != L"")
1657                                         {
1658                                                 verbosestream<<"error_message = "
1659                                                                 <<wide_to_narrow(error_message)<<std::endl;
1660
1661                                                 GUIMessageMenu *menu2 =
1662                                                                 new GUIMessageMenu(guienv, guiroot, -1, 
1663                                                                         &g_menumgr, error_message.c_str());
1664                                                 menu2->drop();
1665                                                 error_message = L"";
1666                                         }
1667
1668                                         // Time is in milliseconds, for clouds
1669                                         u32 lasttime = device->getTimer()->getTime();
1670
1671                                         infostream<<"Created main menu"<<std::endl;
1672
1673                                         while(device->run() && kill == false)
1674                                         {
1675                                                 if(menu->getStatus() == true)
1676                                                         break;
1677
1678                                                 // Time calc for the clouds
1679                                                 f32 dtime; // in seconds
1680                                                 if (cloud_menu_background) {
1681                                                         u32 time = device->getTimer()->getTime();
1682                                                         if(time > lasttime)
1683                                                                 dtime = (time - lasttime) / 1000.0;
1684                                                         else
1685                                                                 dtime = 0;
1686                                                         lasttime = time;
1687                                                 }
1688
1689                                                 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1690                                                 driver->beginScene(true, true, video::SColor(255,140,186,250));
1691
1692                                                 if (cloud_menu_background) {
1693                                                         // *3 otherwise the clouds would move very slowly
1694                                                         clouds->step(dtime*3); 
1695                                                         clouds->render();
1696                                                         smgr->drawAll();
1697                                                         drawMenuSplash(driver);
1698                                                         drawMenuFooter(driver, true);
1699                                                         drawMenuHeader(driver);
1700                                                 } else {
1701                                                         drawMenuBackground(driver);
1702                                                         drawMenuFooter(driver, false);
1703                                                 }
1704
1705                                                 guienv->drawAll();
1706
1707                                                 driver->endScene();
1708                                                 
1709                                                 // On some computers framerate doesn't seem to be
1710                                                 // automatically limited
1711                                                 if (cloud_menu_background) {
1712                                                         // Time of frame without fps limit
1713                                                         float busytime;
1714                                                         u32 busytime_u32;
1715                                                         // not using getRealTime is necessary for wine
1716                                                         u32 time = device->getTimer()->getTime();
1717                                                         if(time > lasttime)
1718                                                                 busytime_u32 = time - lasttime;
1719                                                         else
1720                                                                 busytime_u32 = 0;
1721                                                         busytime = busytime_u32 / 1000.0;
1722
1723                                                         // FPS limiter
1724                                                         u32 frametime_min = 1000./fps_max;
1725                         
1726                                                         if(busytime_u32 < frametime_min) {
1727                                                                 u32 sleeptime = frametime_min - busytime_u32;
1728                                                                 device->sleep(sleeptime);
1729                                                         }
1730                                                 } else {
1731                                                         sleep_ms(25);
1732                                                 }
1733                                         }
1734                                         
1735                                         infostream<<"Dropping main menu"<<std::endl;
1736
1737                                         menu->drop();
1738                                         if (cloud_menu_background) {
1739                                                 clouds->drop();
1740                                                 smgr->clear();
1741                                         }
1742                                 }
1743
1744                                 playername = wide_to_narrow(menudata.name);
1745                                 if (playername == "")
1746                                         playername = std::string("Guest") + itos(myrand_range(1000,9999));
1747                                 password = translatePassword(playername, menudata.password);
1748                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1749
1750                                 address = wide_to_narrow(menudata.address);
1751                                 int newport = stoi(wide_to_narrow(menudata.port));
1752                                 if(newport != 0)
1753                                         port = newport;
1754                                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1755                                 // Save settings
1756                                 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1757                                 g_settings->setS32("selected_serverlist", menudata.selected_serverlist);
1758                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1759                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1760                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1761                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1762
1763                                 g_settings->set("mip_map", itos(menudata.mip_map));
1764                                 g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter));
1765                                 g_settings->set("bilinear_filter", itos(menudata.bilinear_filter));
1766                                 g_settings->set("trilinear_filter", itos(menudata.trilinear_filter));
1767
1768                                 g_settings->setS32("enable_shaders", menudata.enable_shaders);
1769                                 g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals));
1770                                 g_settings->set("enable_particles", itos(menudata.enable_particles));
1771                                 g_settings->set("liquid_finite", itos(menudata.liquid_finite));
1772
1773                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1774                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1775                                 g_settings->set("server_announce", itos(menudata.enable_public));
1776                                 g_settings->set("name", playername);
1777                                 g_settings->set("address", address);
1778                                 g_settings->set("port", itos(port));
1779                                 if(menudata.selected_world != -1)
1780                                         g_settings->set("selected_world_path",
1781                                                         worldspecs[menudata.selected_world].path);
1782
1783                                 // Break out of menu-game loop to shut down cleanly
1784                                 if(device->run() == false || kill == true)
1785                                         break;
1786                                 
1787                                 current_playername = playername;
1788                                 current_password = password;
1789                                 current_address = address;
1790                                 current_port = port;
1791
1792                                 // If using simple singleplayer mode, override
1793                                 if(simple_singleplayer_mode){
1794                                         current_playername = "singleplayer";
1795                                         current_password = "";
1796                                         current_address = "";
1797                                         current_port = 30011;
1798                                 }
1799                                 else if (address != "")
1800                                 {
1801                                         ServerListSpec server;
1802                                         server["name"] = menudata.servername;
1803                                         server["address"] = wide_to_narrow(menudata.address);
1804                                         server["port"] = wide_to_narrow(menudata.port);
1805                                         server["description"] = menudata.serverdescription;
1806                                         ServerList::insert(server);
1807                                 }
1808                                 
1809                                 // Set world path to selected one
1810                                 if(menudata.selected_world != -1){
1811                                         worldspec = worldspecs[menudata.selected_world];
1812                                         infostream<<"Selected world: "<<worldspec.name
1813                                                         <<" ["<<worldspec.path<<"]"<<std::endl;
1814                                 }
1815
1816                                 // Only refresh if so requested
1817                                 if(menudata.only_refresh){
1818                                         infostream<<"Refreshing menu"<<std::endl;
1819                                         continue;
1820                                 }
1821                                 
1822                                 // Create new world if requested
1823                                 if(menudata.create_world_name != L"")
1824                                 {
1825                                         std::string path = porting::path_user + DIR_DELIM
1826                                                         "worlds" + DIR_DELIM
1827                                                         + wide_to_narrow(menudata.create_world_name);
1828                                         // Create world if it doesn't exist
1829                                         if(!initializeWorld(path, menudata.create_world_gameid)){
1830                                                 error_message = wgettext("Failed to initialize world");
1831                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1832                                                 continue;
1833                                         }
1834                                         g_settings->set("selected_world_path", path);
1835                                         continue;
1836                                 }
1837
1838                                 // If local game
1839                                 if(current_address == "")
1840                                 {
1841                                         if(menudata.selected_world == -1){
1842                                                 error_message = wgettext("No world selected and no address "
1843                                                                 "provided. Nothing to do.");
1844                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1845                                                 continue;
1846                                         }
1847                                         // Load gamespec for required game
1848                                         gamespec = findWorldSubgame(worldspec.path);
1849                                         if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1850                                                 error_message = wgettext("Could not find or load game \"")
1851                                                                 + narrow_to_wide(worldspec.gameid) + L"\"";
1852                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1853                                                 continue;
1854                                         }
1855                                         if(commanded_gamespec.isValid() &&
1856                                                         commanded_gamespec.id != worldspec.gameid){
1857                                                 errorstream<<"WARNING: Overriding gamespec from \""
1858                                                                 <<worldspec.gameid<<"\" to \""
1859                                                                 <<commanded_gamespec.id<<"\""<<std::endl;
1860                                                 gamespec = commanded_gamespec;
1861                                         }
1862
1863                                         if(!gamespec.isValid()){
1864                                                 error_message = wgettext("Invalid gamespec.");
1865                                                 error_message += L" (world_gameid="
1866                                                                 +narrow_to_wide(worldspec.gameid)+L")";
1867                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1868                                                 continue;
1869                                         }
1870                                 }
1871
1872                                 // Continue to game
1873                                 break;
1874                         }
1875                         
1876                         // Break out of menu-game loop to shut down cleanly
1877                         if(device->run() == false || kill == true)
1878                                 break;
1879
1880                         /*
1881                                 Run game
1882                         */
1883                         the_game(
1884                                 kill,
1885                                 random_input,
1886                                 input,
1887                                 device,
1888                                 font,
1889                                 worldspec.path,
1890                                 current_playername,
1891                                 current_password,
1892                                 current_address,
1893                                 current_port,
1894                                 error_message,
1895                                 configpath,
1896                                 chat_backend,
1897                                 gamespec,
1898                                 simple_singleplayer_mode
1899                         );
1900
1901                 } //try
1902                 catch(con::PeerNotFoundException &e)
1903                 {
1904                         error_message = wgettext("Connection error (timed out?)");
1905                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1906                 }
1907 #ifdef NDEBUG
1908                 catch(std::exception &e)
1909                 {
1910                         std::string narrow_message = "Some exception: \"";
1911                         narrow_message += e.what();
1912                         narrow_message += "\"";
1913                         errorstream<<narrow_message<<std::endl;
1914                         error_message = narrow_to_wide(narrow_message);
1915                 }
1916 #endif
1917
1918                 // If no main menu, show error and exit
1919                 if(skip_main_menu)
1920                 {
1921                         if(error_message != L""){
1922                                 verbosestream<<"error_message = "
1923                                                 <<wide_to_narrow(error_message)<<std::endl;
1924                                 retval = 1;
1925                         }
1926                         break;
1927                 }
1928         } // Menu-game loop
1929         
1930         delete input;
1931
1932         /*
1933                 In the end, delete the Irrlicht device.
1934         */
1935         device->drop();
1936
1937 #endif // !SERVER
1938         
1939         // Update configuration file
1940         if(configpath != "")
1941                 g_settings->updateConfigFile(configpath.c_str());
1942         
1943         // Print modified quicktune values
1944         {
1945                 bool header_printed = false;
1946                 std::vector<std::string> names = getQuicktuneNames();
1947                 for(u32 i=0; i<names.size(); i++){
1948                         QuicktuneValue val = getQuicktuneValue(names[i]);
1949                         if(!val.modified)
1950                                 continue;
1951                         if(!header_printed){
1952                                 dstream<<"Modified quicktune values:"<<std::endl;
1953                                 header_printed = true;
1954                         }
1955                         dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1956                 }
1957         }
1958
1959         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1960         
1961         debugstreams_deinit();
1962         
1963         return retval;
1964 }
1965
1966 //END
1967