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