]> git.lizzy.rs Git - minetest.git/blob - src/client/clientlauncher.cpp
refacto: RenderingEngine is now better hidden
[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 m_rendering_engine;
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 m_rendering_engine->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 (m_rendering_engine->get_video_driver() == NULL) {
124                 errorstream << "Could not initialize video driver." << std::endl;
125                 return false;
126         }
127
128         m_rendering_engine->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         m_rendering_engine->setResizable(true);
140
141         init_input();
142
143         m_rendering_engine->get_scene_manager()->getParameters()->
144                 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
145
146         guienv = m_rendering_engine->get_gui_env();
147         skin = guienv->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 = m_rendering_engine->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(guienv);
179         FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
180
181         // Irrlicht 1.8 input colours
182         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
183         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
184
185         // Create the menu clouds
186         if (!g_menucloudsmgr)
187                 g_menucloudsmgr = m_rendering_engine->get_scene_manager()->createNewSceneManager();
188         if (!g_menuclouds)
189                 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
190         g_menuclouds->setHeight(100.0f);
191         g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
192         scene::ICameraSceneNode* camera;
193         camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
194         camera->setFarValue(10000);
195
196         /*
197                 GUI stuff
198         */
199
200         ChatBackend chat_backend;
201
202         // If an error occurs, this is set to something by menu().
203         // It is then displayed before the menu shows on the next call to menu()
204         std::string error_message;
205         bool reconnect_requested = false;
206
207         bool first_loop = true;
208
209         /*
210                 Menu-game loop
211         */
212         bool retval = true;
213         bool *kill = porting::signal_handler_killstatus();
214
215         while (m_rendering_engine->run() && !*kill &&
216                 !g_gamecallback->shutdown_requested) {
217                 // Set the window caption
218                 const wchar_t *text = wgettext("Main Menu");
219                 m_rendering_engine->get_raw_device()->
220                         setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
221                         L" " + utf8_to_wide(g_version_hash) +
222                         L" [" + text + L"]").c_str());
223                 delete[] text;
224
225                 try {   // This is used for catching disconnects
226
227                         m_rendering_engine->get_gui_env()->clear();
228
229                         /*
230                                 We need some kind of a root node to be able to add
231                                 custom gui elements directly on the screen.
232                                 Otherwise they won't be automatically drawn.
233                         */
234                         guiroot = m_rendering_engine->get_gui_env()->addStaticText(L"",
235                                 core::rect<s32>(0, 0, 10000, 10000));
236
237                         bool game_has_run = launch_game(error_message, reconnect_requested,
238                                 start_data, cmd_args);
239
240                         // Reset the reconnect_requested flag
241                         reconnect_requested = false;
242
243                         // If skip_main_menu, we only want to startup once
244                         if (skip_main_menu && !first_loop)
245                                 break;
246
247                         first_loop = false;
248
249                         if (!game_has_run) {
250                                 if (skip_main_menu)
251                                         break;
252
253                                 continue;
254                         }
255
256                         // Break out of menu-game loop to shut down cleanly
257                         if (!m_rendering_engine->run() || *kill) {
258                                 if (!g_settings_path.empty())
259                                         g_settings->updateConfigFile(g_settings_path.c_str());
260                                 break;
261                         }
262
263                         m_rendering_engine->get_video_driver()->setTextureCreationFlag(
264                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
265
266 #ifdef HAVE_TOUCHSCREENGUI
267                         receiver->m_touchscreengui = new TouchScreenGUI(m_rendering_engine->get_raw_device(), receiver);
268                         g_touchscreengui = receiver->m_touchscreengui;
269 #endif
270
271                         the_game(
272                                 kill,
273                                 input,
274                                 m_rendering_engine,
275                                 start_data,
276                                 error_message,
277                                 chat_backend,
278                                 &reconnect_requested
279                         );
280                         m_rendering_engine->get_scene_manager()->clear();
281
282 #ifdef HAVE_TOUCHSCREENGUI
283                         delete g_touchscreengui;
284                         g_touchscreengui = NULL;
285                         receiver->m_touchscreengui = NULL;
286 #endif
287
288                 } //try
289                 catch (con::PeerNotFoundException &e) {
290                         error_message = gettext("Connection error (timed out?)");
291                         errorstream << error_message << std::endl;
292                 }
293
294 #ifdef NDEBUG
295                 catch (std::exception &e) {
296                         std::string error_message = "Some exception: \"";
297                         error_message += e.what();
298                         error_message += "\"";
299                         errorstream << error_message << std::endl;
300                 }
301 #endif
302
303                 // If no main menu, show error and exit
304                 if (skip_main_menu) {
305                         if (!error_message.empty()) {
306                                 verbosestream << "error_message = "
307                                               << error_message << std::endl;
308                                 retval = false;
309                         }
310                         break;
311                 }
312         } // Menu-game loop
313
314         g_menuclouds->drop();
315         g_menucloudsmgr->drop();
316
317         return retval;
318 }
319
320 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
321 {
322         skip_main_menu = cmd_args.getFlag("go");
323
324         start_data.address = g_settings->get("address");
325         if (cmd_args.exists("address")) {
326                 // Join a remote server
327                 start_data.address = cmd_args.get("address");
328                 start_data.world_path.clear();
329                 start_data.name = g_settings->get("name");
330         }
331         if (!start_data.world_path.empty()) {
332                 // Start a singleplayer instance
333                 start_data.address = "";
334         }
335
336         if (cmd_args.exists("name"))
337                 start_data.name = cmd_args.get("name");
338
339         list_video_modes = cmd_args.getFlag("videomodes");
340
341         random_input = g_settings->getBool("random_input")
342                         || cmd_args.getFlag("random-input");
343 }
344
345 bool ClientLauncher::init_engine()
346 {
347         receiver = new MyEventReceiver();
348         m_rendering_engine = new RenderingEngine(receiver);
349         return m_rendering_engine->get_raw_device() != nullptr;
350 }
351
352 void ClientLauncher::init_input()
353 {
354         if (random_input)
355                 input = new RandomInputHandler();
356         else
357                 input = new RealInputHandler(receiver);
358
359         if (g_settings->getBool("enable_joysticks")) {
360                 irr::core::array<irr::SJoystickInfo> infos;
361                 std::vector<irr::SJoystickInfo> joystick_infos;
362
363                 // Make sure this is called maximum once per
364                 // irrlicht device, otherwise it will give you
365                 // multiple events for the same joystick.
366                 if (m_rendering_engine->get_raw_device()->activateJoysticks(infos)) {
367                         infostream << "Joystick support enabled" << std::endl;
368                         joystick_infos.reserve(infos.size());
369                         for (u32 i = 0; i < infos.size(); i++) {
370                                 joystick_infos.push_back(infos[i]);
371                         }
372                         input->joystick.onJoystickConnect(joystick_infos);
373                 } else {
374                         errorstream << "Could not activate joystick support." << std::endl;
375                 }
376         }
377 }
378
379 bool ClientLauncher::launch_game(std::string &error_message,
380                 bool reconnect_requested, GameStartData &start_data,
381                 const Settings &cmd_args)
382 {
383         // Prepare and check the start data to launch a game
384         std::string error_message_lua = error_message;
385         error_message.clear();
386
387         if (cmd_args.exists("password"))
388                 start_data.password = cmd_args.get("password");
389
390         if (cmd_args.exists("password-file")) {
391                 std::ifstream passfile(cmd_args.get("password-file"));
392                 if (passfile.good()) {
393                         getline(passfile, start_data.password);
394                 } else {
395                         error_message = gettext("Provided password file "
396                                         "failed to open: ")
397                                         + cmd_args.get("password-file");
398                         errorstream << error_message << std::endl;
399                         return false;
400                 }
401         }
402
403         // If a world was commanded, append and select it
404         // This is provieded by "get_world_from_cmdline()", main.cpp
405         if (!start_data.world_path.empty()) {
406                 auto &spec = start_data.world_spec;
407
408                 spec.path = start_data.world_path;
409                 spec.gameid = getWorldGameId(spec.path, true);
410                 spec.name = _("[--world parameter]");
411
412                 if (spec.gameid.empty()) {      // Create new
413                         spec.gameid = g_settings->get("default_game");
414                         spec.name += " [new]";
415                 }
416         }
417
418         /* Show the GUI menu
419          */
420         std::string server_name, server_description;
421         if (!skip_main_menu) {
422                 // Initialize menu data
423                 // TODO: Re-use existing structs (GameStartData)
424                 MainMenuData menudata;
425                 menudata.address                         = start_data.address;
426                 menudata.name                            = start_data.name;
427                 menudata.password                        = start_data.password;
428                 menudata.port                            = itos(start_data.socket_port);
429                 menudata.script_data.errormessage        = error_message_lua;
430                 menudata.script_data.reconnect_requested = reconnect_requested;
431
432                 main_menu(&menudata);
433
434                 // Skip further loading if there was an exit signal.
435                 if (*porting::signal_handler_killstatus())
436                         return false;
437
438                 if (!menudata.script_data.errormessage.empty()) {
439                         /* The calling function will pass this back into this function upon the
440                          * next iteration (if any) causing it to be displayed by the GUI
441                          */
442                         error_message = menudata.script_data.errormessage;
443                         return false;
444                 }
445
446                 int newport = stoi(menudata.port);
447                 if (newport != 0)
448                         start_data.socket_port = newport;
449
450                 // Update world information using main menu data
451                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
452
453                 int world_index = menudata.selected_world;
454                 if (world_index >= 0 && world_index < (int)worldspecs.size()) {
455                         g_settings->set("selected_world_path",
456                                         worldspecs[world_index].path);
457                         start_data.world_spec = worldspecs[world_index];
458                 }
459
460                 start_data.name = menudata.name;
461                 start_data.password = menudata.password;
462                 start_data.address = std::move(menudata.address);
463                 server_name = menudata.servername;
464                 server_description = menudata.serverdescription;
465
466                 start_data.local_server = !menudata.simple_singleplayer_mode &&
467                         start_data.address.empty();
468         } else {
469                 start_data.local_server = !start_data.world_path.empty() &&
470                         start_data.address.empty() && !start_data.name.empty();
471         }
472
473         if (!m_rendering_engine->run())
474                 return false;
475
476         if (!start_data.isSinglePlayer() && start_data.name.empty()) {
477                 error_message = gettext("Please choose a name!");
478                 errorstream << error_message << std::endl;
479                 return false;
480         }
481
482         // If using simple singleplayer mode, override
483         if (start_data.isSinglePlayer()) {
484                 start_data.name = "singleplayer";
485                 start_data.password = "";
486                 start_data.socket_port = myrand_range(49152, 65535);
487         } else {
488                 g_settings->set("name", start_data.name);
489         }
490
491         if (start_data.name.length() > PLAYERNAME_SIZE - 1) {
492                 error_message = gettext("Player name too long.");
493                 start_data.name.resize(PLAYERNAME_SIZE);
494                 g_settings->set("name", start_data.name);
495                 return false;
496         }
497
498         auto &worldspec = start_data.world_spec;
499         infostream << "Selected world: " << worldspec.name
500                    << " [" << worldspec.path << "]" << std::endl;
501
502         if (start_data.address.empty()) {
503                 // For singleplayer and local server
504                 if (worldspec.path.empty()) {
505                         error_message = gettext("No world selected and no address "
506                                         "provided. Nothing to do.");
507                         errorstream << error_message << std::endl;
508                         return false;
509                 }
510
511                 if (!fs::PathExists(worldspec.path)) {
512                         error_message = gettext("Provided world path doesn't exist: ")
513                                         + worldspec.path;
514                         errorstream << error_message << std::endl;
515                         return false;
516                 }
517
518                 // Load gamespec for required game
519                 start_data.game_spec = findWorldSubgame(worldspec.path);
520                 if (!start_data.game_spec.isValid()) {
521                         error_message = gettext("Could not find or load game \"")
522                                         + worldspec.gameid + "\"";
523                         errorstream << error_message << std::endl;
524                         return false;
525                 }
526
527                 if (porting::signal_handler_killstatus())
528                         return true;
529
530                 if (!start_data.game_spec.isValid()) {
531                         error_message = gettext("Invalid gamespec.");
532                         error_message += " (world.gameid=" + worldspec.gameid + ")";
533                         errorstream << error_message << std::endl;
534                         return false;
535                 }
536         }
537
538         start_data.world_path = start_data.world_spec.path;
539         return true;
540 }
541
542 void ClientLauncher::main_menu(MainMenuData *menudata)
543 {
544         bool *kill = porting::signal_handler_killstatus();
545         video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
546
547         infostream << "Waiting for other menus" << std::endl;
548         while (m_rendering_engine->run() && !*kill) {
549                 if (!isMenuActive())
550                         break;
551                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
552                 m_rendering_engine->get_gui_env()->drawAll();
553                 driver->endScene();
554                 // On some computers framerate doesn't seem to be automatically limited
555                 sleep_ms(25);
556         }
557         infostream << "Waited for other menus" << std::endl;
558
559         // Cursor can be non-visible when coming from the game
560 #ifndef ANDROID
561         m_rendering_engine->get_raw_device()->getCursorControl()->setVisible(true);
562 #endif
563
564         /* show main menu */
565         GUIEngine mymenu(&input->joystick, guiroot, m_rendering_engine, &g_menumgr, menudata, *kill);
566
567         /* leave scene manager in a clean state */
568         m_rendering_engine->get_scene_manager()->clear();
569 }
570
571 void ClientLauncher::speed_tests()
572 {
573         // volatile to avoid some potential compiler optimisations
574         volatile static s16 temp16;
575         volatile static f32 tempf;
576         static v3f tempv3f1;
577         static v3f tempv3f2;
578         static std::string tempstring;
579         static std::string tempstring2;
580
581         tempv3f1 = v3f();
582         tempv3f2 = v3f();
583         tempstring.clear();
584         tempstring2.clear();
585
586         {
587                 infostream << "The following test should take around 20ms." << std::endl;
588                 TimeTaker timer("Testing std::string speed");
589                 const u32 jj = 10000;
590                 for (u32 j = 0; j < jj; j++) {
591                         tempstring = "";
592                         tempstring2 = "";
593                         const u32 ii = 10;
594                         for (u32 i = 0; i < ii; i++) {
595                                 tempstring2 += "asd";
596                         }
597                         for (u32 i = 0; i < ii+1; i++) {
598                                 tempstring += "asd";
599                                 if (tempstring == tempstring2)
600                                         break;
601                         }
602                 }
603         }
604
605         infostream << "All of the following tests should take around 100ms each."
606                    << std::endl;
607
608         {
609                 TimeTaker timer("Testing floating-point conversion speed");
610                 tempf = 0.001;
611                 for (u32 i = 0; i < 4000000; i++) {
612                         temp16 += tempf;
613                         tempf += 0.001;
614                 }
615         }
616
617         {
618                 TimeTaker timer("Testing floating-point vector speed");
619
620                 tempv3f1 = v3f(1, 2, 3);
621                 tempv3f2 = v3f(4, 5, 6);
622                 for (u32 i = 0; i < 10000000; i++) {
623                         tempf += tempv3f1.dotProduct(tempv3f2);
624                         tempv3f2 += v3f(7, 8, 9);
625                 }
626         }
627
628         {
629                 TimeTaker timer("Testing std::map speed");
630
631                 std::map<v2s16, f32> map1;
632                 tempf = -324;
633                 const s16 ii = 300;
634                 for (s16 y = 0; y < ii; y++) {
635                         for (s16 x = 0; x < ii; x++) {
636                                 map1[v2s16(x, y)] =  tempf;
637                                 tempf += 1;
638                         }
639                 }
640                 for (s16 y = ii - 1; y >= 0; y--) {
641                         for (s16 x = 0; x < ii; x++) {
642                                 tempf = map1[v2s16(x, y)];
643                         }
644                 }
645         }
646
647         {
648                 infostream << "Around 5000/ms should do well here." << std::endl;
649                 TimeTaker timer("Testing mutex speed");
650
651                 std::mutex m;
652                 u32 n = 0;
653                 u32 i = 0;
654                 do {
655                         n += 10000;
656                         for (; i < n; i++) {
657                                 m.lock();
658                                 m.unlock();
659                         }
660                 }
661                 // Do at least 10ms
662                 while(timer.getTimerTime() < 10);
663
664                 u32 dtime = timer.stop();
665                 u32 per_ms = n / dtime;
666                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
667         }
668 }