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