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