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