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.
21 #include "mainmenumanager.h"
26 #include "guiMainMenu.h"
32 #include "serverlist.h"
33 #include "guiEngine.h"
35 #include "fontengine.h"
36 #include "clientlauncher.h"
38 // A pointer to a global instance of the time getter
40 TimeGetter *g_timegetter = NULL;
44 if (g_timegetter == NULL)
46 return g_timegetter->getTime(PRECISION_MILLI);
49 u32 getTime(TimePrecision prec) {
50 if (g_timegetter == NULL)
52 return g_timegetter->getTime(prec);
55 ClientLauncher::~ClientLauncher()
71 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
73 init_args(game_params, cmd_args);
75 // List video modes if requested
77 return print_video_modes();
79 if (!init_engine(game_params.log_level)) {
80 errorstream << "Could not initialize game engine." << std::endl;
85 g_timegetter = new IrrlichtTimeGetter(device);
87 // Speed tests (done after irrlicht is loaded to get timer)
88 if (cmd_args.getFlag("speedtests")) {
89 dstream << "Running speed tests" << std::endl;
94 video::IVideoDriver *video_driver = device->getVideoDriver();
95 if (video_driver == NULL) {
96 errorstream << "Could not initialize video driver." << std::endl;
100 porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME);
103 This changes the minimum allowed number of vertices in a VBO.
106 //driver->setMinHardwareBufferVertexCount(50);
108 // Create game callback for menus
109 g_gamecallback = new MainGameCallback(device);
111 device->setResizable(true);
114 input = new RandomInputHandler();
116 input = new RealInputHandler(device, receiver);
118 smgr = device->getSceneManager();
119 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
121 guienv = device->getGUIEnvironment();
122 skin = guienv->getSkin();
123 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
124 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
125 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
126 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
127 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
128 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
130 g_fontengine = new FontEngine(g_settings, guienv);
131 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
133 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
134 // Irrlicht 1.8 input colours
135 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
136 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
139 // Create the menu clouds
140 if (!g_menucloudsmgr)
141 g_menucloudsmgr = smgr->createNewSceneManager();
143 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
144 g_menucloudsmgr, -1, rand(), 100);
145 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
146 scene::ICameraSceneNode* camera;
147 camera = g_menucloudsmgr->addCameraSceneNode(0,
148 v3f(0, 0, 0), v3f(0, 60, 100));
149 camera->setFarValue(10000);
155 ChatBackend chat_backend;
157 // If an error occurs, this is set to something by menu().
158 // It is then displayed before the menu shows on the next call to menu()
159 std::string error_message;
161 bool first_loop = true;
167 bool *kill = porting::signal_handler_killstatus();
169 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
171 // Set the window caption
172 const wchar_t *text = wgettext("Main Menu");
173 device->setWindowCaption((narrow_to_wide(PROJECT_NAME) + L" [" + text + L"]").c_str());
176 try { // This is used for catching disconnects
181 We need some kind of a root node to be able to add
182 custom gui elements directly on the screen.
183 Otherwise they won't be automatically drawn.
185 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
187 bool game_has_run = launch_game(error_message, game_params, cmd_args);
189 // If skip_main_menu, we only want to startup once
190 if (skip_main_menu && !first_loop)
202 // Break out of menu-game loop to shut down cleanly
203 if (!device->run() || *kill) {
204 if (g_settings_path != "")
205 g_settings->updateConfigFile(g_settings_path.c_str());
209 if (current_playername.length() > PLAYERNAME_SIZE-1) {
210 error_message = gettext("Player name too long.");
211 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
212 g_settings->set("name", playername);
216 device->getVideoDriver()->setTextureCreationFlag(
217 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
219 #ifdef HAVE_TOUCHSCREENGUI
220 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
221 g_touchscreengui = receiver->m_touchscreengui;
236 simple_singleplayer_mode
240 #ifdef HAVE_TOUCHSCREENGUI
241 delete g_touchscreengui;
242 g_touchscreengui = NULL;
243 receiver->m_touchscreengui = NULL;
247 catch (con::PeerNotFoundException &e) {
248 error_message = gettext("Connection error (timed out?)");
249 errorstream << error_message << std::endl;
253 catch (std::exception &e) {
254 std::string error_message = "Some exception: \"";
255 error_message += e.what();
256 error_message += "\"";
257 errorstream << error_message << std::endl;
261 // If no main menu, show error and exit
262 if (skip_main_menu) {
263 if (!error_message.empty()) {
264 verbosestream << "error_message = "
265 << error_message << std::endl;
272 g_menuclouds->drop();
273 g_menucloudsmgr->drop();
278 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
281 skip_main_menu = cmd_args.getFlag("go");
283 // FIXME: This is confusing (but correct)
285 /* If world_path is set then override it unless skipping the main menu using
286 * the --go command line param. Else, give preference to the address
287 * supplied on the command line
289 address = g_settings->get("address");
290 if (game_params.world_path != "" && !skip_main_menu)
292 else if (cmd_args.exists("address"))
293 address = cmd_args.get("address");
295 playername = g_settings->get("name");
296 if (cmd_args.exists("name"))
297 playername = cmd_args.get("name");
299 list_video_modes = cmd_args.getFlag("videomodes");
301 use_freetype = g_settings->getBool("freetype");
303 random_input = g_settings->getBool("random_input")
304 || cmd_args.getFlag("random-input");
307 bool ClientLauncher::init_engine(int log_level)
309 receiver = new MyEventReceiver();
310 create_engine_device(log_level);
311 return device != NULL;
314 bool ClientLauncher::launch_game(std::string &error_message,
315 GameParams &game_params, const Settings &cmd_args)
317 // Initialize menu data
318 MainMenuData menudata;
319 menudata.address = address;
320 menudata.name = playername;
321 menudata.port = itos(game_params.socket_port);
322 menudata.errormessage = error_message;
324 error_message.clear();
326 if (cmd_args.exists("password"))
327 menudata.password = cmd_args.get("password");
329 menudata.enable_public = g_settings->getBool("server_announce");
331 // If a world was commanded, append and select it
332 if (game_params.world_path != "") {
333 worldspec.gameid = getWorldGameId(game_params.world_path, true);
334 worldspec.name = _("[--world parameter]");
336 if (worldspec.gameid == "") { // Create new
337 worldspec.gameid = g_settings->get("default_game");
338 worldspec.name += " [new]";
340 worldspec.path = game_params.world_path;
345 if (!skip_main_menu) {
346 main_menu(&menudata);
348 // Skip further loading if there was an exit signal.
349 if (*porting::signal_handler_killstatus())
352 address = menudata.address;
353 int newport = stoi(menudata.port);
355 game_params.socket_port = newport;
357 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
359 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
361 if (menudata.selected_world >= 0
362 && menudata.selected_world < (int)worldspecs.size()) {
363 g_settings->set("selected_world_path",
364 worldspecs[menudata.selected_world].path);
365 worldspec = worldspecs[menudata.selected_world];
369 if (!menudata.errormessage.empty()) {
370 /* The calling function will pass this back into this function upon the
371 * next iteration (if any) causing it to be displayed by the GUI
373 error_message = menudata.errormessage;
377 if (menudata.name == "")
378 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
380 playername = menudata.name;
382 password = translatePassword(playername, narrow_to_wide(menudata.password));
384 g_settings->set("name", playername);
386 current_playername = playername;
387 current_password = password;
388 current_address = address;
389 current_port = game_params.socket_port;
391 // If using simple singleplayer mode, override
392 if (simple_singleplayer_mode) {
393 assert(skip_main_menu == false);
394 current_playername = "singleplayer";
395 current_password = "";
396 current_address = "";
397 current_port = myrand_range(49152, 65535);
398 } else if (address != "") {
399 ServerListSpec server;
400 server["name"] = menudata.servername;
401 server["address"] = menudata.address;
402 server["port"] = menudata.port;
403 server["description"] = menudata.serverdescription;
404 ServerList::insert(server);
407 infostream << "Selected world: " << worldspec.name
408 << " [" << worldspec.path << "]" << std::endl;
410 if (current_address == "") { // If local game
411 if (worldspec.path == "") {
412 error_message = gettext("No world selected and no address "
413 "provided. Nothing to do.");
414 errorstream << error_message << std::endl;
418 if (!fs::PathExists(worldspec.path)) {
419 error_message = gettext("Provided world path doesn't exist: ")
421 errorstream << error_message << std::endl;
425 // Load gamespec for required game
426 gamespec = findWorldSubgame(worldspec.path);
427 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
428 error_message = gettext("Could not find or load game \"")
429 + worldspec.gameid + "\"";
430 errorstream << error_message << std::endl;
434 if (porting::signal_handler_killstatus())
437 if (game_params.game_spec.isValid() &&
438 game_params.game_spec.id != worldspec.gameid) {
439 errorstream << "WARNING: Overriding gamespec from \""
440 << worldspec.gameid << "\" to \""
441 << game_params.game_spec.id << "\"" << std::endl;
442 gamespec = game_params.game_spec;
445 if (!gamespec.isValid()) {
446 error_message = gettext("Invalid gamespec.");
447 error_message += " (world.gameid=" + worldspec.gameid + ")";
448 errorstream << error_message << std::endl;
456 void ClientLauncher::main_menu(MainMenuData *menudata)
458 bool *kill = porting::signal_handler_killstatus();
459 video::IVideoDriver *driver = device->getVideoDriver();
461 infostream << "Waiting for other menus" << std::endl;
462 while (device->run() && *kill == false) {
465 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
468 // On some computers framerate doesn't seem to be automatically limited
471 infostream << "Waited for other menus" << std::endl;
473 // Cursor can be non-visible when coming from the game
475 device->getCursorControl()->setVisible(true);
479 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
481 smgr->clear(); /* leave scene manager in a clean state */
484 bool ClientLauncher::create_engine_device(int log_level)
486 static const irr::ELOG_LEVEL irr_log_level[5] = {
491 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
498 // Resolution selection
499 bool fullscreen = g_settings->getBool("fullscreen");
500 u16 screenW = g_settings->getU16("screenW");
501 u16 screenH = g_settings->getU16("screenH");
504 bool vsync = g_settings->getBool("vsync");
505 u16 bits = g_settings->getU16("fullscreen_bpp");
506 u16 fsaa = g_settings->getU16("fsaa");
509 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
510 std::string driverstring = g_settings->get("video_driver");
511 std::vector<video::E_DRIVER_TYPE> drivers
512 = porting::getSupportedVideoDrivers();
514 for (i = 0; i != drivers.size(); i++) {
515 if (!strcasecmp(driverstring.c_str(),
516 porting::getVideoDriverName(drivers[i]))) {
517 driverType = drivers[i];
521 if (i == drivers.size()) {
522 errorstream << "Invalid video_driver specified; "
523 "defaulting to opengl" << std::endl;
526 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
527 params.DriverType = driverType;
528 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
530 params.AntiAlias = fsaa;
531 params.Fullscreen = fullscreen;
532 params.Stencilbuffer = false;
533 params.Vsync = vsync;
534 params.EventReceiver = receiver;
535 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
537 params.PrivateData = porting::app_global;
538 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
539 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
542 device = createDeviceEx(params);
545 // Map our log level to irrlicht engine one.
546 ILogger* irr_logger = device->getLogger();
547 irr_logger->setLogLevel(irr_log_level[log_level]);
549 porting::initIrrlicht(device);
552 return device != NULL;
555 void ClientLauncher::speed_tests()
557 // volatile to avoid some potential compiler optimisations
558 volatile static s16 temp16;
559 volatile static f32 tempf;
562 static std::string tempstring;
563 static std::string tempstring2;
567 tempstring = std::string();
568 tempstring2 = std::string();
571 infostream << "The following test should take around 20ms." << std::endl;
572 TimeTaker timer("Testing std::string speed");
573 const u32 jj = 10000;
574 for (u32 j = 0; j < jj; j++) {
578 for (u32 i = 0; i < ii; i++) {
579 tempstring2 += "asd";
581 for (u32 i = 0; i < ii+1; i++) {
583 if (tempstring == tempstring2)
589 infostream << "All of the following tests should take around 100ms each."
593 TimeTaker timer("Testing floating-point conversion speed");
595 for (u32 i = 0; i < 4000000; i++) {
602 TimeTaker timer("Testing floating-point vector speed");
604 tempv3f1 = v3f(1, 2, 3);
605 tempv3f2 = v3f(4, 5, 6);
606 for (u32 i = 0; i < 10000000; i++) {
607 tempf += tempv3f1.dotProduct(tempv3f2);
608 tempv3f2 += v3f(7, 8, 9);
613 TimeTaker timer("Testing std::map speed");
615 std::map<v2s16, f32> map1;
618 for (s16 y = 0; y < ii; y++) {
619 for (s16 x = 0; x < ii; x++) {
620 map1[v2s16(x, y)] = tempf;
624 for (s16 y = ii - 1; y >= 0; y--) {
625 for (s16 x = 0; x < ii; x++) {
626 tempf = map1[v2s16(x, y)];
632 infostream << "Around 5000/ms should do well here." << std::endl;
633 TimeTaker timer("Testing mutex speed");
646 while(timer.getTimerTime() < 10);
648 u32 dtime = timer.stop();
649 u32 per_ms = n / dtime;
650 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
654 bool ClientLauncher::print_video_modes()
656 IrrlichtDevice *nulldevice;
658 bool vsync = g_settings->getBool("vsync");
659 u16 fsaa = g_settings->getU16("fsaa");
660 MyEventReceiver* receiver = new MyEventReceiver();
662 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
663 params.DriverType = video::EDT_NULL;
664 params.WindowSize = core::dimension2d<u32>(640, 480);
666 params.AntiAlias = fsaa;
667 params.Fullscreen = false;
668 params.Stencilbuffer = false;
669 params.Vsync = vsync;
670 params.EventReceiver = receiver;
671 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
673 nulldevice = createDeviceEx(params);
675 if (nulldevice == NULL) {
680 dstream << _("Available video modes (WxHxD):") << std::endl;
682 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
684 if (videomode_list != NULL) {
685 s32 videomode_count = videomode_list->getVideoModeCount();
686 core::dimension2d<u32> videomode_res;
688 for (s32 i = 0; i < videomode_count; ++i) {
689 videomode_res = videomode_list->getVideoModeResolution(i);
690 videomode_depth = videomode_list->getVideoModeDepth(i);
691 dstream << videomode_res.Width << "x" << videomode_res.Height
692 << "x" << videomode_depth << std::endl;
695 dstream << _("Active video mode (WxHxD):") << std::endl;
696 videomode_res = videomode_list->getDesktopResolution();
697 videomode_depth = videomode_list->getDesktopDepth();
698 dstream << videomode_res.Width << "x" << videomode_res.Height
699 << "x" << videomode_depth << std::endl;
706 return videomode_list != NULL;