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);
117 porting::setWindowIcon(device);
120 This changes the minimum allowed number of vertices in a VBO.
123 //driver->setMinHardwareBufferVertexCount(50);
125 // Create game callback for menus
126 g_gamecallback = new MainGameCallback(device);
128 device->setResizable(true);
132 smgr = device->getSceneManager();
133 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
135 guienv = device->getGUIEnvironment();
136 skin = guienv->getSkin();
137 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
138 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
139 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
140 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
141 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
142 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
144 g_fontengine = new FontEngine(g_settings, guienv);
145 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
147 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
148 // Irrlicht 1.8 input colours
149 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
150 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
153 // Create the menu clouds
154 if (!g_menucloudsmgr)
155 g_menucloudsmgr = smgr->createNewSceneManager();
157 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
158 g_menucloudsmgr, -1, rand(), 100);
159 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
160 scene::ICameraSceneNode* camera;
161 camera = g_menucloudsmgr->addCameraSceneNode(0,
162 v3f(0, 0, 0), v3f(0, 60, 100));
163 camera->setFarValue(10000);
169 ChatBackend chat_backend;
171 // If an error occurs, this is set to something by menu().
172 // It is then displayed before the menu shows on the next call to menu()
173 std::string error_message;
174 bool reconnect_requested = false;
176 bool first_loop = true;
182 bool *kill = porting::signal_handler_killstatus();
184 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
186 // Set the window caption
187 const wchar_t *text = wgettext("Main Menu");
188 device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
189 L" " + utf8_to_wide(g_version_hash) +
190 L" [" + text + L"]").c_str());
193 try { // This is used for catching disconnects
198 We need some kind of a root node to be able to add
199 custom gui elements directly on the screen.
200 Otherwise they won't be automatically drawn.
202 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
204 bool game_has_run = launch_game(error_message, reconnect_requested,
205 game_params, cmd_args);
207 // Reset the reconnect_requested flag
208 reconnect_requested = false;
210 // If skip_main_menu, we only want to startup once
211 if (skip_main_menu && !first_loop)
223 // Break out of menu-game loop to shut down cleanly
224 if (!device->run() || *kill) {
225 if (g_settings_path != "")
226 g_settings->updateConfigFile(g_settings_path.c_str());
230 if (current_playername.length() > PLAYERNAME_SIZE-1) {
231 error_message = gettext("Player name too long.");
232 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
233 g_settings->set("name", playername);
237 device->getVideoDriver()->setTextureCreationFlag(
238 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
240 #ifdef HAVE_TOUCHSCREENGUI
241 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
242 g_touchscreengui = receiver->m_touchscreengui;
257 &reconnect_requested,
259 simple_singleplayer_mode
263 #ifdef HAVE_TOUCHSCREENGUI
264 delete g_touchscreengui;
265 g_touchscreengui = NULL;
266 receiver->m_touchscreengui = NULL;
270 catch (con::PeerNotFoundException &e) {
271 error_message = gettext("Connection error (timed out?)");
272 errorstream << error_message << std::endl;
276 catch (std::exception &e) {
277 std::string error_message = "Some exception: \"";
278 error_message += e.what();
279 error_message += "\"";
280 errorstream << error_message << std::endl;
284 // If no main menu, show error and exit
285 if (skip_main_menu) {
286 if (!error_message.empty()) {
287 verbosestream << "error_message = "
288 << error_message << std::endl;
295 g_menuclouds->drop();
296 g_menucloudsmgr->drop();
301 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
304 skip_main_menu = cmd_args.getFlag("go");
306 // FIXME: This is confusing (but correct)
308 /* If world_path is set then override it unless skipping the main menu using
309 * the --go command line param. Else, give preference to the address
310 * supplied on the command line
312 address = g_settings->get("address");
313 if (game_params.world_path != "" && !skip_main_menu)
315 else if (cmd_args.exists("address"))
316 address = cmd_args.get("address");
318 playername = g_settings->get("name");
319 if (cmd_args.exists("name"))
320 playername = cmd_args.get("name");
322 list_video_modes = cmd_args.getFlag("videomodes");
324 use_freetype = g_settings->getBool("freetype");
326 random_input = g_settings->getBool("random_input")
327 || cmd_args.getFlag("random-input");
330 bool ClientLauncher::init_engine()
332 receiver = new MyEventReceiver();
333 create_engine_device();
334 return device != NULL;
337 void ClientLauncher::init_input()
340 input = new RandomInputHandler();
342 input = new RealInputHandler(device, receiver);
344 if (g_settings->getBool("enable_joysticks")) {
345 irr::core::array<irr::SJoystickInfo> infos;
346 std::vector<irr::SJoystickInfo> joystick_infos;
348 // Make sure this is called maximum once per
349 // irrlicht device, otherwise it will give you
350 // multiple events for the same joystick.
351 if (device->activateJoysticks(infos)) {
352 infostream << "Joystick support enabled" << std::endl;
353 joystick_infos.reserve(infos.size());
354 for (u32 i = 0; i < infos.size(); i++) {
355 joystick_infos.push_back(infos[i]);
357 input->joystick.onJoystickConnect(joystick_infos);
359 errorstream << "Could not activate joystick support." << std::endl;
364 bool ClientLauncher::launch_game(std::string &error_message,
365 bool reconnect_requested, GameParams &game_params,
366 const Settings &cmd_args)
368 // Initialize menu data
369 MainMenuData menudata;
370 menudata.address = address;
371 menudata.name = playername;
372 menudata.password = password;
373 menudata.port = itos(game_params.socket_port);
374 menudata.script_data.errormessage = error_message;
375 menudata.script_data.reconnect_requested = reconnect_requested;
377 error_message.clear();
379 if (cmd_args.exists("password"))
380 menudata.password = cmd_args.get("password");
382 menudata.enable_public = g_settings->getBool("server_announce");
384 // If a world was commanded, append and select it
385 if (game_params.world_path != "") {
386 worldspec.gameid = getWorldGameId(game_params.world_path, true);
387 worldspec.name = _("[--world parameter]");
389 if (worldspec.gameid == "") { // Create new
390 worldspec.gameid = g_settings->get("default_game");
391 worldspec.name += " [new]";
393 worldspec.path = game_params.world_path;
398 if (!skip_main_menu) {
399 main_menu(&menudata);
401 // Skip further loading if there was an exit signal.
402 if (*porting::signal_handler_killstatus())
405 address = menudata.address;
406 int newport = stoi(menudata.port);
408 game_params.socket_port = newport;
410 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
412 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
414 if (menudata.selected_world >= 0
415 && menudata.selected_world < (int)worldspecs.size()) {
416 g_settings->set("selected_world_path",
417 worldspecs[menudata.selected_world].path);
418 worldspec = worldspecs[menudata.selected_world];
422 if (!menudata.script_data.errormessage.empty()) {
423 /* The calling function will pass this back into this function upon the
424 * next iteration (if any) causing it to be displayed by the GUI
426 error_message = menudata.script_data.errormessage;
430 if (menudata.name == "" && !simple_singleplayer_mode) {
431 error_message = gettext("Please choose a name!");
435 playername = menudata.name;
436 password = menudata.password;
438 current_playername = playername;
439 current_password = password;
440 current_address = address;
441 current_port = game_params.socket_port;
443 // If using simple singleplayer mode, override
444 if (simple_singleplayer_mode) {
445 assert(skip_main_menu == false);
446 current_playername = "singleplayer";
447 current_password = "";
448 current_address = "";
449 current_port = myrand_range(49152, 65535);
451 g_settings->set("name", playername);
453 ServerListSpec server;
454 server["name"] = menudata.servername;
455 server["address"] = menudata.address;
456 server["port"] = menudata.port;
457 server["description"] = menudata.serverdescription;
458 ServerList::insert(server);
462 infostream << "Selected world: " << worldspec.name
463 << " [" << worldspec.path << "]" << std::endl;
465 if (current_address == "") { // If local game
466 if (worldspec.path == "") {
467 error_message = gettext("No world selected and no address "
468 "provided. Nothing to do.");
469 errorstream << error_message << std::endl;
473 if (!fs::PathExists(worldspec.path)) {
474 error_message = gettext("Provided world path doesn't exist: ")
476 errorstream << error_message << std::endl;
480 // Load gamespec for required game
481 gamespec = findWorldSubgame(worldspec.path);
482 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
483 error_message = gettext("Could not find or load game \"")
484 + worldspec.gameid + "\"";
485 errorstream << error_message << std::endl;
489 if (porting::signal_handler_killstatus())
492 if (game_params.game_spec.isValid() &&
493 game_params.game_spec.id != worldspec.gameid) {
494 warningstream << "Overriding gamespec from \""
495 << worldspec.gameid << "\" to \""
496 << game_params.game_spec.id << "\"" << std::endl;
497 gamespec = game_params.game_spec;
500 if (!gamespec.isValid()) {
501 error_message = gettext("Invalid gamespec.");
502 error_message += " (world.gameid=" + worldspec.gameid + ")";
503 errorstream << error_message << std::endl;
511 void ClientLauncher::main_menu(MainMenuData *menudata)
513 bool *kill = porting::signal_handler_killstatus();
514 video::IVideoDriver *driver = device->getVideoDriver();
516 infostream << "Waiting for other menus" << std::endl;
517 while (device->run() && *kill == false) {
520 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
523 // On some computers framerate doesn't seem to be automatically limited
526 infostream << "Waited for other menus" << std::endl;
528 // Cursor can be non-visible when coming from the game
530 device->getCursorControl()->setVisible(true);
534 GUIEngine mymenu(device, &input->joystick, guiroot,
535 &g_menumgr, smgr, menudata, *kill);
537 smgr->clear(); /* leave scene manager in a clean state */
540 bool ClientLauncher::create_engine_device()
542 // Resolution selection
543 bool fullscreen = g_settings->getBool("fullscreen");
544 u16 screenW = g_settings->getU16("screenW");
545 u16 screenH = g_settings->getU16("screenH");
548 bool vsync = g_settings->getBool("vsync");
549 u16 bits = g_settings->getU16("fullscreen_bpp");
550 u16 fsaa = g_settings->getU16("fsaa");
552 // stereo buffer required for pageflip stereo
553 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
556 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
557 const std::string &driverstring = g_settings->get("video_driver");
558 std::vector<video::E_DRIVER_TYPE> drivers
559 = porting::getSupportedVideoDrivers();
561 for (i = 0; i != drivers.size(); i++) {
562 if (!strcasecmp(driverstring.c_str(),
563 porting::getVideoDriverName(drivers[i]))) {
564 driverType = drivers[i];
568 if (i == drivers.size()) {
569 errorstream << "Invalid video_driver specified; "
570 "defaulting to opengl" << std::endl;
573 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
574 params.DriverType = driverType;
575 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
577 params.AntiAlias = fsaa;
578 params.Fullscreen = fullscreen;
579 params.Stencilbuffer = false;
580 params.Stereobuffer = stereo_buffer;
581 params.Vsync = vsync;
582 params.EventReceiver = receiver;
583 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
584 params.ZBufferBits = 24;
586 params.PrivateData = porting::app_global;
587 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
588 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
591 device = createDeviceEx(params);
594 porting::initIrrlicht(device);
596 return device != NULL;
599 void ClientLauncher::speed_tests()
601 // volatile to avoid some potential compiler optimisations
602 volatile static s16 temp16;
603 volatile static f32 tempf;
606 static std::string tempstring;
607 static std::string tempstring2;
611 tempstring = std::string();
612 tempstring2 = std::string();
615 infostream << "The following test should take around 20ms." << std::endl;
616 TimeTaker timer("Testing std::string speed");
617 const u32 jj = 10000;
618 for (u32 j = 0; j < jj; j++) {
622 for (u32 i = 0; i < ii; i++) {
623 tempstring2 += "asd";
625 for (u32 i = 0; i < ii+1; i++) {
627 if (tempstring == tempstring2)
633 infostream << "All of the following tests should take around 100ms each."
637 TimeTaker timer("Testing floating-point conversion speed");
639 for (u32 i = 0; i < 4000000; i++) {
646 TimeTaker timer("Testing floating-point vector speed");
648 tempv3f1 = v3f(1, 2, 3);
649 tempv3f2 = v3f(4, 5, 6);
650 for (u32 i = 0; i < 10000000; i++) {
651 tempf += tempv3f1.dotProduct(tempv3f2);
652 tempv3f2 += v3f(7, 8, 9);
657 TimeTaker timer("Testing std::map speed");
659 std::map<v2s16, f32> map1;
662 for (s16 y = 0; y < ii; y++) {
663 for (s16 x = 0; x < ii; x++) {
664 map1[v2s16(x, y)] = tempf;
668 for (s16 y = ii - 1; y >= 0; y--) {
669 for (s16 x = 0; x < ii; x++) {
670 tempf = map1[v2s16(x, y)];
676 infostream << "Around 5000/ms should do well here." << std::endl;
677 TimeTaker timer("Testing mutex speed");
690 while(timer.getTimerTime() < 10);
692 u32 dtime = timer.stop();
693 u32 per_ms = n / dtime;
694 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
698 bool ClientLauncher::print_video_modes()
700 IrrlichtDevice *nulldevice;
702 bool vsync = g_settings->getBool("vsync");
703 u16 fsaa = g_settings->getU16("fsaa");
704 MyEventReceiver* receiver = new MyEventReceiver();
706 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
707 params.DriverType = video::EDT_NULL;
708 params.WindowSize = core::dimension2d<u32>(640, 480);
710 params.AntiAlias = fsaa;
711 params.Fullscreen = false;
712 params.Stencilbuffer = false;
713 params.Vsync = vsync;
714 params.EventReceiver = receiver;
715 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
717 nulldevice = createDeviceEx(params);
719 if (nulldevice == NULL) {
724 std::cout << _("Available video modes (WxHxD):") << std::endl;
726 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
728 if (videomode_list != NULL) {
729 s32 videomode_count = videomode_list->getVideoModeCount();
730 core::dimension2d<u32> videomode_res;
732 for (s32 i = 0; i < videomode_count; ++i) {
733 videomode_res = videomode_list->getVideoModeResolution(i);
734 videomode_depth = videomode_list->getVideoModeDepth(i);
735 std::cout << videomode_res.Width << "x" << videomode_res.Height
736 << "x" << videomode_depth << std::endl;
739 std::cout << _("Active video mode (WxHxD):") << std::endl;
740 videomode_res = videomode_list->getDesktopResolution();
741 videomode_depth = videomode_list->getDesktopDepth();
742 std::cout << videomode_res.Width << "x" << videomode_res.Height
743 << "x" << videomode_depth << std::endl;
750 return videomode_list != NULL;