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();
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 RenderingEngine::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 (RenderingEngine::get_video_driver() == NULL) {
124 errorstream << "Could not initialize video driver." << std::endl;
128 RenderingEngine::get_instance()->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 RenderingEngine::get_instance()->setResizable(true);
143 RenderingEngine::get_scene_manager()->getParameters()->
144 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
146 guienv = RenderingEngine::get_gui_env();
147 skin = RenderingEngine::get_gui_env()->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 = RenderingEngine::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(g_settings, guienv);
179 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
181 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || 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()->createNewSceneManager();
191 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
192 g_menuclouds->setHeight(100.0f);
193 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
194 scene::ICameraSceneNode* camera;
195 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
196 camera->setFarValue(10000);
202 ChatBackend chat_backend;
204 // If an error occurs, this is set to something by menu().
205 // It is then displayed before the menu shows on the next call to menu()
206 std::string error_message;
207 bool reconnect_requested = false;
209 bool first_loop = true;
215 bool *kill = porting::signal_handler_killstatus();
217 while (RenderingEngine::run() && !*kill &&
218 !g_gamecallback->shutdown_requested) {
219 // Set the window caption
220 const wchar_t *text = wgettext("Main Menu");
221 RenderingEngine::get_raw_device()->
222 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
223 L" " + utf8_to_wide(g_version_hash) +
224 L" [" + text + L"]").c_str());
227 try { // This is used for catching disconnects
229 RenderingEngine::get_gui_env()->clear();
232 We need some kind of a root node to be able to add
233 custom gui elements directly on the screen.
234 Otherwise they won't be automatically drawn.
236 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
237 core::rect<s32>(0, 0, 10000, 10000));
239 bool game_has_run = launch_game(error_message, reconnect_requested,
240 start_data, cmd_args);
242 // Reset the reconnect_requested flag
243 reconnect_requested = false;
245 // If skip_main_menu, we only want to startup once
246 if (skip_main_menu && !first_loop)
258 // Break out of menu-game loop to shut down cleanly
259 if (!RenderingEngine::get_raw_device()->run() || *kill) {
260 if (!g_settings_path.empty())
261 g_settings->updateConfigFile(g_settings_path.c_str());
265 RenderingEngine::get_video_driver()->setTextureCreationFlag(
266 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
268 #ifdef HAVE_TOUCHSCREENGUI
269 receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
270 g_touchscreengui = receiver->m_touchscreengui;
281 RenderingEngine::get_scene_manager()->clear();
283 #ifdef HAVE_TOUCHSCREENGUI
284 delete g_touchscreengui;
285 g_touchscreengui = NULL;
286 receiver->m_touchscreengui = NULL;
290 catch (con::PeerNotFoundException &e) {
291 error_message = gettext("Connection error (timed out?)");
292 errorstream << error_message << std::endl;
296 catch (std::exception &e) {
297 std::string error_message = "Some exception: \"";
298 error_message += e.what();
299 error_message += "\"";
300 errorstream << error_message << std::endl;
304 // If no main menu, show error and exit
305 if (skip_main_menu) {
306 if (!error_message.empty()) {
307 verbosestream << "error_message = "
308 << error_message << std::endl;
315 g_menuclouds->drop();
316 g_menucloudsmgr->drop();
321 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
323 skip_main_menu = cmd_args.getFlag("go");
325 start_data.address = g_settings->get("address");
326 if (cmd_args.exists("address")) {
327 // Join a remote server
328 start_data.address = cmd_args.get("address");
329 start_data.world_path.clear();
330 start_data.name = g_settings->get("name");
332 if (!start_data.world_path.empty()) {
333 // Start a singleplayer instance
334 start_data.address = "";
337 if (cmd_args.exists("name"))
338 start_data.name = cmd_args.get("name");
340 list_video_modes = cmd_args.getFlag("videomodes");
342 random_input = g_settings->getBool("random_input")
343 || cmd_args.getFlag("random-input");
346 bool ClientLauncher::init_engine()
348 receiver = new MyEventReceiver();
349 new RenderingEngine(receiver);
350 return RenderingEngine::get_raw_device() != nullptr;
353 void ClientLauncher::init_input()
356 input = new RandomInputHandler();
358 input = new RealInputHandler(receiver);
360 if (g_settings->getBool("enable_joysticks")) {
361 irr::core::array<irr::SJoystickInfo> infos;
362 std::vector<irr::SJoystickInfo> joystick_infos;
364 // Make sure this is called maximum once per
365 // irrlicht device, otherwise it will give you
366 // multiple events for the same joystick.
367 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
368 infostream << "Joystick support enabled" << std::endl;
369 joystick_infos.reserve(infos.size());
370 for (u32 i = 0; i < infos.size(); i++) {
371 joystick_infos.push_back(infos[i]);
373 input->joystick.onJoystickConnect(joystick_infos);
375 errorstream << "Could not activate joystick support." << std::endl;
380 bool ClientLauncher::launch_game(std::string &error_message,
381 bool reconnect_requested, GameStartData &start_data,
382 const Settings &cmd_args)
384 // Prepare and check the start data to launch a game
385 std::string error_message_lua = error_message;
386 error_message.clear();
388 if (cmd_args.exists("password"))
389 start_data.password = cmd_args.get("password");
391 if (cmd_args.exists("password-file")) {
392 std::ifstream passfile(cmd_args.get("password-file"));
393 if (passfile.good()) {
394 getline(passfile, start_data.password);
396 error_message = gettext("Provided password file "
398 + cmd_args.get("password-file");
399 errorstream << error_message << std::endl;
404 // If a world was commanded, append and select it
405 // This is provieded by "get_world_from_cmdline()", main.cpp
406 if (!start_data.world_path.empty()) {
407 auto &spec = start_data.world_spec;
409 spec.path = start_data.world_path;
410 spec.gameid = getWorldGameId(spec.path, true);
411 spec.name = _("[--world parameter]");
413 if (spec.gameid.empty()) { // Create new
414 spec.gameid = g_settings->get("default_game");
415 spec.name += " [new]";
421 std::string server_name, server_description;
422 if (!skip_main_menu) {
423 // Initialize menu data
424 // TODO: Re-use existing structs (GameStartData)
425 MainMenuData menudata;
426 menudata.address = start_data.address;
427 menudata.name = start_data.name;
428 menudata.password = start_data.password;
429 menudata.port = itos(start_data.socket_port);
430 menudata.script_data.errormessage = error_message_lua;
431 menudata.script_data.reconnect_requested = reconnect_requested;
433 main_menu(&menudata);
435 // Skip further loading if there was an exit signal.
436 if (*porting::signal_handler_killstatus())
439 if (!menudata.script_data.errormessage.empty()) {
440 /* The calling function will pass this back into this function upon the
441 * next iteration (if any) causing it to be displayed by the GUI
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();
470 start_data.local_server = !start_data.world_path.empty() &&
471 start_data.address.empty() && !start_data.name.empty();
474 if (!RenderingEngine::run())
477 if (!start_data.isSinglePlayer() && start_data.name.empty()) {
478 error_message = gettext("Please choose a name!");
479 errorstream << error_message << std::endl;
483 // If using simple singleplayer mode, override
484 if (start_data.isSinglePlayer()) {
485 start_data.name = "singleplayer";
486 start_data.password = "";
487 start_data.socket_port = myrand_range(49152, 65535);
489 g_settings->set("name", start_data.name);
490 if (!start_data.address.empty()) {
491 ServerListSpec server;
492 server["name"] = server_name;
493 server["address"] = start_data.address;
494 server["port"] = itos(start_data.socket_port);
495 server["description"] = server_description;
496 ServerList::insert(server);
500 if (start_data.name.length() > PLAYERNAME_SIZE - 1) {
501 error_message = gettext("Player name too long.");
502 start_data.name.resize(PLAYERNAME_SIZE);
503 g_settings->set("name", start_data.name);
507 auto &worldspec = start_data.world_spec;
508 infostream << "Selected world: " << worldspec.name
509 << " [" << worldspec.path << "]" << std::endl;
511 if (start_data.address.empty()) {
512 // For singleplayer and local server
513 if (worldspec.path.empty()) {
514 error_message = gettext("No world selected and no address "
515 "provided. Nothing to do.");
516 errorstream << error_message << std::endl;
520 if (!fs::PathExists(worldspec.path)) {
521 error_message = gettext("Provided world path doesn't exist: ")
523 errorstream << error_message << std::endl;
527 // Load gamespec for required game
528 start_data.game_spec = findWorldSubgame(worldspec.path);
529 if (!start_data.game_spec.isValid()) {
530 error_message = gettext("Could not find or load game \"")
531 + worldspec.gameid + "\"";
532 errorstream << error_message << std::endl;
536 if (porting::signal_handler_killstatus())
539 if (!start_data.game_spec.isValid()) {
540 error_message = gettext("Invalid gamespec.");
541 error_message += " (world.gameid=" + worldspec.gameid + ")";
542 errorstream << error_message << std::endl;
547 start_data.world_path = start_data.world_spec.path;
551 void ClientLauncher::main_menu(MainMenuData *menudata)
553 bool *kill = porting::signal_handler_killstatus();
554 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
556 infostream << "Waiting for other menus" << std::endl;
557 while (RenderingEngine::get_raw_device()->run() && !*kill) {
560 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
561 RenderingEngine::get_gui_env()->drawAll();
563 // On some computers framerate doesn't seem to be automatically limited
566 infostream << "Waited for other menus" << std::endl;
568 // Cursor can be non-visible when coming from the game
570 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
574 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
576 /* leave scene manager in a clean state */
577 RenderingEngine::get_scene_manager()->clear();
580 void ClientLauncher::speed_tests()
582 // volatile to avoid some potential compiler optimisations
583 volatile static s16 temp16;
584 volatile static f32 tempf;
587 static std::string tempstring;
588 static std::string tempstring2;
596 infostream << "The following test should take around 20ms." << std::endl;
597 TimeTaker timer("Testing std::string speed");
598 const u32 jj = 10000;
599 for (u32 j = 0; j < jj; j++) {
603 for (u32 i = 0; i < ii; i++) {
604 tempstring2 += "asd";
606 for (u32 i = 0; i < ii+1; i++) {
608 if (tempstring == tempstring2)
614 infostream << "All of the following tests should take around 100ms each."
618 TimeTaker timer("Testing floating-point conversion speed");
620 for (u32 i = 0; i < 4000000; i++) {
627 TimeTaker timer("Testing floating-point vector speed");
629 tempv3f1 = v3f(1, 2, 3);
630 tempv3f2 = v3f(4, 5, 6);
631 for (u32 i = 0; i < 10000000; i++) {
632 tempf += tempv3f1.dotProduct(tempv3f2);
633 tempv3f2 += v3f(7, 8, 9);
638 TimeTaker timer("Testing std::map speed");
640 std::map<v2s16, f32> map1;
643 for (s16 y = 0; y < ii; y++) {
644 for (s16 x = 0; x < ii; x++) {
645 map1[v2s16(x, y)] = tempf;
649 for (s16 y = ii - 1; y >= 0; y--) {
650 for (s16 x = 0; x < ii; x++) {
651 tempf = map1[v2s16(x, y)];
657 infostream << "Around 5000/ms should do well here." << std::endl;
658 TimeTaker timer("Testing mutex speed");
671 while(timer.getTimerTime() < 10);
673 u32 dtime = timer.stop();
674 u32 per_ms = n / dtime;
675 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;