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 "mainmenumanager.h"
24 #include "guiMainMenu.h"
29 #include "serverlist.h"
30 #include "guiEngine.h"
31 #include "fontengine.h"
32 #include "clientlauncher.h"
34 #include "renderingengine.h"
38 gui::IGUIEnvironment *guienv = nullptr;
39 gui::IGUIStaticText *guiroot = nullptr;
40 MainMenuManager g_menumgr;
44 return g_menumgr.menuCount() != 0;
47 // Passed to menus to allow disconnecting and exiting
48 MainGameCallback *g_gamecallback = nullptr;
51 ClientLauncher::~ClientLauncher()
58 delete g_gamecallback;
60 delete RenderingEngine::get_instance();
64 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
66 init_args(game_params, cmd_args);
68 // List video modes if requested
70 return RenderingEngine::print_video_modes();
73 errorstream << "Could not initialize game engine." << std::endl;
77 // Speed tests (done after irrlicht is loaded to get timer)
78 if (cmd_args.getFlag("speedtests")) {
79 dstream << "Running speed tests" << std::endl;
84 video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
85 if (video_driver == NULL) {
86 errorstream << "Could not initialize video driver." << std::endl;
90 RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
91 RenderingEngine::get_instance()->setWindowIcon();
94 This changes the minimum allowed number of vertices in a VBO.
97 //driver->setMinHardwareBufferVertexCount(50);
99 // Create game callback for menus
100 g_gamecallback = new MainGameCallback();
102 RenderingEngine::get_instance()->setResizable(true);
106 RenderingEngine::get_scene_manager()->getParameters()->
107 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
109 guienv = RenderingEngine::get_gui_env();
110 skin = RenderingEngine::get_gui_env()->getSkin();
111 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
112 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
113 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
114 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
115 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
116 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
118 g_fontengine = new FontEngine(g_settings, guienv);
119 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
121 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
122 // Irrlicht 1.8 input colours
123 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
124 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
127 // Create the menu clouds
128 if (!g_menucloudsmgr)
129 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
131 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
132 g_menuclouds->setHeight(100.0f);
133 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
134 scene::ICameraSceneNode* camera;
135 camera = g_menucloudsmgr->addCameraSceneNode(0,
136 v3f(0, 0, 0), v3f(0, 60, 100));
137 camera->setFarValue(10000);
143 ChatBackend chat_backend;
145 // If an error occurs, this is set to something by menu().
146 // It is then displayed before the menu shows on the next call to menu()
147 std::string error_message;
148 bool reconnect_requested = false;
150 bool first_loop = true;
156 bool *kill = porting::signal_handler_killstatus();
158 while (RenderingEngine::run() && !*kill &&
159 !g_gamecallback->shutdown_requested) {
160 // Set the window caption
161 const wchar_t *text = wgettext("Main Menu");
162 RenderingEngine::get_raw_device()->
163 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
164 L" " + utf8_to_wide(g_version_hash) +
165 L" [" + text + L"]").c_str());
168 try { // This is used for catching disconnects
170 RenderingEngine::get_gui_env()->clear();
173 We need some kind of a root node to be able to add
174 custom gui elements directly on the screen.
175 Otherwise they won't be automatically drawn.
177 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
178 core::rect<s32>(0, 0, 10000, 10000));
180 bool game_has_run = launch_game(error_message, reconnect_requested,
181 game_params, cmd_args);
183 // Reset the reconnect_requested flag
184 reconnect_requested = false;
186 // If skip_main_menu, we only want to startup once
187 if (skip_main_menu && !first_loop)
199 // Break out of menu-game loop to shut down cleanly
200 if (!RenderingEngine::get_raw_device()->run() || *kill) {
201 if (g_settings_path != "")
202 g_settings->updateConfigFile(g_settings_path.c_str());
206 if (current_playername.length() > PLAYERNAME_SIZE-1) {
207 error_message = gettext("Player name too long.");
208 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
209 g_settings->set("name", playername);
213 RenderingEngine::get_video_driver()->setTextureCreationFlag(
214 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
216 #ifdef HAVE_TOUCHSCREENGUI
217 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
218 g_touchscreengui = receiver->m_touchscreengui;
232 &reconnect_requested,
234 simple_singleplayer_mode
236 RenderingEngine::get_scene_manager()->clear();
238 #ifdef HAVE_TOUCHSCREENGUI
239 delete g_touchscreengui;
240 g_touchscreengui = NULL;
241 receiver->m_touchscreengui = NULL;
245 catch (con::PeerNotFoundException &e) {
246 error_message = gettext("Connection error (timed out?)");
247 errorstream << error_message << std::endl;
251 catch (std::exception &e) {
252 std::string error_message = "Some exception: \"";
253 error_message += e.what();
254 error_message += "\"";
255 errorstream << error_message << std::endl;
259 // If no main menu, show error and exit
260 if (skip_main_menu) {
261 if (!error_message.empty()) {
262 verbosestream << "error_message = "
263 << error_message << std::endl;
270 g_menuclouds->drop();
271 g_menucloudsmgr->drop();
276 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
279 skip_main_menu = cmd_args.getFlag("go");
281 // FIXME: This is confusing (but correct)
283 /* If world_path is set then override it unless skipping the main menu using
284 * the --go command line param. Else, give preference to the address
285 * supplied on the command line
287 address = g_settings->get("address");
288 if (game_params.world_path != "" && !skip_main_menu)
290 else if (cmd_args.exists("address"))
291 address = cmd_args.get("address");
293 playername = g_settings->get("name");
294 if (cmd_args.exists("name"))
295 playername = cmd_args.get("name");
297 list_video_modes = cmd_args.getFlag("videomodes");
299 use_freetype = g_settings->getBool("freetype");
301 random_input = g_settings->getBool("random_input")
302 || cmd_args.getFlag("random-input");
305 bool ClientLauncher::init_engine()
307 receiver = new MyEventReceiver();
308 new RenderingEngine(receiver);
309 return RenderingEngine::get_raw_device() != nullptr;
312 void ClientLauncher::init_input()
315 input = new RandomInputHandler();
317 input = new RealInputHandler(receiver);
319 if (g_settings->getBool("enable_joysticks")) {
320 irr::core::array<irr::SJoystickInfo> infos;
321 std::vector<irr::SJoystickInfo> joystick_infos;
323 // Make sure this is called maximum once per
324 // irrlicht device, otherwise it will give you
325 // multiple events for the same joystick.
326 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
327 infostream << "Joystick support enabled" << std::endl;
328 joystick_infos.reserve(infos.size());
329 for (u32 i = 0; i < infos.size(); i++) {
330 joystick_infos.push_back(infos[i]);
332 input->joystick.onJoystickConnect(joystick_infos);
334 errorstream << "Could not activate joystick support." << std::endl;
339 bool ClientLauncher::launch_game(std::string &error_message,
340 bool reconnect_requested, GameParams &game_params,
341 const Settings &cmd_args)
343 // Initialize menu data
344 MainMenuData menudata;
345 menudata.address = address;
346 menudata.name = playername;
347 menudata.password = password;
348 menudata.port = itos(game_params.socket_port);
349 menudata.script_data.errormessage = error_message;
350 menudata.script_data.reconnect_requested = reconnect_requested;
352 error_message.clear();
354 if (cmd_args.exists("password"))
355 menudata.password = cmd_args.get("password");
357 // If a world was commanded, append and select it
358 if (game_params.world_path != "") {
359 worldspec.gameid = getWorldGameId(game_params.world_path, true);
360 worldspec.name = _("[--world parameter]");
362 if (worldspec.gameid == "") { // Create new
363 worldspec.gameid = g_settings->get("default_game");
364 worldspec.name += " [new]";
366 worldspec.path = game_params.world_path;
371 if (!skip_main_menu) {
372 main_menu(&menudata);
374 // Skip further loading if there was an exit signal.
375 if (*porting::signal_handler_killstatus())
378 address = menudata.address;
379 int newport = stoi(menudata.port);
381 game_params.socket_port = newport;
383 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
385 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
387 if (menudata.selected_world >= 0
388 && menudata.selected_world < (int)worldspecs.size()) {
389 g_settings->set("selected_world_path",
390 worldspecs[menudata.selected_world].path);
391 worldspec = worldspecs[menudata.selected_world];
395 if (!menudata.script_data.errormessage.empty()) {
396 /* The calling function will pass this back into this function upon the
397 * next iteration (if any) causing it to be displayed by the GUI
399 error_message = menudata.script_data.errormessage;
403 if (menudata.name == "" && !simple_singleplayer_mode) {
404 error_message = gettext("Please choose a name!");
405 errorstream << error_message << std::endl;
409 playername = menudata.name;
410 password = menudata.password;
412 current_playername = playername;
413 current_password = password;
414 current_address = address;
415 current_port = game_params.socket_port;
417 // If using simple singleplayer mode, override
418 if (simple_singleplayer_mode) {
419 assert(skip_main_menu == false);
420 current_playername = "singleplayer";
421 current_password = "";
422 current_address = "";
423 current_port = myrand_range(49152, 65535);
425 g_settings->set("name", playername);
427 ServerListSpec server;
428 server["name"] = menudata.servername;
429 server["address"] = menudata.address;
430 server["port"] = menudata.port;
431 server["description"] = menudata.serverdescription;
432 ServerList::insert(server);
436 infostream << "Selected world: " << worldspec.name
437 << " [" << worldspec.path << "]" << std::endl;
439 if (current_address == "") { // If local game
440 if (worldspec.path == "") {
441 error_message = gettext("No world selected and no address "
442 "provided. Nothing to do.");
443 errorstream << error_message << std::endl;
447 if (!fs::PathExists(worldspec.path)) {
448 error_message = gettext("Provided world path doesn't exist: ")
450 errorstream << error_message << std::endl;
454 // Load gamespec for required game
455 gamespec = findWorldSubgame(worldspec.path);
456 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
457 error_message = gettext("Could not find or load game \"")
458 + worldspec.gameid + "\"";
459 errorstream << error_message << std::endl;
463 if (porting::signal_handler_killstatus())
466 if (game_params.game_spec.isValid() &&
467 game_params.game_spec.id != worldspec.gameid) {
468 warningstream << "Overriding gamespec from \""
469 << worldspec.gameid << "\" to \""
470 << game_params.game_spec.id << "\"" << std::endl;
471 gamespec = game_params.game_spec;
474 if (!gamespec.isValid()) {
475 error_message = gettext("Invalid gamespec.");
476 error_message += " (world.gameid=" + worldspec.gameid + ")";
477 errorstream << error_message << std::endl;
485 void ClientLauncher::main_menu(MainMenuData *menudata)
487 bool *kill = porting::signal_handler_killstatus();
488 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
490 infostream << "Waiting for other menus" << std::endl;
491 while (RenderingEngine::get_raw_device()->run() && *kill == false) {
494 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
495 RenderingEngine::get_gui_env()->drawAll();
497 // On some computers framerate doesn't seem to be automatically limited
500 infostream << "Waited for other menus" << std::endl;
502 // Cursor can be non-visible when coming from the game
504 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
508 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
510 /* leave scene manager in a clean state */
511 RenderingEngine::get_scene_manager()->clear();
514 void ClientLauncher::speed_tests()
516 // volatile to avoid some potential compiler optimisations
517 volatile static s16 temp16;
518 volatile static f32 tempf;
521 static std::string tempstring;
522 static std::string tempstring2;
530 infostream << "The following test should take around 20ms." << std::endl;
531 TimeTaker timer("Testing std::string speed");
532 const u32 jj = 10000;
533 for (u32 j = 0; j < jj; j++) {
537 for (u32 i = 0; i < ii; i++) {
538 tempstring2 += "asd";
540 for (u32 i = 0; i < ii+1; i++) {
542 if (tempstring == tempstring2)
548 infostream << "All of the following tests should take around 100ms each."
552 TimeTaker timer("Testing floating-point conversion speed");
554 for (u32 i = 0; i < 4000000; i++) {
561 TimeTaker timer("Testing floating-point vector speed");
563 tempv3f1 = v3f(1, 2, 3);
564 tempv3f2 = v3f(4, 5, 6);
565 for (u32 i = 0; i < 10000000; i++) {
566 tempf += tempv3f1.dotProduct(tempv3f2);
567 tempv3f2 += v3f(7, 8, 9);
572 TimeTaker timer("Testing std::map speed");
574 std::map<v2s16, f32> map1;
577 for (s16 y = 0; y < ii; y++) {
578 for (s16 x = 0; x < ii; x++) {
579 map1[v2s16(x, y)] = tempf;
583 for (s16 y = ii - 1; y >= 0; y--) {
584 for (s16 x = 0; x < ii; x++) {
585 tempf = map1[v2s16(x, y)];
591 infostream << "Around 5000/ms should do well here." << std::endl;
592 TimeTaker timer("Testing mutex speed");
605 while(timer.getTimerTime() < 10);
607 u32 dtime = timer.stop();
608 u32 per_ms = n / dtime;
609 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;