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);
103 if (g_settings->getBool("enable_sound"))
104 g_sound_manager_singleton = createSoundManagerSingleton();
107 if (!init_engine()) {
108 errorstream << "Could not initialize game engine." << std::endl;
112 // Speed tests (done after irrlicht is loaded to get timer)
113 if (cmd_args.getFlag("speedtests")) {
114 dstream << "Running speed tests" << std::endl;
119 if (m_rendering_engine->get_video_driver() == NULL) {
120 errorstream << "Could not initialize video driver." << std::endl;
124 m_rendering_engine->setupTopLevelWindow(PROJECT_NAME_C);
127 This changes the minimum allowed number of vertices in a VBO.
130 //driver->setMinHardwareBufferVertexCount(50);
132 // Create game callback for menus
133 g_gamecallback = new MainGameCallback();
135 m_rendering_engine->setResizable(true);
139 m_rendering_engine->get_scene_manager()->getParameters()->
140 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
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));
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/";
158 sprite_path.append("checkbox_64.png");
159 else if (density > 2.0f)
160 sprite_path.append("checkbox_32.png");
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);
170 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
174 g_fontengine = new FontEngine(guienv);
175 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
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));
181 // Create the menu clouds
182 if (!g_menucloudsmgr)
183 g_menucloudsmgr = m_rendering_engine->get_scene_manager()->createNewSceneManager();
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);
196 ChatBackend chat_backend;
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;
203 bool first_loop = true;
209 bool *kill = porting::signal_handler_killstatus();
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());
221 try { // This is used for catching disconnects
223 m_rendering_engine->get_gui_env()->clear();
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.
230 guiroot = m_rendering_engine->get_gui_env()->addStaticText(L"",
231 core::rect<s32>(0, 0, 10000, 10000));
233 bool game_has_run = launch_game(error_message, reconnect_requested,
234 start_data, cmd_args);
236 // Reset the reconnect_requested flag
237 reconnect_requested = false;
239 // If skip_main_menu, we only want to startup once
240 if (skip_main_menu && !first_loop)
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());
259 m_rendering_engine->get_video_driver()->setTextureCreationFlag(
260 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
262 #ifdef HAVE_TOUCHSCREENGUI
263 receiver->m_touchscreengui = new TouchScreenGUI(m_rendering_engine->get_raw_device(), receiver);
264 g_touchscreengui = receiver->m_touchscreengui;
277 catch (con::PeerNotFoundException &e) {
278 error_message = gettext("Connection error (timed out?)");
279 errorstream << error_message << std::endl;
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;
291 m_rendering_engine->get_scene_manager()->clear();
293 #ifdef HAVE_TOUCHSCREENGUI
294 delete g_touchscreengui;
295 g_touchscreengui = NULL;
296 receiver->m_touchscreengui = NULL;
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;
310 g_menuclouds->drop();
311 g_menucloudsmgr->drop();
316 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
318 skip_main_menu = cmd_args.getFlag("go");
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");
327 if (!start_data.world_path.empty()) {
328 // Start a singleplayer instance
329 start_data.address = "";
332 if (cmd_args.exists("name"))
333 start_data.name = cmd_args.get("name");
335 random_input = g_settings->getBool("random_input")
336 || cmd_args.getFlag("random-input");
339 bool ClientLauncher::init_engine()
341 receiver = new MyEventReceiver();
342 m_rendering_engine = new RenderingEngine(receiver);
343 return m_rendering_engine->get_raw_device() != nullptr;
346 void ClientLauncher::init_input()
349 input = new RandomInputHandler();
351 input = new RealInputHandler(receiver);
353 if (g_settings->getBool("enable_joysticks")) {
354 irr::core::array<irr::SJoystickInfo> infos;
355 std::vector<irr::SJoystickInfo> joystick_infos;
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]);
366 input->joystick.onJoystickConnect(joystick_infos);
368 errorstream << "Could not activate joystick support." << std::endl;
373 bool ClientLauncher::launch_game(std::string &error_message,
374 bool reconnect_requested, GameStartData &start_data,
375 const Settings &cmd_args)
377 // Prepare and check the start data to launch a game
378 std::string error_message_lua = error_message;
379 error_message.clear();
381 if (cmd_args.exists("password"))
382 start_data.password = cmd_args.get("password");
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);
389 error_message = gettext("Provided password file "
391 + cmd_args.get("password-file");
392 errorstream << error_message << std::endl;
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;
402 spec.path = start_data.world_path;
403 spec.gameid = getWorldGameId(spec.path, true);
404 spec.name = _("[--world parameter]");
406 if (spec.gameid.empty()) { // Create new
407 spec.gameid = g_settings->get("default_game");
408 spec.name += " [new]";
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;
426 main_menu(&menudata);
428 // Skip further loading if there was an exit signal.
429 if (*porting::signal_handler_killstatus())
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
436 error_message = menudata.script_data.errormessage;
440 int newport = stoi(menudata.port);
442 start_data.socket_port = newport;
444 // Update world information using main menu data
445 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
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];
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;
460 start_data.local_server = !menudata.simple_singleplayer_mode &&
461 start_data.address.empty();
463 start_data.local_server = !start_data.world_path.empty() &&
464 start_data.address.empty() && !start_data.name.empty();
467 if (!m_rendering_engine->run())
470 if (!start_data.isSinglePlayer() && start_data.name.empty()) {
471 error_message = gettext("Please choose a name!");
472 errorstream << error_message << std::endl;
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);
482 g_settings->set("name", start_data.name);
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);
492 auto &worldspec = start_data.world_spec;
493 infostream << "Selected world: " << worldspec.name
494 << " [" << worldspec.path << "]" << std::endl;
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;
505 if (!fs::PathExists(worldspec.path)) {
506 error_message = gettext("Provided world path doesn't exist: ")
508 errorstream << error_message << std::endl;
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: ")
517 errorstream << error_message << std::endl;
521 if (porting::signal_handler_killstatus())
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;
532 start_data.world_path = start_data.world_spec.path;
536 void ClientLauncher::main_menu(MainMenuData *menudata)
538 bool *kill = porting::signal_handler_killstatus();
539 video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
541 infostream << "Waiting for other menus" << std::endl;
542 while (m_rendering_engine->run() && !*kill) {
545 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
546 m_rendering_engine->get_gui_env()->drawAll();
548 // On some computers framerate doesn't seem to be automatically limited
551 infostream << "Waited for other menus" << std::endl;
553 // Cursor can be non-visible when coming from the game
555 m_rendering_engine->get_raw_device()->getCursorControl()->setVisible(true);
559 GUIEngine mymenu(&input->joystick, guiroot, m_rendering_engine, &g_menumgr, menudata, *kill);
561 /* leave scene manager in a clean state */
562 m_rendering_engine->get_scene_manager()->clear();
565 void ClientLauncher::speed_tests()
567 // volatile to avoid some potential compiler optimisations
568 volatile static s16 temp16;
569 volatile static f32 tempf;
572 static std::string tempstring;
573 static std::string tempstring2;
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++) {
588 for (u32 i = 0; i < ii; i++) {
589 tempstring2 += "asd";
591 for (u32 i = 0; i < ii+1; i++) {
593 if (tempstring == tempstring2)
599 infostream << "All of the following tests should take around 100ms each."
603 TimeTaker timer("Testing floating-point conversion speed");
605 for (u32 i = 0; i < 4000000; i++) {
612 TimeTaker timer("Testing floating-point vector speed");
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);
623 TimeTaker timer("Testing std::map speed");
625 std::map<v2s16, f32> map1;
628 for (s16 y = 0; y < ii; y++) {
629 for (s16 x = 0; x < ii; x++) {
630 map1[v2s16(x, y)] = tempf;
634 for (s16 y = ii - 1; y >= 0; y--) {
635 for (s16 x = 0; x < ii; x++) {
636 tempf = map1[v2s16(x, y)];
642 infostream << "Around 5000/ms should do well here." << std::endl;
643 TimeTaker timer("Testing mutex speed");
656 while(timer.getTimerTime() < 10);
658 u32 dtime = timer.stop();
659 u32 per_ms = n / dtime;
660 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;