Modernize client code (#6250)
[oweals/minetest.git] / src / client / clientlauncher.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 #include "mainmenumanager.h"
21 #include "clouds.h"
22 #include "server.h"
23 #include "filesys.h"
24 #include "guiMainMenu.h"
25 #include "game.h"
26 #include "chat.h"
27 #include "gettext.h"
28 #include "profiler.h"
29 #include "serverlist.h"
30 #include "guiEngine.h"
31 #include "fontengine.h"
32 #include "clientlauncher.h"
33 #include "version.h"
34 #include "renderingengine.h"
35
36 /* mainmenumanager.h
37  */
38 gui::IGUIEnvironment *guienv = nullptr;
39 gui::IGUIStaticText *guiroot = nullptr;
40 MainMenuManager g_menumgr;
41
42 bool isMenuActive()
43 {
44         return g_menumgr.menuCount() != 0;
45 }
46
47 // Passed to menus to allow disconnecting and exiting
48 MainGameCallback *g_gamecallback = nullptr;
49
50
51 ClientLauncher::~ClientLauncher()
52 {
53         delete receiver;
54
55         delete input;
56
57         delete g_fontengine;
58         delete g_gamecallback;
59
60         delete RenderingEngine::get_instance();
61 }
62
63
64 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
65 {
66         init_args(game_params, cmd_args);
67
68         // List video modes if requested
69         if (list_video_modes)
70                 return RenderingEngine::print_video_modes();
71
72         if (!init_engine()) {
73                 errorstream << "Could not initialize game engine." << std::endl;
74                 return false;
75         }
76
77         // Speed tests (done after irrlicht is loaded to get timer)
78         if (cmd_args.getFlag("speedtests")) {
79                 dstream << "Running speed tests" << std::endl;
80                 speed_tests();
81                 return true;
82         }
83
84         video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
85         if (video_driver == NULL) {
86                 errorstream << "Could not initialize video driver." << std::endl;
87                 return false;
88         }
89
90         RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
91         RenderingEngine::get_instance()->setWindowIcon();
92
93         /*
94                 This changes the minimum allowed number of vertices in a VBO.
95                 Default is 500.
96         */
97         //driver->setMinHardwareBufferVertexCount(50);
98
99         // Create game callback for menus
100         g_gamecallback = new MainGameCallback();
101
102         RenderingEngine::get_instance()->setResizable(true);
103
104         init_input();
105
106         RenderingEngine::get_scene_manager()->getParameters()->
107                 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
108
109         guienv = RenderingEngine::get_gui_env();
110         skin = RenderingEngine::get_gui_env()->getSkin();
111         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
112         skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
113         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
114         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
115         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
116         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
117
118         g_fontengine = new FontEngine(g_settings, guienv);
119         FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
120
121 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
122         // Irrlicht 1.8 input colours
123         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
124         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
125 #endif
126
127         // Create the menu clouds
128         if (!g_menucloudsmgr)
129                 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
130         if (!g_menuclouds)
131                 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
132         g_menuclouds->setHeight(100.0f);
133         g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
134         scene::ICameraSceneNode* camera;
135         camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
136         camera->setFarValue(10000);
137
138         /*
139                 GUI stuff
140         */
141
142         ChatBackend chat_backend;
143
144         // If an error occurs, this is set to something by menu().
145         // It is then displayed before the menu shows on the next call to menu()
146         std::string error_message;
147         bool reconnect_requested = false;
148
149         bool first_loop = true;
150
151         /*
152                 Menu-game loop
153         */
154         bool retval = true;
155         bool *kill = porting::signal_handler_killstatus();
156
157         while (RenderingEngine::run() && !*kill &&
158                 !g_gamecallback->shutdown_requested) {
159                 // Set the window caption
160                 const wchar_t *text = wgettext("Main Menu");
161                 RenderingEngine::get_raw_device()->
162                         setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
163                         L" " + utf8_to_wide(g_version_hash) +
164                         L" [" + text + L"]").c_str());
165                 delete[] text;
166
167                 try {   // This is used for catching disconnects
168
169                         RenderingEngine::get_gui_env()->clear();
170
171                         /*
172                                 We need some kind of a root node to be able to add
173                                 custom gui elements directly on the screen.
174                                 Otherwise they won't be automatically drawn.
175                         */
176                         guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
177                                 core::rect<s32>(0, 0, 10000, 10000));
178
179                         bool game_has_run = launch_game(error_message, reconnect_requested,
180                                 game_params, cmd_args);
181
182                         // Reset the reconnect_requested flag
183                         reconnect_requested = false;
184
185                         // If skip_main_menu, we only want to startup once
186                         if (skip_main_menu && !first_loop)
187                                 break;
188
189                         first_loop = false;
190
191                         if (!game_has_run) {
192                                 if (skip_main_menu)
193                                         break;
194
195                                 continue;
196                         }
197
198                         // Break out of menu-game loop to shut down cleanly
199                         if (!RenderingEngine::get_raw_device()->run() || *kill) {
200                                 if (!g_settings_path.empty())
201                                         g_settings->updateConfigFile(g_settings_path.c_str());
202                                 break;
203                         }
204
205                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
206                                 error_message = gettext("Player name too long.");
207                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
208                                 g_settings->set("name", playername);
209                                 continue;
210                         }
211
212                         RenderingEngine::get_video_driver()->setTextureCreationFlag(
213                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
214
215 #ifdef HAVE_TOUCHSCREENGUI
216                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
217                         g_touchscreengui = receiver->m_touchscreengui;
218 #endif
219
220                         the_game(
221                                 kill,
222                                 random_input,
223                                 input,
224                                 worldspec.path,
225                                 current_playername,
226                                 current_password,
227                                 current_address,
228                                 current_port,
229                                 error_message,
230                                 chat_backend,
231                                 &reconnect_requested,
232                                 gamespec,
233                                 simple_singleplayer_mode
234                         );
235                         RenderingEngine::get_scene_manager()->clear();
236
237 #ifdef HAVE_TOUCHSCREENGUI
238                         delete g_touchscreengui;
239                         g_touchscreengui = NULL;
240                         receiver->m_touchscreengui = NULL;
241 #endif
242
243                 } //try
244                 catch (con::PeerNotFoundException &e) {
245                         error_message = gettext("Connection error (timed out?)");
246                         errorstream << error_message << std::endl;
247                 }
248
249 #ifdef NDEBUG
250                 catch (std::exception &e) {
251                         std::string error_message = "Some exception: \"";
252                         error_message += e.what();
253                         error_message += "\"";
254                         errorstream << error_message << std::endl;
255                 }
256 #endif
257
258                 // If no main menu, show error and exit
259                 if (skip_main_menu) {
260                         if (!error_message.empty()) {
261                                 verbosestream << "error_message = "
262                                               << error_message << std::endl;
263                                 retval = false;
264                         }
265                         break;
266                 }
267         } // Menu-game loop
268
269         g_menuclouds->drop();
270         g_menucloudsmgr->drop();
271
272         return retval;
273 }
274
275 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
276 {
277
278         skip_main_menu = cmd_args.getFlag("go");
279
280         // FIXME: This is confusing (but correct)
281
282         /* If world_path is set then override it unless skipping the main menu using
283          * the --go command line param. Else, give preference to the address
284          * supplied on the command line
285          */
286         address = g_settings->get("address");
287         if (!game_params.world_path.empty() && !skip_main_menu)
288                 address = "";
289         else if (cmd_args.exists("address"))
290                 address = cmd_args.get("address");
291
292         playername = g_settings->get("name");
293         if (cmd_args.exists("name"))
294                 playername = cmd_args.get("name");
295
296         list_video_modes = cmd_args.getFlag("videomodes");
297
298         use_freetype = g_settings->getBool("freetype");
299
300         random_input = g_settings->getBool("random_input")
301                         || cmd_args.getFlag("random-input");
302 }
303
304 bool ClientLauncher::init_engine()
305 {
306         receiver = new MyEventReceiver();
307         new RenderingEngine(receiver);
308         return RenderingEngine::get_raw_device() != nullptr;
309 }
310
311 void ClientLauncher::init_input()
312 {
313         if (random_input)
314                 input = new RandomInputHandler();
315         else
316                 input = new RealInputHandler(receiver);
317
318         if (g_settings->getBool("enable_joysticks")) {
319                 irr::core::array<irr::SJoystickInfo> infos;
320                 std::vector<irr::SJoystickInfo> joystick_infos;
321
322                 // Make sure this is called maximum once per
323                 // irrlicht device, otherwise it will give you
324                 // multiple events for the same joystick.
325                 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
326                         infostream << "Joystick support enabled" << std::endl;
327                         joystick_infos.reserve(infos.size());
328                         for (u32 i = 0; i < infos.size(); i++) {
329                                 joystick_infos.push_back(infos[i]);
330                         }
331                         input->joystick.onJoystickConnect(joystick_infos);
332                 } else {
333                         errorstream << "Could not activate joystick support." << std::endl;
334                 }
335         }
336 }
337
338 bool ClientLauncher::launch_game(std::string &error_message,
339                 bool reconnect_requested, GameParams &game_params,
340                 const Settings &cmd_args)
341 {
342         // Initialize menu data
343         MainMenuData menudata;
344         menudata.address                         = address;
345         menudata.name                            = playername;
346         menudata.password                        = password;
347         menudata.port                            = itos(game_params.socket_port);
348         menudata.script_data.errormessage        = error_message;
349         menudata.script_data.reconnect_requested = reconnect_requested;
350
351         error_message.clear();
352
353         if (cmd_args.exists("password"))
354                 menudata.password = cmd_args.get("password");
355
356         // If a world was commanded, append and select it
357         if (!game_params.world_path.empty()) {
358                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
359                 worldspec.name = _("[--world parameter]");
360
361                 if (worldspec.gameid.empty()) { // Create new
362                         worldspec.gameid = g_settings->get("default_game");
363                         worldspec.name += " [new]";
364                 }
365                 worldspec.path = game_params.world_path;
366         }
367
368         /* Show the GUI menu
369          */
370         if (!skip_main_menu) {
371                 main_menu(&menudata);
372
373                 // Skip further loading if there was an exit signal.
374                 if (*porting::signal_handler_killstatus())
375                         return false;
376
377                 address = menudata.address;
378                 int newport = stoi(menudata.port);
379                 if (newport != 0)
380                         game_params.socket_port = newport;
381
382                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
383
384                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
385
386                 if (menudata.selected_world >= 0
387                                 && menudata.selected_world < (int)worldspecs.size()) {
388                         g_settings->set("selected_world_path",
389                                         worldspecs[menudata.selected_world].path);
390                         worldspec = worldspecs[menudata.selected_world];
391                 }
392         }
393
394         if (!menudata.script_data.errormessage.empty()) {
395                 /* The calling function will pass this back into this function upon the
396                  * next iteration (if any) causing it to be displayed by the GUI
397                  */
398                 error_message = menudata.script_data.errormessage;
399                 return false;
400         }
401
402         if (menudata.name.empty() && !simple_singleplayer_mode) {
403                 error_message = gettext("Please choose a name!");
404                 errorstream << error_message << std::endl;
405                 return false;
406         }
407
408         playername = menudata.name;
409         password = menudata.password;
410
411         current_playername = playername;
412         current_password   = password;
413         current_address    = address;
414         current_port       = game_params.socket_port;
415
416         // If using simple singleplayer mode, override
417         if (simple_singleplayer_mode) {
418                 assert(!skip_main_menu);
419                 current_playername = "singleplayer";
420                 current_password = "";
421                 current_address = "";
422                 current_port = myrand_range(49152, 65535);
423         } else {
424                 g_settings->set("name", playername);
425                 if (!address.empty()) {
426                         ServerListSpec server;
427                         server["name"] = menudata.servername;
428                         server["address"] = menudata.address;
429                         server["port"] = menudata.port;
430                         server["description"] = menudata.serverdescription;
431                         ServerList::insert(server);
432                 }
433         }
434
435         infostream << "Selected world: " << worldspec.name
436                    << " [" << worldspec.path << "]" << std::endl;
437
438         if (current_address.empty()) { // If local game
439                 if (worldspec.path.empty()) {
440                         error_message = gettext("No world selected and no address "
441                                         "provided. Nothing to do.");
442                         errorstream << error_message << std::endl;
443                         return false;
444                 }
445
446                 if (!fs::PathExists(worldspec.path)) {
447                         error_message = gettext("Provided world path doesn't exist: ")
448                                         + worldspec.path;
449                         errorstream << error_message << std::endl;
450                         return false;
451                 }
452
453                 // Load gamespec for required game
454                 gamespec = findWorldSubgame(worldspec.path);
455                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
456                         error_message = gettext("Could not find or load game \"")
457                                         + worldspec.gameid + "\"";
458                         errorstream << error_message << std::endl;
459                         return false;
460                 }
461
462                 if (porting::signal_handler_killstatus())
463                         return true;
464
465                 if (game_params.game_spec.isValid() &&
466                                 game_params.game_spec.id != worldspec.gameid) {
467                         warningstream << "Overriding gamespec from \""
468                                     << worldspec.gameid << "\" to \""
469                                     << game_params.game_spec.id << "\"" << std::endl;
470                         gamespec = game_params.game_spec;
471                 }
472
473                 if (!gamespec.isValid()) {
474                         error_message = gettext("Invalid gamespec.");
475                         error_message += " (world.gameid=" + worldspec.gameid + ")";
476                         errorstream << error_message << std::endl;
477                         return false;
478                 }
479         }
480
481         return true;
482 }
483
484 void ClientLauncher::main_menu(MainMenuData *menudata)
485 {
486         bool *kill = porting::signal_handler_killstatus();
487         video::IVideoDriver *driver = RenderingEngine::get_video_driver();
488
489         infostream << "Waiting for other menus" << std::endl;
490         while (RenderingEngine::get_raw_device()->run() && !*kill) {
491                 if (!isMenuActive())
492                         break;
493                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
494                 RenderingEngine::get_gui_env()->drawAll();
495                 driver->endScene();
496                 // On some computers framerate doesn't seem to be automatically limited
497                 sleep_ms(25);
498         }
499         infostream << "Waited for other menus" << std::endl;
500
501         // Cursor can be non-visible when coming from the game
502 #ifndef ANDROID
503         RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
504 #endif
505
506         /* show main menu */
507         GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
508
509         /* leave scene manager in a clean state */
510         RenderingEngine::get_scene_manager()->clear();
511 }
512
513 void ClientLauncher::speed_tests()
514 {
515         // volatile to avoid some potential compiler optimisations
516         volatile static s16 temp16;
517         volatile static f32 tempf;
518         static v3f tempv3f1;
519         static v3f tempv3f2;
520         static std::string tempstring;
521         static std::string tempstring2;
522
523         tempv3f1 = v3f();
524         tempv3f2 = v3f();
525         tempstring.clear();
526         tempstring2.clear();
527
528         {
529                 infostream << "The following test should take around 20ms." << std::endl;
530                 TimeTaker timer("Testing std::string speed");
531                 const u32 jj = 10000;
532                 for (u32 j = 0; j < jj; j++) {
533                         tempstring = "";
534                         tempstring2 = "";
535                         const u32 ii = 10;
536                         for (u32 i = 0; i < ii; i++) {
537                                 tempstring2 += "asd";
538                         }
539                         for (u32 i = 0; i < ii+1; i++) {
540                                 tempstring += "asd";
541                                 if (tempstring == tempstring2)
542                                         break;
543                         }
544                 }
545         }
546
547         infostream << "All of the following tests should take around 100ms each."
548                    << std::endl;
549
550         {
551                 TimeTaker timer("Testing floating-point conversion speed");
552                 tempf = 0.001;
553                 for (u32 i = 0; i < 4000000; i++) {
554                         temp16 += tempf;
555                         tempf += 0.001;
556                 }
557         }
558
559         {
560                 TimeTaker timer("Testing floating-point vector speed");
561
562                 tempv3f1 = v3f(1, 2, 3);
563                 tempv3f2 = v3f(4, 5, 6);
564                 for (u32 i = 0; i < 10000000; i++) {
565                         tempf += tempv3f1.dotProduct(tempv3f2);
566                         tempv3f2 += v3f(7, 8, 9);
567                 }
568         }
569
570         {
571                 TimeTaker timer("Testing std::map speed");
572
573                 std::map<v2s16, f32> map1;
574                 tempf = -324;
575                 const s16 ii = 300;
576                 for (s16 y = 0; y < ii; y++) {
577                         for (s16 x = 0; x < ii; x++) {
578                                 map1[v2s16(x, y)] =  tempf;
579                                 tempf += 1;
580                         }
581                 }
582                 for (s16 y = ii - 1; y >= 0; y--) {
583                         for (s16 x = 0; x < ii; x++) {
584                                 tempf = map1[v2s16(x, y)];
585                         }
586                 }
587         }
588
589         {
590                 infostream << "Around 5000/ms should do well here." << std::endl;
591                 TimeTaker timer("Testing mutex speed");
592
593                 std::mutex m;
594                 u32 n = 0;
595                 u32 i = 0;
596                 do {
597                         n += 10000;
598                         for (; i < n; i++) {
599                                 m.lock();
600                                 m.unlock();
601                         }
602                 }
603                 // Do at least 10ms
604                 while(timer.getTimerTime() < 10);
605
606                 u32 dtime = timer.stop();
607                 u32 per_ms = n / dtime;
608                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
609         }
610 }