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