3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "gui/mainmenumanager.h"
24 #include "gui/guiMainMenu.h"
30 #include "serverlist.h"
31 #include "gui/guiEngine.h"
32 #include "fontengine.h"
33 #include "clientlauncher.h"
35 #include "renderingengine.h"
36 #include "network/networkexceptions.h"
39 #include "sound_openal.h"
47 gui::IGUIEnvironment *guienv = nullptr;
48 gui::IGUIStaticText *guiroot = nullptr;
49 MainMenuManager g_menumgr;
53 return g_menumgr.menuCount() != 0;
56 // Passed to menus to allow disconnecting and exiting
57 MainGameCallback *g_gamecallback = nullptr;
60 // This can be helpful for the next code cleanup
61 static void dump_start_data(const GameStartData &data)
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;
74 ClientLauncher::~ClientLauncher()
81 delete g_gamecallback;
83 delete m_rendering_engine;
86 g_sound_manager_singleton.reset();
91 bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
93 /* This function is called when a client must be started.
95 * - Singleplayer (address but map provided)
96 * - Join server (no map but address provided)
97 * - Local server (for main menu only)
100 init_args(start_data, cmd_args);
102 // List video modes if requested
103 if (list_video_modes)
104 return m_rendering_engine->print_video_modes();
107 if (g_settings->getBool("enable_sound"))
108 g_sound_manager_singleton = createSoundManagerSingleton();
111 if (!init_engine()) {
112 errorstream << "Could not initialize game engine." << std::endl;
116 // Speed tests (done after irrlicht is loaded to get timer)
117 if (cmd_args.getFlag("speedtests")) {
118 dstream << "Running speed tests" << std::endl;
123 if (m_rendering_engine->get_video_driver() == NULL) {
124 errorstream << "Could not initialize video driver." << std::endl;
128 m_rendering_engine->setupTopLevelWindow(PROJECT_NAME_C);
131 This changes the minimum allowed number of vertices in a VBO.
134 //driver->setMinHardwareBufferVertexCount(50);
136 // Create game callback for menus
137 g_gamecallback = new MainGameCallback();
139 m_rendering_engine->setResizable(true);
143 m_rendering_engine->get_scene_manager()->getParameters()->
144 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
146 guienv = m_rendering_engine->get_gui_env();
147 skin = guienv->getSkin();
148 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
149 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
150 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
151 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
152 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
153 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
155 float density = porting::getDisplayDensity();
156 skin->setSize(gui::EGDS_CHECK_BOX_WIDTH, (s32)(17.0f * density));
157 skin->setSize(gui::EGDS_SCROLLBAR_SIZE, (s32)(14.0f * density));
158 skin->setSize(gui::EGDS_WINDOW_BUTTON_WIDTH, (s32)(15.0f * density));
159 if (density > 1.5f) {
160 std::string sprite_path = porting::path_user + "/textures/base/pack/";
162 sprite_path.append("checkbox_64.png");
163 else if (density > 2.0f)
164 sprite_path.append("checkbox_32.png");
166 sprite_path.append("checkbox_16.png");
167 // Texture dimensions should be a power of 2
168 gui::IGUISpriteBank *sprites = skin->getSpriteBank();
169 video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
170 video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str());
171 if (sprite_texture) {
172 s32 sprite_id = sprites->addTextureAsSprite(sprite_texture);
174 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
178 g_fontengine = new FontEngine(guienv);
179 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
181 // Irrlicht 1.8 input colours
182 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
183 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
185 // Create the menu clouds
186 if (!g_menucloudsmgr)
187 g_menucloudsmgr = m_rendering_engine->get_scene_manager()->createNewSceneManager();
189 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
190 g_menuclouds->setHeight(100.0f);
191 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
192 scene::ICameraSceneNode* camera;
193 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
194 camera->setFarValue(10000);
200 ChatBackend chat_backend;
202 // If an error occurs, this is set to something by menu().
203 // It is then displayed before the menu shows on the next call to menu()
204 std::string error_message;
205 bool reconnect_requested = false;
207 bool first_loop = true;
213 bool *kill = porting::signal_handler_killstatus();
215 while (m_rendering_engine->run() && !*kill &&
216 !g_gamecallback->shutdown_requested) {
217 // Set the window caption
218 const wchar_t *text = wgettext("Main Menu");
219 m_rendering_engine->get_raw_device()->
220 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
221 L" " + utf8_to_wide(g_version_hash) +
222 L" [" + text + L"]").c_str());
225 try { // This is used for catching disconnects
227 m_rendering_engine->get_gui_env()->clear();
230 We need some kind of a root node to be able to add
231 custom gui elements directly on the screen.
232 Otherwise they won't be automatically drawn.
234 guiroot = m_rendering_engine->get_gui_env()->addStaticText(L"",
235 core::rect<s32>(0, 0, 10000, 10000));
237 bool game_has_run = launch_game(error_message, reconnect_requested,
238 start_data, cmd_args);
240 // Reset the reconnect_requested flag
241 reconnect_requested = false;
243 // If skip_main_menu, we only want to startup once
244 if (skip_main_menu && !first_loop)
256 // Break out of menu-game loop to shut down cleanly
257 if (!m_rendering_engine->run() || *kill) {
258 if (!g_settings_path.empty())
259 g_settings->updateConfigFile(g_settings_path.c_str());
263 m_rendering_engine->get_video_driver()->setTextureCreationFlag(
264 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
266 #ifdef HAVE_TOUCHSCREENGUI
267 receiver->m_touchscreengui = new TouchScreenGUI(m_rendering_engine->get_raw_device(), receiver);
268 g_touchscreengui = receiver->m_touchscreengui;
280 m_rendering_engine->get_scene_manager()->clear();
282 #ifdef HAVE_TOUCHSCREENGUI
283 delete g_touchscreengui;
284 g_touchscreengui = NULL;
285 receiver->m_touchscreengui = NULL;
289 catch (con::PeerNotFoundException &e) {
290 error_message = gettext("Connection error (timed out?)");
291 errorstream << error_message << std::endl;
295 catch (std::exception &e) {
296 std::string error_message = "Some exception: \"";
297 error_message += e.what();
298 error_message += "\"";
299 errorstream << error_message << std::endl;
303 // If no main menu, show error and exit
304 if (skip_main_menu) {
305 if (!error_message.empty()) {
306 verbosestream << "error_message = "
307 << error_message << std::endl;
314 g_menuclouds->drop();
315 g_menucloudsmgr->drop();
320 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
322 skip_main_menu = cmd_args.getFlag("go");
324 start_data.address = g_settings->get("address");
325 if (cmd_args.exists("address")) {
326 // Join a remote server
327 start_data.address = cmd_args.get("address");
328 start_data.world_path.clear();
329 start_data.name = g_settings->get("name");
331 if (!start_data.world_path.empty()) {
332 // Start a singleplayer instance
333 start_data.address = "";
336 if (cmd_args.exists("name"))
337 start_data.name = cmd_args.get("name");
339 list_video_modes = cmd_args.getFlag("videomodes");
341 random_input = g_settings->getBool("random_input")
342 || cmd_args.getFlag("random-input");
345 bool ClientLauncher::init_engine()
347 receiver = new MyEventReceiver();
348 m_rendering_engine = new RenderingEngine(receiver);
349 return m_rendering_engine->get_raw_device() != nullptr;
352 void ClientLauncher::init_input()
355 input = new RandomInputHandler();
357 input = new RealInputHandler(receiver);
359 if (g_settings->getBool("enable_joysticks")) {
360 irr::core::array<irr::SJoystickInfo> infos;
361 std::vector<irr::SJoystickInfo> joystick_infos;
363 // Make sure this is called maximum once per
364 // irrlicht device, otherwise it will give you
365 // multiple events for the same joystick.
366 if (m_rendering_engine->get_raw_device()->activateJoysticks(infos)) {
367 infostream << "Joystick support enabled" << std::endl;
368 joystick_infos.reserve(infos.size());
369 for (u32 i = 0; i < infos.size(); i++) {
370 joystick_infos.push_back(infos[i]);
372 input->joystick.onJoystickConnect(joystick_infos);
374 errorstream << "Could not activate joystick support." << std::endl;
379 bool ClientLauncher::launch_game(std::string &error_message,
380 bool reconnect_requested, GameStartData &start_data,
381 const Settings &cmd_args)
383 // Prepare and check the start data to launch a game
384 std::string error_message_lua = error_message;
385 error_message.clear();
387 if (cmd_args.exists("password"))
388 start_data.password = cmd_args.get("password");
390 if (cmd_args.exists("password-file")) {
391 std::ifstream passfile(cmd_args.get("password-file"));
392 if (passfile.good()) {
393 getline(passfile, start_data.password);
395 error_message = gettext("Provided password file "
397 + cmd_args.get("password-file");
398 errorstream << error_message << std::endl;
403 // If a world was commanded, append and select it
404 // This is provieded by "get_world_from_cmdline()", main.cpp
405 if (!start_data.world_path.empty()) {
406 auto &spec = start_data.world_spec;
408 spec.path = start_data.world_path;
409 spec.gameid = getWorldGameId(spec.path, true);
410 spec.name = _("[--world parameter]");
412 if (spec.gameid.empty()) { // Create new
413 spec.gameid = g_settings->get("default_game");
414 spec.name += " [new]";
420 std::string server_name, server_description;
421 if (!skip_main_menu) {
422 // Initialize menu data
423 // TODO: Re-use existing structs (GameStartData)
424 MainMenuData menudata;
425 menudata.address = start_data.address;
426 menudata.name = start_data.name;
427 menudata.password = start_data.password;
428 menudata.port = itos(start_data.socket_port);
429 menudata.script_data.errormessage = error_message_lua;
430 menudata.script_data.reconnect_requested = reconnect_requested;
432 main_menu(&menudata);
434 // Skip further loading if there was an exit signal.
435 if (*porting::signal_handler_killstatus())
438 if (!menudata.script_data.errormessage.empty()) {
439 /* The calling function will pass this back into this function upon the
440 * next iteration (if any) causing it to be displayed by the GUI
442 error_message = menudata.script_data.errormessage;
446 int newport = stoi(menudata.port);
448 start_data.socket_port = newport;
450 // Update world information using main menu data
451 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
453 int world_index = menudata.selected_world;
454 if (world_index >= 0 && world_index < (int)worldspecs.size()) {
455 g_settings->set("selected_world_path",
456 worldspecs[world_index].path);
457 start_data.world_spec = worldspecs[world_index];
460 start_data.name = menudata.name;
461 start_data.password = menudata.password;
462 start_data.address = std::move(menudata.address);
463 server_name = menudata.servername;
464 server_description = menudata.serverdescription;
466 start_data.local_server = !menudata.simple_singleplayer_mode &&
467 start_data.address.empty();
469 start_data.local_server = !start_data.world_path.empty() &&
470 start_data.address.empty() && !start_data.name.empty();
473 if (!m_rendering_engine->run())
476 if (!start_data.isSinglePlayer() && start_data.name.empty()) {
477 error_message = gettext("Please choose a name!");
478 errorstream << error_message << std::endl;
482 // If using simple singleplayer mode, override
483 if (start_data.isSinglePlayer()) {
484 start_data.name = "singleplayer";
485 start_data.password = "";
486 start_data.socket_port = myrand_range(49152, 65535);
488 g_settings->set("name", start_data.name);
491 if (start_data.name.length() > PLAYERNAME_SIZE - 1) {
492 error_message = gettext("Player name too long.");
493 start_data.name.resize(PLAYERNAME_SIZE);
494 g_settings->set("name", start_data.name);
498 auto &worldspec = start_data.world_spec;
499 infostream << "Selected world: " << worldspec.name
500 << " [" << worldspec.path << "]" << std::endl;
502 if (start_data.address.empty()) {
503 // For singleplayer and local server
504 if (worldspec.path.empty()) {
505 error_message = gettext("No world selected and no address "
506 "provided. Nothing to do.");
507 errorstream << error_message << std::endl;
511 if (!fs::PathExists(worldspec.path)) {
512 error_message = gettext("Provided world path doesn't exist: ")
514 errorstream << error_message << std::endl;
518 // Load gamespec for required game
519 start_data.game_spec = findWorldSubgame(worldspec.path);
520 if (!start_data.game_spec.isValid()) {
521 error_message = gettext("Could not find or load game \"")
522 + worldspec.gameid + "\"";
523 errorstream << error_message << std::endl;
527 if (porting::signal_handler_killstatus())
530 if (!start_data.game_spec.isValid()) {
531 error_message = gettext("Invalid gamespec.");
532 error_message += " (world.gameid=" + worldspec.gameid + ")";
533 errorstream << error_message << std::endl;
538 start_data.world_path = start_data.world_spec.path;
542 void ClientLauncher::main_menu(MainMenuData *menudata)
544 bool *kill = porting::signal_handler_killstatus();
545 video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
547 infostream << "Waiting for other menus" << std::endl;
548 while (m_rendering_engine->run() && !*kill) {
551 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
552 m_rendering_engine->get_gui_env()->drawAll();
554 // On some computers framerate doesn't seem to be automatically limited
557 infostream << "Waited for other menus" << std::endl;
559 // Cursor can be non-visible when coming from the game
561 m_rendering_engine->get_raw_device()->getCursorControl()->setVisible(true);
565 GUIEngine mymenu(&input->joystick, guiroot, m_rendering_engine, &g_menumgr, menudata, *kill);
567 /* leave scene manager in a clean state */
568 m_rendering_engine->get_scene_manager()->clear();
571 void ClientLauncher::speed_tests()
573 // volatile to avoid some potential compiler optimisations
574 volatile static s16 temp16;
575 volatile static f32 tempf;
578 static std::string tempstring;
579 static std::string tempstring2;
587 infostream << "The following test should take around 20ms." << std::endl;
588 TimeTaker timer("Testing std::string speed");
589 const u32 jj = 10000;
590 for (u32 j = 0; j < jj; j++) {
594 for (u32 i = 0; i < ii; i++) {
595 tempstring2 += "asd";
597 for (u32 i = 0; i < ii+1; i++) {
599 if (tempstring == tempstring2)
605 infostream << "All of the following tests should take around 100ms each."
609 TimeTaker timer("Testing floating-point conversion speed");
611 for (u32 i = 0; i < 4000000; i++) {
618 TimeTaker timer("Testing floating-point vector speed");
620 tempv3f1 = v3f(1, 2, 3);
621 tempv3f2 = v3f(4, 5, 6);
622 for (u32 i = 0; i < 10000000; i++) {
623 tempf += tempv3f1.dotProduct(tempv3f2);
624 tempv3f2 += v3f(7, 8, 9);
629 TimeTaker timer("Testing std::map speed");
631 std::map<v2s16, f32> map1;
634 for (s16 y = 0; y < ii; y++) {
635 for (s16 x = 0; x < ii; x++) {
636 map1[v2s16(x, y)] = tempf;
640 for (s16 y = ii - 1; y >= 0; y--) {
641 for (s16 x = 0; x < ii; x++) {
642 tempf = map1[v2s16(x, y)];
648 infostream << "Around 5000/ms should do well here." << std::endl;
649 TimeTaker timer("Testing mutex speed");
662 while(timer.getTimerTime() < 10);
664 u32 dtime = timer.stop();
665 u32 per_ms = n / dtime;
666 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;