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 RenderingEngine::get_instance();
86 g_sound_manager_singleton.reset();
90 bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
92 /* This function is called when a client must be started.
94 * - Singleplayer (address but map provided)
95 * - Join server (no map but address provided)
96 * - Local server (for main menu only)
99 init_args(start_data, cmd_args);
101 // List video modes if requested
102 if (list_video_modes)
103 return RenderingEngine::print_video_modes();
106 if (g_settings->getBool("enable_sound"))
107 g_sound_manager_singleton = createSoundManagerSingleton();
110 if (!init_engine()) {
111 errorstream << "Could not initialize game engine." << std::endl;
115 // Speed tests (done after irrlicht is loaded to get timer)
116 if (cmd_args.getFlag("speedtests")) {
117 dstream << "Running speed tests" << std::endl;
122 if (RenderingEngine::get_video_driver() == NULL) {
123 errorstream << "Could not initialize video driver." << std::endl;
127 RenderingEngine::get_instance()->setupTopLevelWindow(PROJECT_NAME_C);
130 This changes the minimum allowed number of vertices in a VBO.
133 // driver->setMinHardwareBufferVertexCount(50);
135 // Create game callback for menus
136 g_gamecallback = new MainGameCallback();
138 RenderingEngine::get_instance()->setResizable(true);
142 RenderingEngine::get_scene_manager()->getParameters()->setAttribute(
143 scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
145 guienv = RenderingEngine::get_gui_env();
146 skin = RenderingEngine::get_gui_env()->getSkin();
147 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
148 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
149 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
150 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
151 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
152 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
154 float density = porting::getDisplayDensity();
155 skin->setSize(gui::EGDS_CHECK_BOX_WIDTH, (s32)(17.0f * density));
156 skin->setSize(gui::EGDS_SCROLLBAR_SIZE, (s32)(14.0f * density));
157 skin->setSize(gui::EGDS_WINDOW_BUTTON_WIDTH, (s32)(15.0f * density));
158 if (density > 1.5f) {
159 std::string sprite_path = porting::path_user + "/textures/base/pack/";
161 sprite_path.append("checkbox_64.png");
162 else if (density > 2.0f)
163 sprite_path.append("checkbox_32.png");
165 sprite_path.append("checkbox_16.png");
166 // Texture dimensions should be a power of 2
167 gui::IGUISpriteBank *sprites = skin->getSpriteBank();
168 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
169 video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str());
170 if (sprite_texture) {
171 s32 sprite_id = sprites->addTextureAsSprite(sprite_texture);
173 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
177 g_fontengine = new FontEngine(g_settings, guienv);
178 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
180 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || \
181 IRRLICHT_VERSION_MAJOR >= 2
182 // Irrlicht 1.8 input colours
183 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
184 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
187 // Create the menu clouds
188 if (!g_menucloudsmgr)
189 g_menucloudsmgr = RenderingEngine::get_scene_manager()
190 ->createNewSceneManager();
192 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
193 g_menuclouds->setHeight(100.0f);
194 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
195 scene::ICameraSceneNode *camera;
196 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
197 camera->setFarValue(10000);
203 ChatBackend chat_backend;
205 // If an error occurs, this is set to something by menu().
206 // It is then displayed before the menu shows on the next call to menu()
207 std::string error_message;
208 bool reconnect_requested = false;
210 bool first_loop = true;
216 bool *kill = porting::signal_handler_killstatus();
218 while (RenderingEngine::run() && !*kill && !g_gamecallback->shutdown_requested) {
219 // Set the window caption
220 const wchar_t *text = wgettext("Main Menu");
221 RenderingEngine::get_raw_device()->setWindowCaption(
222 (utf8_to_wide(PROJECT_NAME_C) + L" " +
223 utf8_to_wide(g_version_hash) + L" [" +
228 try { // This is used for catching disconnects
230 RenderingEngine::get_gui_env()->clear();
233 We need some kind of a root node to be able to add
234 custom gui elements directly on the screen.
235 Otherwise they won't be automatically drawn.
237 guiroot = RenderingEngine::get_gui_env()->addStaticText(
238 L"", core::rect<s32>(0, 0, 10000, 10000));
240 bool game_has_run = launch_game(error_message,
241 reconnect_requested, start_data, cmd_args);
243 // Reset the reconnect_requested flag
244 reconnect_requested = false;
246 // If skip_main_menu, we only want to startup once
247 if (skip_main_menu && !first_loop)
259 // Break out of menu-game loop to shut down cleanly
260 if (!RenderingEngine::get_raw_device()->run() || *kill) {
261 if (!g_settings_path.empty())
262 g_settings->updateConfigFile(
263 g_settings_path.c_str());
267 RenderingEngine::get_video_driver()->setTextureCreationFlag(
268 video::ETCF_CREATE_MIP_MAPS,
269 g_settings->getBool("mip_map"));
271 #ifdef HAVE_TOUCHSCREENGUI
272 receiver->m_touchscreengui = new TouchScreenGUI(
273 RenderingEngine::get_raw_device(), receiver);
274 g_touchscreengui = receiver->m_touchscreengui;
277 the_game(kill, input, start_data, error_message, chat_backend,
278 &reconnect_requested);
279 RenderingEngine::get_scene_manager()->clear();
281 #ifdef HAVE_TOUCHSCREENGUI
282 delete g_touchscreengui;
283 g_touchscreengui = NULL;
284 receiver->m_touchscreengui = NULL;
288 catch (con::PeerNotFoundException &e) {
289 error_message = gettext("Connection error (timed out?)");
290 errorstream << error_message << std::endl;
294 catch (std::exception &e) {
295 std::string error_message = "Some exception: \"";
296 error_message += e.what();
297 error_message += "\"";
298 errorstream << error_message << std::endl;
302 // If no main menu, show error and exit
303 if (skip_main_menu) {
304 if (!error_message.empty()) {
305 verbosestream << "error_message = " << error_message
313 g_menuclouds->drop();
314 g_menucloudsmgr->drop();
319 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
321 skip_main_menu = cmd_args.getFlag("go");
323 start_data.address = g_settings->get("address");
324 if (cmd_args.exists("address")) {
325 // Join a remote server
326 start_data.address = cmd_args.get("address");
327 start_data.world_path.clear();
329 if (!start_data.world_path.empty()) {
330 // Start a singleplayer instance
331 start_data.address = "";
334 start_data.name = g_settings->get("name");
335 if (cmd_args.exists("name"))
336 start_data.name = cmd_args.get("name");
338 list_video_modes = cmd_args.getFlag("videomodes");
340 random_input = g_settings->getBool("random_input") ||
341 cmd_args.getFlag("random-input");
344 bool ClientLauncher::init_engine()
346 receiver = new MyEventReceiver();
347 new RenderingEngine(receiver);
348 return RenderingEngine::get_raw_device() != nullptr;
351 void ClientLauncher::init_input()
354 input = new RandomInputHandler();
356 input = new RealInputHandler(receiver);
358 if (g_settings->getBool("enable_joysticks")) {
359 irr::core::array<irr::SJoystickInfo> infos;
360 std::vector<irr::SJoystickInfo> joystick_infos;
362 // Make sure this is called maximum once per
363 // irrlicht device, otherwise it will give you
364 // multiple events for the same joystick.
365 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
366 infostream << "Joystick support enabled" << std::endl;
367 joystick_infos.reserve(infos.size());
368 for (u32 i = 0; i < infos.size(); i++) {
369 joystick_infos.push_back(infos[i]);
371 input->joystick.onJoystickConnect(joystick_infos);
373 errorstream << "Could not activate joystick support."
379 bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requested,
380 GameStartData &start_data, const Settings &cmd_args)
382 // Prepare and check the start data to launch a game
383 std::string error_message_lua = error_message;
384 error_message.clear();
386 if (cmd_args.exists("password"))
387 start_data.password = cmd_args.get("password");
389 if (cmd_args.exists("password-file")) {
390 std::ifstream passfile(cmd_args.get("password-file"));
391 if (passfile.good()) {
392 getline(passfile, start_data.password);
394 error_message = gettext("Provided password file "
395 "failed to open: ") +
396 cmd_args.get("password-file");
397 errorstream << error_message << std::endl;
402 // If a world was commanded, append and select it
403 // This is provieded by "get_world_from_cmdline()", main.cpp
404 if (!start_data.world_path.empty()) {
405 auto &spec = start_data.world_spec;
407 spec.path = start_data.world_path;
408 spec.gameid = getWorldGameId(spec.path, true);
409 spec.name = _("[--world parameter]");
411 if (spec.gameid.empty()) { // Create new
412 spec.gameid = g_settings->get("default_game");
413 spec.name += " [new]";
419 std::string server_name, server_description;
420 start_data.local_server = false;
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
440 * upon the next iteration (if any) causing it to be displayed by
443 error_message = menudata.script_data.errormessage;
447 int newport = stoi(menudata.port);
449 start_data.socket_port = newport;
451 // Update world information using main menu data
452 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
454 int world_index = menudata.selected_world;
455 if (world_index >= 0 && world_index < (int)worldspecs.size()) {
456 g_settings->set("selected_world_path",
457 worldspecs[world_index].path);
458 start_data.world_spec = worldspecs[world_index];
461 start_data.name = menudata.name;
462 start_data.password = menudata.password;
463 start_data.address = std::move(menudata.address);
464 server_name = menudata.servername;
465 server_description = menudata.serverdescription;
467 start_data.local_server = !menudata.simple_singleplayer_mode &&
468 start_data.address.empty();
471 if (!RenderingEngine::run())
474 if (!start_data.isSinglePlayer() && start_data.name.empty()) {
475 error_message = gettext("Please choose a name!");
476 errorstream << error_message << std::endl;
480 // If using simple singleplayer mode, override
481 if (start_data.isSinglePlayer()) {
482 start_data.name = "singleplayer";
483 start_data.password = "";
484 start_data.socket_port = myrand_range(49152, 65535);
486 g_settings->set("name", start_data.name);
487 if (!start_data.address.empty()) {
488 ServerListSpec server;
489 server["name"] = server_name;
490 server["address"] = start_data.address;
491 server["port"] = itos(start_data.socket_port);
492 server["description"] = server_description;
493 ServerList::insert(server);
497 if (start_data.name.length() > PLAYERNAME_SIZE - 1) {
498 error_message = gettext("Player name too long.");
499 start_data.name.resize(PLAYERNAME_SIZE);
500 g_settings->set("name", start_data.name);
504 auto &worldspec = start_data.world_spec;
505 infostream << "Selected world: " << worldspec.name << " [" << worldspec.path
508 if (start_data.address.empty()) {
509 // For singleplayer and local server
510 if (worldspec.path.empty()) {
511 error_message = gettext("No world selected and no address "
512 "provided. Nothing to do.");
513 errorstream << error_message << std::endl;
517 if (!fs::PathExists(worldspec.path)) {
518 error_message = gettext("Provided world path doesn't exist: ") +
520 errorstream << error_message << std::endl;
524 // Load gamespec for required game
525 start_data.game_spec = findWorldSubgame(worldspec.path);
526 if (!start_data.game_spec.isValid()) {
527 error_message = gettext("Could not find or load game \"") +
528 worldspec.gameid + "\"";
529 errorstream << error_message << std::endl;
533 if (porting::signal_handler_killstatus())
536 if (!start_data.game_spec.isValid()) {
537 error_message = gettext("Invalid gamespec.");
538 error_message += " (world.gameid=" + worldspec.gameid + ")";
539 errorstream << error_message << std::endl;
544 start_data.world_path = start_data.world_spec.path;
548 void ClientLauncher::main_menu(MainMenuData *menudata)
550 bool *kill = porting::signal_handler_killstatus();
551 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
553 infostream << "Waiting for other menus" << std::endl;
554 while (RenderingEngine::get_raw_device()->run() && !*kill) {
557 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
558 RenderingEngine::get_gui_env()->drawAll();
560 // On some computers framerate doesn't seem to be automatically limited
563 infostream << "Waited for other menus" << std::endl;
565 // Cursor can be non-visible when coming from the game
567 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
571 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
573 /* leave scene manager in a clean state */
574 RenderingEngine::get_scene_manager()->clear();
577 void ClientLauncher::speed_tests()
579 // volatile to avoid some potential compiler optimisations
580 volatile static s16 temp16;
581 volatile static f32 tempf;
584 static std::string tempstring;
585 static std::string tempstring2;
593 infostream << "The following test should take around 20ms." << std::endl;
594 TimeTaker timer("Testing std::string speed");
595 const u32 jj = 10000;
596 for (u32 j = 0; j < jj; j++) {
600 for (u32 i = 0; i < ii; i++) {
601 tempstring2 += "asd";
603 for (u32 i = 0; i < ii + 1; i++) {
605 if (tempstring == tempstring2)
611 infostream << "All of the following tests should take around 100ms each."
615 TimeTaker timer("Testing floating-point conversion speed");
617 for (u32 i = 0; i < 4000000; i++) {
624 TimeTaker timer("Testing floating-point vector speed");
626 tempv3f1 = v3f(1, 2, 3);
627 tempv3f2 = v3f(4, 5, 6);
628 for (u32 i = 0; i < 10000000; i++) {
629 tempf += tempv3f1.dotProduct(tempv3f2);
630 tempv3f2 += v3f(7, 8, 9);
635 TimeTaker timer("Testing std::map speed");
637 std::map<v2s16, f32> map1;
640 for (s16 y = 0; y < ii; y++) {
641 for (s16 x = 0; x < ii; x++) {
642 map1[v2s16(x, y)] = tempf;
646 for (s16 y = ii - 1; y >= 0; y--) {
647 for (s16 x = 0; x < ii; x++) {
648 tempf = map1[v2s16(x, y)];
654 infostream << "Around 5000/ms should do well here." << std::endl;
655 TimeTaker timer("Testing mutex speed");
668 while (timer.getTimerTime() < 10);
670 u32 dtime = timer.stop();
671 u32 per_ms = n / dtime;
672 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;