clientlauncher.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "mainmenumanager.h"
  17. #include "clouds.h"
  18. #include "server.h"
  19. #include "filesys.h"
  20. #include "guiMainMenu.h"
  21. #include "game.h"
  22. #include "player.h"
  23. #include "chat.h"
  24. #include "gettext.h"
  25. #include "profiler.h"
  26. #include "serverlist.h"
  27. #include "guiEngine.h"
  28. #include "fontengine.h"
  29. #include "clientlauncher.h"
  30. #include "version.h"
  31. #include "renderingengine.h"
  32. #include "network/networkexceptions.h"
  33. /* mainmenumanager.h
  34. */
  35. gui::IGUIEnvironment *guienv = nullptr;
  36. gui::IGUIStaticText *guiroot = nullptr;
  37. MainMenuManager g_menumgr;
  38. bool isMenuActive()
  39. {
  40. return g_menumgr.menuCount() != 0;
  41. }
  42. // Passed to menus to allow disconnecting and exiting
  43. MainGameCallback *g_gamecallback = nullptr;
  44. ClientLauncher::~ClientLauncher()
  45. {
  46. delete receiver;
  47. delete input;
  48. delete g_fontengine;
  49. delete g_gamecallback;
  50. delete RenderingEngine::get_instance();
  51. }
  52. bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
  53. {
  54. init_args(game_params, cmd_args);
  55. // List video modes if requested
  56. if (list_video_modes)
  57. return RenderingEngine::print_video_modes();
  58. if (!init_engine()) {
  59. errorstream << "Could not initialize game engine." << std::endl;
  60. return false;
  61. }
  62. // Speed tests (done after irrlicht is loaded to get timer)
  63. if (cmd_args.getFlag("speedtests")) {
  64. dstream << "Running speed tests" << std::endl;
  65. speed_tests();
  66. return true;
  67. }
  68. video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
  69. if (video_driver == NULL) {
  70. errorstream << "Could not initialize video driver." << std::endl;
  71. return false;
  72. }
  73. RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
  74. RenderingEngine::get_instance()->setWindowIcon();
  75. /*
  76. This changes the minimum allowed number of vertices in a VBO.
  77. Default is 500.
  78. */
  79. //driver->setMinHardwareBufferVertexCount(50);
  80. // Create game callback for menus
  81. g_gamecallback = new MainGameCallback();
  82. RenderingEngine::get_instance()->setResizable(true);
  83. init_input();
  84. RenderingEngine::get_scene_manager()->getParameters()->
  85. setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
  86. guienv = RenderingEngine::get_gui_env();
  87. skin = RenderingEngine::get_gui_env()->getSkin();
  88. skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
  89. skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
  90. skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
  91. skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
  92. skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
  93. skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
  94. g_fontengine = new FontEngine(g_settings, guienv);
  95. FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
  96. #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
  97. // Irrlicht 1.8 input colours
  98. skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
  99. skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
  100. #endif
  101. // Create the menu clouds
  102. if (!g_menucloudsmgr)
  103. g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
  104. if (!g_menuclouds)
  105. g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
  106. g_menuclouds->setHeight(100.0f);
  107. g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
  108. scene::ICameraSceneNode* camera;
  109. camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
  110. camera->setFarValue(10000);
  111. /*
  112. GUI stuff
  113. */
  114. ChatBackend chat_backend;
  115. // If an error occurs, this is set to something by menu().
  116. // It is then displayed before the menu shows on the next call to menu()
  117. std::string error_message;
  118. bool reconnect_requested = false;
  119. bool first_loop = true;
  120. /*
  121. Menu-game loop
  122. */
  123. bool retval = true;
  124. bool *kill = porting::signal_handler_killstatus();
  125. while (RenderingEngine::run() && !*kill &&
  126. !g_gamecallback->shutdown_requested) {
  127. // Set the window caption
  128. const wchar_t *text = wgettext("Main Menu");
  129. RenderingEngine::get_raw_device()->
  130. setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
  131. L" " + utf8_to_wide(g_version_hash) +
  132. L" [" + text + L"]").c_str());
  133. delete[] text;
  134. try { // This is used for catching disconnects
  135. RenderingEngine::get_gui_env()->clear();
  136. /*
  137. We need some kind of a root node to be able to add
  138. custom gui elements directly on the screen.
  139. Otherwise they won't be automatically drawn.
  140. */
  141. guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
  142. core::rect<s32>(0, 0, 10000, 10000));
  143. bool game_has_run = launch_game(error_message, reconnect_requested,
  144. game_params, cmd_args);
  145. // Reset the reconnect_requested flag
  146. reconnect_requested = false;
  147. // If skip_main_menu, we only want to startup once
  148. if (skip_main_menu && !first_loop)
  149. break;
  150. first_loop = false;
  151. if (!game_has_run) {
  152. if (skip_main_menu)
  153. break;
  154. continue;
  155. }
  156. // Break out of menu-game loop to shut down cleanly
  157. if (!RenderingEngine::get_raw_device()->run() || *kill) {
  158. if (!g_settings_path.empty())
  159. g_settings->updateConfigFile(g_settings_path.c_str());
  160. break;
  161. }
  162. if (current_playername.length() > PLAYERNAME_SIZE-1) {
  163. error_message = gettext("Player name too long.");
  164. playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
  165. g_settings->set("name", playername);
  166. continue;
  167. }
  168. RenderingEngine::get_video_driver()->setTextureCreationFlag(
  169. video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
  170. #ifdef HAVE_TOUCHSCREENGUI
  171. receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
  172. g_touchscreengui = receiver->m_touchscreengui;
  173. #endif
  174. the_game(
  175. kill,
  176. random_input,
  177. input,
  178. worldspec.path,
  179. current_playername,
  180. current_password,
  181. current_address,
  182. current_port,
  183. error_message,
  184. chat_backend,
  185. &reconnect_requested,
  186. gamespec,
  187. simple_singleplayer_mode
  188. );
  189. RenderingEngine::get_scene_manager()->clear();
  190. #ifdef HAVE_TOUCHSCREENGUI
  191. delete g_touchscreengui;
  192. g_touchscreengui = NULL;
  193. receiver->m_touchscreengui = NULL;
  194. #endif
  195. } //try
  196. catch (con::PeerNotFoundException &e) {
  197. error_message = gettext("Connection error (timed out?)");
  198. errorstream << error_message << std::endl;
  199. }
  200. #ifdef NDEBUG
  201. catch (std::exception &e) {
  202. std::string error_message = "Some exception: \"";
  203. error_message += e.what();
  204. error_message += "\"";
  205. errorstream << error_message << std::endl;
  206. }
  207. #endif
  208. // If no main menu, show error and exit
  209. if (skip_main_menu) {
  210. if (!error_message.empty()) {
  211. verbosestream << "error_message = "
  212. << error_message << std::endl;
  213. retval = false;
  214. }
  215. break;
  216. }
  217. } // Menu-game loop
  218. g_menuclouds->drop();
  219. g_menucloudsmgr->drop();
  220. return retval;
  221. }
  222. void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
  223. {
  224. skip_main_menu = cmd_args.getFlag("go");
  225. // FIXME: This is confusing (but correct)
  226. /* If world_path is set then override it unless skipping the main menu using
  227. * the --go command line param. Else, give preference to the address
  228. * supplied on the command line
  229. */
  230. address = g_settings->get("address");
  231. if (!game_params.world_path.empty() && !skip_main_menu)
  232. address = "";
  233. else if (cmd_args.exists("address"))
  234. address = cmd_args.get("address");
  235. playername = g_settings->get("name");
  236. if (cmd_args.exists("name"))
  237. playername = cmd_args.get("name");
  238. list_video_modes = cmd_args.getFlag("videomodes");
  239. use_freetype = g_settings->getBool("freetype");
  240. random_input = g_settings->getBool("random_input")
  241. || cmd_args.getFlag("random-input");
  242. }
  243. bool ClientLauncher::init_engine()
  244. {
  245. receiver = new MyEventReceiver();
  246. new RenderingEngine(receiver);
  247. return RenderingEngine::get_raw_device() != nullptr;
  248. }
  249. void ClientLauncher::init_input()
  250. {
  251. if (random_input)
  252. input = new RandomInputHandler();
  253. else
  254. input = new RealInputHandler(receiver);
  255. if (g_settings->getBool("enable_joysticks")) {
  256. irr::core::array<irr::SJoystickInfo> infos;
  257. std::vector<irr::SJoystickInfo> joystick_infos;
  258. // Make sure this is called maximum once per
  259. // irrlicht device, otherwise it will give you
  260. // multiple events for the same joystick.
  261. if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
  262. infostream << "Joystick support enabled" << std::endl;
  263. joystick_infos.reserve(infos.size());
  264. for (u32 i = 0; i < infos.size(); i++) {
  265. joystick_infos.push_back(infos[i]);
  266. }
  267. input->joystick.onJoystickConnect(joystick_infos);
  268. } else {
  269. errorstream << "Could not activate joystick support." << std::endl;
  270. }
  271. }
  272. }
  273. bool ClientLauncher::launch_game(std::string &error_message,
  274. bool reconnect_requested, GameParams &game_params,
  275. const Settings &cmd_args)
  276. {
  277. // Initialize menu data
  278. MainMenuData menudata;
  279. menudata.address = address;
  280. menudata.name = playername;
  281. menudata.password = password;
  282. menudata.port = itos(game_params.socket_port);
  283. menudata.script_data.errormessage = error_message;
  284. menudata.script_data.reconnect_requested = reconnect_requested;
  285. error_message.clear();
  286. if (cmd_args.exists("password"))
  287. menudata.password = cmd_args.get("password");
  288. // If a world was commanded, append and select it
  289. if (!game_params.world_path.empty()) {
  290. worldspec.gameid = getWorldGameId(game_params.world_path, true);
  291. worldspec.name = _("[--world parameter]");
  292. if (worldspec.gameid.empty()) { // Create new
  293. worldspec.gameid = g_settings->get("default_game");
  294. worldspec.name += " [new]";
  295. }
  296. worldspec.path = game_params.world_path;
  297. }
  298. /* Show the GUI menu
  299. */
  300. if (!skip_main_menu) {
  301. main_menu(&menudata);
  302. // Skip further loading if there was an exit signal.
  303. if (*porting::signal_handler_killstatus())
  304. return false;
  305. address = menudata.address;
  306. int newport = stoi(menudata.port);
  307. if (newport != 0)
  308. game_params.socket_port = newport;
  309. simple_singleplayer_mode = menudata.simple_singleplayer_mode;
  310. std::vector<WorldSpec> worldspecs = getAvailableWorlds();
  311. if (menudata.selected_world >= 0
  312. && menudata.selected_world < (int)worldspecs.size()) {
  313. g_settings->set("selected_world_path",
  314. worldspecs[menudata.selected_world].path);
  315. worldspec = worldspecs[menudata.selected_world];
  316. }
  317. }
  318. if (!menudata.script_data.errormessage.empty()) {
  319. /* The calling function will pass this back into this function upon the
  320. * next iteration (if any) causing it to be displayed by the GUI
  321. */
  322. error_message = menudata.script_data.errormessage;
  323. return false;
  324. }
  325. if (menudata.name.empty() && !simple_singleplayer_mode) {
  326. error_message = gettext("Please choose a name!");
  327. errorstream << error_message << std::endl;
  328. return false;
  329. }
  330. playername = menudata.name;
  331. password = menudata.password;
  332. current_playername = playername;
  333. current_password = password;
  334. current_address = address;
  335. current_port = game_params.socket_port;
  336. // If using simple singleplayer mode, override
  337. if (simple_singleplayer_mode) {
  338. assert(!skip_main_menu);
  339. current_playername = "singleplayer";
  340. current_password = "";
  341. current_address = "";
  342. current_port = myrand_range(49152, 65535);
  343. } else {
  344. g_settings->set("name", playername);
  345. if (!address.empty()) {
  346. ServerListSpec server;
  347. server["name"] = menudata.servername;
  348. server["address"] = menudata.address;
  349. server["port"] = menudata.port;
  350. server["description"] = menudata.serverdescription;
  351. ServerList::insert(server);
  352. }
  353. }
  354. infostream << "Selected world: " << worldspec.name
  355. << " [" << worldspec.path << "]" << std::endl;
  356. if (current_address.empty()) { // If local game
  357. if (worldspec.path.empty()) {
  358. error_message = gettext("No world selected and no address "
  359. "provided. Nothing to do.");
  360. errorstream << error_message << std::endl;
  361. return false;
  362. }
  363. if (!fs::PathExists(worldspec.path)) {
  364. error_message = gettext("Provided world path doesn't exist: ")
  365. + worldspec.path;
  366. errorstream << error_message << std::endl;
  367. return false;
  368. }
  369. // Load gamespec for required game
  370. gamespec = findWorldSubgame(worldspec.path);
  371. if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
  372. error_message = gettext("Could not find or load game \"")
  373. + worldspec.gameid + "\"";
  374. errorstream << error_message << std::endl;
  375. return false;
  376. }
  377. if (porting::signal_handler_killstatus())
  378. return true;
  379. if (game_params.game_spec.isValid() &&
  380. game_params.game_spec.id != worldspec.gameid) {
  381. warningstream << "Overriding gamespec from \""
  382. << worldspec.gameid << "\" to \""
  383. << game_params.game_spec.id << "\"" << std::endl;
  384. gamespec = game_params.game_spec;
  385. }
  386. if (!gamespec.isValid()) {
  387. error_message = gettext("Invalid gamespec.");
  388. error_message += " (world.gameid=" + worldspec.gameid + ")";
  389. errorstream << error_message << std::endl;
  390. return false;
  391. }
  392. }
  393. return true;
  394. }
  395. void ClientLauncher::main_menu(MainMenuData *menudata)
  396. {
  397. bool *kill = porting::signal_handler_killstatus();
  398. video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  399. infostream << "Waiting for other menus" << std::endl;
  400. while (RenderingEngine::get_raw_device()->run() && !*kill) {
  401. if (!isMenuActive())
  402. break;
  403. driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
  404. RenderingEngine::get_gui_env()->drawAll();
  405. driver->endScene();
  406. // On some computers framerate doesn't seem to be automatically limited
  407. sleep_ms(25);
  408. }
  409. infostream << "Waited for other menus" << std::endl;
  410. // Cursor can be non-visible when coming from the game
  411. #ifndef ANDROID
  412. RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
  413. #endif
  414. /* show main menu */
  415. GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
  416. /* leave scene manager in a clean state */
  417. RenderingEngine::get_scene_manager()->clear();
  418. }
  419. void ClientLauncher::speed_tests()
  420. {
  421. // volatile to avoid some potential compiler optimisations
  422. volatile static s16 temp16;
  423. volatile static f32 tempf;
  424. static v3f tempv3f1;
  425. static v3f tempv3f2;
  426. static std::string tempstring;
  427. static std::string tempstring2;
  428. tempv3f1 = v3f();
  429. tempv3f2 = v3f();
  430. tempstring.clear();
  431. tempstring2.clear();
  432. {
  433. infostream << "The following test should take around 20ms." << std::endl;
  434. TimeTaker timer("Testing std::string speed");
  435. const u32 jj = 10000;
  436. for (u32 j = 0; j < jj; j++) {
  437. tempstring = "";
  438. tempstring2 = "";
  439. const u32 ii = 10;
  440. for (u32 i = 0; i < ii; i++) {
  441. tempstring2 += "asd";
  442. }
  443. for (u32 i = 0; i < ii+1; i++) {
  444. tempstring += "asd";
  445. if (tempstring == tempstring2)
  446. break;
  447. }
  448. }
  449. }
  450. infostream << "All of the following tests should take around 100ms each."
  451. << std::endl;
  452. {
  453. TimeTaker timer("Testing floating-point conversion speed");
  454. tempf = 0.001;
  455. for (u32 i = 0; i < 4000000; i++) {
  456. temp16 += tempf;
  457. tempf += 0.001;
  458. }
  459. }
  460. {
  461. TimeTaker timer("Testing floating-point vector speed");
  462. tempv3f1 = v3f(1, 2, 3);
  463. tempv3f2 = v3f(4, 5, 6);
  464. for (u32 i = 0; i < 10000000; i++) {
  465. tempf += tempv3f1.dotProduct(tempv3f2);
  466. tempv3f2 += v3f(7, 8, 9);
  467. }
  468. }
  469. {
  470. TimeTaker timer("Testing std::map speed");
  471. std::map<v2s16, f32> map1;
  472. tempf = -324;
  473. const s16 ii = 300;
  474. for (s16 y = 0; y < ii; y++) {
  475. for (s16 x = 0; x < ii; x++) {
  476. map1[v2s16(x, y)] = tempf;
  477. tempf += 1;
  478. }
  479. }
  480. for (s16 y = ii - 1; y >= 0; y--) {
  481. for (s16 x = 0; x < ii; x++) {
  482. tempf = map1[v2s16(x, y)];
  483. }
  484. }
  485. }
  486. {
  487. infostream << "Around 5000/ms should do well here." << std::endl;
  488. TimeTaker timer("Testing mutex speed");
  489. std::mutex m;
  490. u32 n = 0;
  491. u32 i = 0;
  492. do {
  493. n += 10000;
  494. for (; i < n; i++) {
  495. m.lock();
  496. m.unlock();
  497. }
  498. }
  499. // Do at least 10ms
  500. while(timer.getTimerTime() < 10);
  501. u32 dtime = timer.stop();
  502. u32 per_ms = n / dtime;
  503. infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
  504. }
  505. }