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