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 ClientLauncher::~ClientLauncher()
67 delete g_gamecallback;
69 delete RenderingEngine::get_instance();
72 g_sound_manager_singleton.reset();
77 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
79 init_args(game_params, cmd_args);
81 // List video modes if requested
83 return RenderingEngine::print_video_modes();
86 if (g_settings->getBool("enable_sound"))
87 g_sound_manager_singleton = createSoundManagerSingleton();
91 errorstream << "Could not initialize game engine." << std::endl;
95 // Speed tests (done after irrlicht is loaded to get timer)
96 if (cmd_args.getFlag("speedtests")) {
97 dstream << "Running speed tests" << std::endl;
102 if (RenderingEngine::get_video_driver() == NULL) {
103 errorstream << "Could not initialize video driver." << std::endl;
107 RenderingEngine::get_instance()->setupTopLevelWindow(PROJECT_NAME_C);
110 This changes the minimum allowed number of vertices in a VBO.
113 //driver->setMinHardwareBufferVertexCount(50);
115 // Create game callback for menus
116 g_gamecallback = new MainGameCallback();
118 RenderingEngine::get_instance()->setResizable(true);
122 RenderingEngine::get_scene_manager()->getParameters()->
123 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
125 guienv = RenderingEngine::get_gui_env();
126 skin = RenderingEngine::get_gui_env()->getSkin();
127 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
128 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
129 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
130 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
131 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
132 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
134 float density = porting::getDisplayDensity();
135 skin->setSize(gui::EGDS_CHECK_BOX_WIDTH, (s32)(17.0f * density));
136 skin->setSize(gui::EGDS_SCROLLBAR_SIZE, (s32)(14.0f * density));
137 skin->setSize(gui::EGDS_WINDOW_BUTTON_WIDTH, (s32)(15.0f * density));
138 if (density > 1.5f) {
139 std::string sprite_path = porting::path_user + "/textures/base/pack/";
141 sprite_path.append("checkbox_64.png");
142 else if (density > 2.0f)
143 sprite_path.append("checkbox_32.png");
145 sprite_path.append("checkbox_16.png");
146 // Texture dimensions should be a power of 2
147 gui::IGUISpriteBank *sprites = skin->getSpriteBank();
148 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
149 video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str());
150 if (sprite_texture) {
151 s32 sprite_id = sprites->addTextureAsSprite(sprite_texture);
153 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
157 g_fontengine = new FontEngine(g_settings, guienv);
158 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
160 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
161 // Irrlicht 1.8 input colours
162 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
163 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
166 // Create the menu clouds
167 if (!g_menucloudsmgr)
168 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
170 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
171 g_menuclouds->setHeight(100.0f);
172 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
173 scene::ICameraSceneNode* camera;
174 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
175 camera->setFarValue(10000);
181 ChatBackend chat_backend;
183 // If an error occurs, this is set to something by menu().
184 // It is then displayed before the menu shows on the next call to menu()
185 std::string error_message;
186 bool reconnect_requested = false;
188 bool first_loop = true;
194 bool *kill = porting::signal_handler_killstatus();
196 while (RenderingEngine::run() && !*kill &&
197 !g_gamecallback->shutdown_requested) {
198 // Set the window caption
199 const wchar_t *text = wgettext("Main Menu");
200 RenderingEngine::get_raw_device()->
201 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
202 L" " + utf8_to_wide(g_version_hash) +
203 L" [" + text + L"]").c_str());
206 try { // This is used for catching disconnects
208 RenderingEngine::get_gui_env()->clear();
211 We need some kind of a root node to be able to add
212 custom gui elements directly on the screen.
213 Otherwise they won't be automatically drawn.
215 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
216 core::rect<s32>(0, 0, 10000, 10000));
218 bool game_has_run = launch_game(error_message, reconnect_requested,
219 game_params, cmd_args);
221 // Reset the reconnect_requested flag
222 reconnect_requested = false;
224 // If skip_main_menu, we only want to startup once
225 if (skip_main_menu && !first_loop)
237 // Break out of menu-game loop to shut down cleanly
238 if (!RenderingEngine::get_raw_device()->run() || *kill) {
239 if (!g_settings_path.empty())
240 g_settings->updateConfigFile(g_settings_path.c_str());
244 if (current_playername.length() > PLAYERNAME_SIZE-1) {
245 error_message = gettext("Player name too long.");
246 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
247 g_settings->set("name", playername);
251 RenderingEngine::get_video_driver()->setTextureCreationFlag(
252 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
254 #ifdef HAVE_TOUCHSCREENGUI
255 receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
256 g_touchscreengui = receiver->m_touchscreengui;
270 &reconnect_requested,
272 simple_singleplayer_mode
274 RenderingEngine::get_scene_manager()->clear();
276 #ifdef HAVE_TOUCHSCREENGUI
277 delete g_touchscreengui;
278 g_touchscreengui = NULL;
279 receiver->m_touchscreengui = NULL;
283 catch (con::PeerNotFoundException &e) {
284 error_message = gettext("Connection error (timed out?)");
285 errorstream << error_message << std::endl;
289 catch (std::exception &e) {
290 std::string error_message = "Some exception: \"";
291 error_message += e.what();
292 error_message += "\"";
293 errorstream << error_message << std::endl;
297 // If no main menu, show error and exit
298 if (skip_main_menu) {
299 if (!error_message.empty()) {
300 verbosestream << "error_message = "
301 << error_message << std::endl;
308 g_menuclouds->drop();
309 g_menucloudsmgr->drop();
314 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
317 skip_main_menu = cmd_args.getFlag("go");
319 // FIXME: This is confusing (but correct)
321 /* If world_path is set then override it unless skipping the main menu using
322 * the --go command line param. Else, give preference to the address
323 * supplied on the command line
325 address = g_settings->get("address");
326 if (!game_params.world_path.empty() && !skip_main_menu)
328 else if (cmd_args.exists("address"))
329 address = cmd_args.get("address");
331 playername = g_settings->get("name");
332 if (cmd_args.exists("name"))
333 playername = cmd_args.get("name");
335 list_video_modes = cmd_args.getFlag("videomodes");
337 use_freetype = g_settings->getBool("freetype");
339 random_input = g_settings->getBool("random_input")
340 || cmd_args.getFlag("random-input");
343 bool ClientLauncher::init_engine()
345 receiver = new MyEventReceiver();
346 new RenderingEngine(receiver);
347 return RenderingEngine::get_raw_device() != nullptr;
350 void ClientLauncher::init_input()
353 input = new RandomInputHandler();
355 input = new RealInputHandler(receiver);
357 if (g_settings->getBool("enable_joysticks")) {
358 irr::core::array<irr::SJoystickInfo> infos;
359 std::vector<irr::SJoystickInfo> joystick_infos;
361 // Make sure this is called maximum once per
362 // irrlicht device, otherwise it will give you
363 // multiple events for the same joystick.
364 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
365 infostream << "Joystick support enabled" << std::endl;
366 joystick_infos.reserve(infos.size());
367 for (u32 i = 0; i < infos.size(); i++) {
368 joystick_infos.push_back(infos[i]);
370 input->joystick.onJoystickConnect(joystick_infos);
372 errorstream << "Could not activate joystick support." << std::endl;
377 bool ClientLauncher::launch_game(std::string &error_message,
378 bool reconnect_requested, GameParams &game_params,
379 const Settings &cmd_args)
381 // Initialize menu data
382 MainMenuData menudata;
383 menudata.address = address;
384 menudata.name = playername;
385 menudata.password = password;
386 menudata.port = itos(game_params.socket_port);
387 menudata.script_data.errormessage = error_message;
388 menudata.script_data.reconnect_requested = reconnect_requested;
390 error_message.clear();
392 if (cmd_args.exists("password"))
393 menudata.password = cmd_args.get("password");
396 if (cmd_args.exists("password-file")) {
397 std::ifstream passfile(cmd_args.get("password-file"));
398 if (passfile.good()) {
399 getline(passfile, menudata.password);
401 error_message = gettext("Provided password file "
403 + cmd_args.get("password-file");
404 errorstream << error_message << std::endl;
409 // If a world was commanded, append and select it
410 if (!game_params.world_path.empty()) {
411 worldspec.gameid = getWorldGameId(game_params.world_path, true);
412 worldspec.name = _("[--world parameter]");
414 if (worldspec.gameid.empty()) { // Create new
415 worldspec.gameid = g_settings->get("default_game");
416 worldspec.name += " [new]";
418 worldspec.path = game_params.world_path;
423 if (!skip_main_menu) {
424 main_menu(&menudata);
426 // Skip further loading if there was an exit signal.
427 if (*porting::signal_handler_killstatus())
430 address = menudata.address;
431 int newport = stoi(menudata.port);
433 game_params.socket_port = newport;
435 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
437 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
439 if (menudata.selected_world >= 0
440 && menudata.selected_world < (int)worldspecs.size()) {
441 g_settings->set("selected_world_path",
442 worldspecs[menudata.selected_world].path);
443 worldspec = worldspecs[menudata.selected_world];
447 if (!menudata.script_data.errormessage.empty()) {
448 /* The calling function will pass this back into this function upon the
449 * next iteration (if any) causing it to be displayed by the GUI
451 error_message = menudata.script_data.errormessage;
455 if (menudata.name.empty() && !simple_singleplayer_mode) {
456 error_message = gettext("Please choose a name!");
457 errorstream << error_message << std::endl;
461 playername = menudata.name;
462 password = menudata.password;
464 current_playername = playername;
465 current_password = password;
466 current_address = address;
467 current_port = game_params.socket_port;
469 // If using simple singleplayer mode, override
470 if (simple_singleplayer_mode) {
471 assert(!skip_main_menu);
472 current_playername = "singleplayer";
473 current_password = "";
474 current_address = "";
475 current_port = myrand_range(49152, 65535);
477 g_settings->set("name", playername);
478 if (!address.empty()) {
479 ServerListSpec server;
480 server["name"] = menudata.servername;
481 server["address"] = menudata.address;
482 server["port"] = menudata.port;
483 server["description"] = menudata.serverdescription;
484 ServerList::insert(server);
488 infostream << "Selected world: " << worldspec.name
489 << " [" << worldspec.path << "]" << std::endl;
491 if (current_address.empty()) { // If local game
492 if (worldspec.path.empty()) {
493 error_message = gettext("No world selected and no address "
494 "provided. Nothing to do.");
495 errorstream << error_message << std::endl;
499 if (!fs::PathExists(worldspec.path)) {
500 error_message = gettext("Provided world path doesn't exist: ")
502 errorstream << error_message << std::endl;
506 // Load gamespec for required game
507 gamespec = findWorldSubgame(worldspec.path);
508 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
509 error_message = gettext("Could not find or load game \"")
510 + worldspec.gameid + "\"";
511 errorstream << error_message << std::endl;
515 if (porting::signal_handler_killstatus())
518 if (game_params.game_spec.isValid() &&
519 game_params.game_spec.id != worldspec.gameid) {
520 warningstream << "Overriding gamespec from \""
521 << worldspec.gameid << "\" to \""
522 << game_params.game_spec.id << "\"" << std::endl;
523 gamespec = game_params.game_spec;
526 if (!gamespec.isValid()) {
527 error_message = gettext("Invalid gamespec.");
528 error_message += " (world.gameid=" + worldspec.gameid + ")";
529 errorstream << error_message << std::endl;
537 void ClientLauncher::main_menu(MainMenuData *menudata)
539 bool *kill = porting::signal_handler_killstatus();
540 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
542 infostream << "Waiting for other menus" << std::endl;
543 while (RenderingEngine::get_raw_device()->run() && !*kill) {
546 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
547 RenderingEngine::get_gui_env()->drawAll();
549 // On some computers framerate doesn't seem to be automatically limited
552 infostream << "Waited for other menus" << std::endl;
554 // Cursor can be non-visible when coming from the game
556 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
560 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
562 /* leave scene manager in a clean state */
563 RenderingEngine::get_scene_manager()->clear();
566 void ClientLauncher::speed_tests()
568 // volatile to avoid some potential compiler optimisations
569 volatile static s16 temp16;
570 volatile static f32 tempf;
573 static std::string tempstring;
574 static std::string tempstring2;
582 infostream << "The following test should take around 20ms." << std::endl;
583 TimeTaker timer("Testing std::string speed");
584 const u32 jj = 10000;
585 for (u32 j = 0; j < jj; j++) {
589 for (u32 i = 0; i < ii; i++) {
590 tempstring2 += "asd";
592 for (u32 i = 0; i < ii+1; i++) {
594 if (tempstring == tempstring2)
600 infostream << "All of the following tests should take around 100ms each."
604 TimeTaker timer("Testing floating-point conversion speed");
606 for (u32 i = 0; i < 4000000; i++) {
613 TimeTaker timer("Testing floating-point vector speed");
615 tempv3f1 = v3f(1, 2, 3);
616 tempv3f2 = v3f(4, 5, 6);
617 for (u32 i = 0; i < 10000000; i++) {
618 tempf += tempv3f1.dotProduct(tempv3f2);
619 tempv3f2 += v3f(7, 8, 9);
624 TimeTaker timer("Testing std::map speed");
626 std::map<v2s16, f32> map1;
629 for (s16 y = 0; y < ii; y++) {
630 for (s16 x = 0; x < ii; x++) {
631 map1[v2s16(x, y)] = tempf;
635 for (s16 y = ii - 1; y >= 0; y--) {
636 for (s16 x = 0; x < ii; x++) {
637 tempf = map1[v2s16(x, y)];
643 infostream << "Around 5000/ms should do well here." << std::endl;
644 TimeTaker timer("Testing mutex speed");
657 while(timer.getTimerTime() < 10);
659 u32 dtime = timer.stop();
660 u32 per_ms = n / dtime;
661 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;