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