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"
25 #include "guiMainMenu.h"
31 #include "serverlist.h"
32 #include "guiEngine.h"
34 #include "fontengine.h"
35 #include "joystick_controller.h"
36 #include "clientlauncher.h"
41 gui::IGUIEnvironment *guienv = NULL;
42 gui::IGUIStaticText *guiroot = NULL;
43 MainMenuManager g_menumgr;
47 return g_menumgr.menuCount() == 0;
50 // Passed to menus to allow disconnecting and exiting
51 MainGameCallback *g_gamecallback = NULL;
54 // Instance of the time getter
55 static TimeGetter *g_timegetter = NULL;
59 if (g_timegetter == NULL)
61 return g_timegetter->getTime(PRECISION_MILLI);
64 u32 getTime(TimePrecision prec) {
65 if (g_timegetter == NULL)
67 return g_timegetter->getTime(prec);
70 ClientLauncher::~ClientLauncher()
86 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
88 init_args(game_params, cmd_args);
90 // List video modes if requested
92 return print_video_modes();
95 errorstream << "Could not initialize game engine." << std::endl;
100 g_timegetter = new IrrlichtTimeGetter(device);
102 // Speed tests (done after irrlicht is loaded to get timer)
103 if (cmd_args.getFlag("speedtests")) {
104 dstream << "Running speed tests" << std::endl;
109 video::IVideoDriver *video_driver = device->getVideoDriver();
110 if (video_driver == NULL) {
111 errorstream << "Could not initialize video driver." << std::endl;
115 porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
118 This changes the minimum allowed number of vertices in a VBO.
121 //driver->setMinHardwareBufferVertexCount(50);
123 // Create game callback for menus
124 g_gamecallback = new MainGameCallback(device);
126 device->setResizable(true);
129 input = new RandomInputHandler();
131 input = new RealInputHandler(device, receiver);
133 smgr = device->getSceneManager();
134 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
136 guienv = device->getGUIEnvironment();
137 skin = guienv->getSkin();
138 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
139 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
140 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
141 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
142 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
143 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
145 g_fontengine = new FontEngine(g_settings, guienv);
146 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
148 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
149 // Irrlicht 1.8 input colours
150 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
151 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
154 // Create the menu clouds
155 if (!g_menucloudsmgr)
156 g_menucloudsmgr = smgr->createNewSceneManager();
158 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
159 g_menucloudsmgr, -1, rand(), 100);
160 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
161 scene::ICameraSceneNode* camera;
162 camera = g_menucloudsmgr->addCameraSceneNode(0,
163 v3f(0, 0, 0), v3f(0, 60, 100));
164 camera->setFarValue(10000);
170 ChatBackend chat_backend;
172 // If an error occurs, this is set to something by menu().
173 // It is then displayed before the menu shows on the next call to menu()
174 std::string error_message;
175 bool reconnect_requested = false;
177 bool first_loop = true;
183 bool *kill = porting::signal_handler_killstatus();
185 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
187 // Set the window caption
188 const wchar_t *text = wgettext("Main Menu");
189 device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
190 L" " + utf8_to_wide(g_version_hash) +
191 L" [" + text + L"]").c_str());
194 try { // This is used for catching disconnects
199 We need some kind of a root node to be able to add
200 custom gui elements directly on the screen.
201 Otherwise they won't be automatically drawn.
203 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
205 bool game_has_run = launch_game(error_message, reconnect_requested,
206 game_params, cmd_args);
208 // Reset the reconnect_requested flag
209 reconnect_requested = false;
211 // If skip_main_menu, we only want to startup once
212 if (skip_main_menu && !first_loop)
224 // Break out of menu-game loop to shut down cleanly
225 if (!device->run() || *kill) {
226 if (g_settings_path != "")
227 g_settings->updateConfigFile(g_settings_path.c_str());
231 if (current_playername.length() > PLAYERNAME_SIZE-1) {
232 error_message = gettext("Player name too long.");
233 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
234 g_settings->set("name", playername);
238 device->getVideoDriver()->setTextureCreationFlag(
239 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
241 #ifdef HAVE_TOUCHSCREENGUI
242 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
243 g_touchscreengui = receiver->m_touchscreengui;
258 &reconnect_requested,
260 simple_singleplayer_mode
264 #ifdef HAVE_TOUCHSCREENGUI
265 delete g_touchscreengui;
266 g_touchscreengui = NULL;
267 receiver->m_touchscreengui = NULL;
271 catch (con::PeerNotFoundException &e) {
272 error_message = gettext("Connection error (timed out?)");
273 errorstream << error_message << std::endl;
277 catch (std::exception &e) {
278 std::string error_message = "Some exception: \"";
279 error_message += e.what();
280 error_message += "\"";
281 errorstream << error_message << std::endl;
285 // If no main menu, show error and exit
286 if (skip_main_menu) {
287 if (!error_message.empty()) {
288 verbosestream << "error_message = "
289 << error_message << std::endl;
296 g_menuclouds->drop();
297 g_menucloudsmgr->drop();
302 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
305 skip_main_menu = cmd_args.getFlag("go");
307 // FIXME: This is confusing (but correct)
309 /* If world_path is set then override it unless skipping the main menu using
310 * the --go command line param. Else, give preference to the address
311 * supplied on the command line
313 address = g_settings->get("address");
314 if (game_params.world_path != "" && !skip_main_menu)
316 else if (cmd_args.exists("address"))
317 address = cmd_args.get("address");
319 playername = g_settings->get("name");
320 if (cmd_args.exists("name"))
321 playername = cmd_args.get("name");
323 list_video_modes = cmd_args.getFlag("videomodes");
325 use_freetype = g_settings->getBool("freetype");
327 random_input = g_settings->getBool("random_input")
328 || cmd_args.getFlag("random-input");
331 bool ClientLauncher::init_engine()
333 receiver = new MyEventReceiver();
334 create_engine_device();
335 return device != NULL;
338 bool ClientLauncher::launch_game(std::string &error_message,
339 bool reconnect_requested, GameParams &game_params,
340 const Settings &cmd_args)
342 // Initialize menu data
343 MainMenuData menudata;
344 menudata.address = address;
345 menudata.name = playername;
346 menudata.password = password;
347 menudata.port = itos(game_params.socket_port);
348 menudata.script_data.errormessage = error_message;
349 menudata.script_data.reconnect_requested = reconnect_requested;
351 error_message.clear();
353 if (cmd_args.exists("password"))
354 menudata.password = cmd_args.get("password");
356 menudata.enable_public = g_settings->getBool("server_announce");
358 // If a world was commanded, append and select it
359 if (game_params.world_path != "") {
360 worldspec.gameid = getWorldGameId(game_params.world_path, true);
361 worldspec.name = _("[--world parameter]");
363 if (worldspec.gameid == "") { // Create new
364 worldspec.gameid = g_settings->get("default_game");
365 worldspec.name += " [new]";
367 worldspec.path = game_params.world_path;
372 if (!skip_main_menu) {
373 main_menu(&menudata);
375 // Skip further loading if there was an exit signal.
376 if (*porting::signal_handler_killstatus())
379 address = menudata.address;
380 int newport = stoi(menudata.port);
382 game_params.socket_port = newport;
384 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
386 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
388 if (menudata.selected_world >= 0
389 && menudata.selected_world < (int)worldspecs.size()) {
390 g_settings->set("selected_world_path",
391 worldspecs[menudata.selected_world].path);
392 worldspec = worldspecs[menudata.selected_world];
396 if (!menudata.script_data.errormessage.empty()) {
397 /* The calling function will pass this back into this function upon the
398 * next iteration (if any) causing it to be displayed by the GUI
400 error_message = menudata.script_data.errormessage;
404 if (menudata.name == "")
405 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
407 playername = menudata.name;
409 password = menudata.password;
411 g_settings->set("name", playername);
413 current_playername = playername;
414 current_password = password;
415 current_address = address;
416 current_port = game_params.socket_port;
418 // If using simple singleplayer mode, override
419 if (simple_singleplayer_mode) {
420 assert(skip_main_menu == false);
421 current_playername = "singleplayer";
422 current_password = "";
423 current_address = "";
424 current_port = myrand_range(49152, 65535);
425 } else if (address != "") {
426 ServerListSpec server;
427 server["name"] = menudata.servername;
428 server["address"] = menudata.address;
429 server["port"] = menudata.port;
430 server["description"] = menudata.serverdescription;
431 ServerList::insert(server);
434 infostream << "Selected world: " << worldspec.name
435 << " [" << worldspec.path << "]" << std::endl;
437 if (current_address == "") { // If local game
438 if (worldspec.path == "") {
439 error_message = gettext("No world selected and no address "
440 "provided. Nothing to do.");
441 errorstream << error_message << std::endl;
445 if (!fs::PathExists(worldspec.path)) {
446 error_message = gettext("Provided world path doesn't exist: ")
448 errorstream << error_message << std::endl;
452 // Load gamespec for required game
453 gamespec = findWorldSubgame(worldspec.path);
454 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
455 error_message = gettext("Could not find or load game \"")
456 + worldspec.gameid + "\"";
457 errorstream << error_message << std::endl;
461 if (porting::signal_handler_killstatus())
464 if (game_params.game_spec.isValid() &&
465 game_params.game_spec.id != worldspec.gameid) {
466 warningstream << "Overriding gamespec from \""
467 << worldspec.gameid << "\" to \""
468 << game_params.game_spec.id << "\"" << std::endl;
469 gamespec = game_params.game_spec;
472 if (!gamespec.isValid()) {
473 error_message = gettext("Invalid gamespec.");
474 error_message += " (world.gameid=" + worldspec.gameid + ")";
475 errorstream << error_message << std::endl;
483 void ClientLauncher::main_menu(MainMenuData *menudata)
485 bool *kill = porting::signal_handler_killstatus();
486 video::IVideoDriver *driver = device->getVideoDriver();
488 infostream << "Waiting for other menus" << std::endl;
489 while (device->run() && *kill == false) {
492 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
495 // On some computers framerate doesn't seem to be automatically limited
498 infostream << "Waited for other menus" << std::endl;
500 // Cursor can be non-visible when coming from the game
502 device->getCursorControl()->setVisible(true);
506 GUIEngine mymenu(device, &input->joystick, guiroot,
507 &g_menumgr, smgr, menudata, *kill);
509 smgr->clear(); /* leave scene manager in a clean state */
512 bool ClientLauncher::create_engine_device()
514 // Resolution selection
515 bool fullscreen = g_settings->getBool("fullscreen");
516 u16 screenW = g_settings->getU16("screenW");
517 u16 screenH = g_settings->getU16("screenH");
520 bool vsync = g_settings->getBool("vsync");
521 u16 bits = g_settings->getU16("fullscreen_bpp");
522 u16 fsaa = g_settings->getU16("fsaa");
524 // stereo buffer required for pageflip stereo
525 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
528 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
529 std::string driverstring = g_settings->get("video_driver");
530 std::vector<video::E_DRIVER_TYPE> drivers
531 = porting::getSupportedVideoDrivers();
533 for (i = 0; i != drivers.size(); i++) {
534 if (!strcasecmp(driverstring.c_str(),
535 porting::getVideoDriverName(drivers[i]))) {
536 driverType = drivers[i];
540 if (i == drivers.size()) {
541 errorstream << "Invalid video_driver specified; "
542 "defaulting to opengl" << std::endl;
545 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
546 params.DriverType = driverType;
547 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
549 params.AntiAlias = fsaa;
550 params.Fullscreen = fullscreen;
551 params.Stencilbuffer = false;
552 params.Stereobuffer = stereo_buffer;
553 params.Vsync = vsync;
554 params.EventReceiver = receiver;
555 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
556 params.ZBufferBits = 24;
558 params.PrivateData = porting::app_global;
559 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
560 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
563 device = createDeviceEx(params);
566 if (g_settings->getBool("enable_joysticks")) {
567 irr::core::array<irr::SJoystickInfo> infos;
568 std::vector<irr::SJoystickInfo> joystick_infos;
569 // Make sure this is called maximum once per
570 // irrlicht device, otherwise it will give you
571 // multiple events for the same joystick.
572 if (device->activateJoysticks(infos)) {
573 infostream << "Joystick support enabled" << std::endl;
574 joystick_infos.reserve(infos.size());
575 for (u32 i = 0; i < infos.size(); i++) {
576 joystick_infos.push_back(infos[i]);
579 errorstream << "Could not activate joystick support." << std::endl;
582 porting::initIrrlicht(device);
585 return device != NULL;
588 void ClientLauncher::speed_tests()
590 // volatile to avoid some potential compiler optimisations
591 volatile static s16 temp16;
592 volatile static f32 tempf;
595 static std::string tempstring;
596 static std::string tempstring2;
600 tempstring = std::string();
601 tempstring2 = std::string();
604 infostream << "The following test should take around 20ms." << std::endl;
605 TimeTaker timer("Testing std::string speed");
606 const u32 jj = 10000;
607 for (u32 j = 0; j < jj; j++) {
611 for (u32 i = 0; i < ii; i++) {
612 tempstring2 += "asd";
614 for (u32 i = 0; i < ii+1; i++) {
616 if (tempstring == tempstring2)
622 infostream << "All of the following tests should take around 100ms each."
626 TimeTaker timer("Testing floating-point conversion speed");
628 for (u32 i = 0; i < 4000000; i++) {
635 TimeTaker timer("Testing floating-point vector speed");
637 tempv3f1 = v3f(1, 2, 3);
638 tempv3f2 = v3f(4, 5, 6);
639 for (u32 i = 0; i < 10000000; i++) {
640 tempf += tempv3f1.dotProduct(tempv3f2);
641 tempv3f2 += v3f(7, 8, 9);
646 TimeTaker timer("Testing std::map speed");
648 std::map<v2s16, f32> map1;
651 for (s16 y = 0; y < ii; y++) {
652 for (s16 x = 0; x < ii; x++) {
653 map1[v2s16(x, y)] = tempf;
657 for (s16 y = ii - 1; y >= 0; y--) {
658 for (s16 x = 0; x < ii; x++) {
659 tempf = map1[v2s16(x, y)];
665 infostream << "Around 5000/ms should do well here." << std::endl;
666 TimeTaker timer("Testing mutex speed");
679 while(timer.getTimerTime() < 10);
681 u32 dtime = timer.stop();
682 u32 per_ms = n / dtime;
683 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
687 bool ClientLauncher::print_video_modes()
689 IrrlichtDevice *nulldevice;
691 bool vsync = g_settings->getBool("vsync");
692 u16 fsaa = g_settings->getU16("fsaa");
693 MyEventReceiver* receiver = new MyEventReceiver();
695 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
696 params.DriverType = video::EDT_NULL;
697 params.WindowSize = core::dimension2d<u32>(640, 480);
699 params.AntiAlias = fsaa;
700 params.Fullscreen = false;
701 params.Stencilbuffer = false;
702 params.Vsync = vsync;
703 params.EventReceiver = receiver;
704 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
706 nulldevice = createDeviceEx(params);
708 if (nulldevice == NULL) {
713 std::cout << _("Available video modes (WxHxD):") << std::endl;
715 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
717 if (videomode_list != NULL) {
718 s32 videomode_count = videomode_list->getVideoModeCount();
719 core::dimension2d<u32> videomode_res;
721 for (s32 i = 0; i < videomode_count; ++i) {
722 videomode_res = videomode_list->getVideoModeResolution(i);
723 videomode_depth = videomode_list->getVideoModeDepth(i);
724 std::cout << videomode_res.Width << "x" << videomode_res.Height
725 << "x" << videomode_depth << std::endl;
728 std::cout << _("Active video mode (WxHxD):") << std::endl;
729 videomode_res = videomode_list->getDesktopResolution();
730 videomode_depth = videomode_list->getDesktopDepth();
731 std::cout << videomode_res.Width << "x" << videomode_res.Height
732 << "x" << videomode_depth << std::endl;
739 return videomode_list != NULL;