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