CMT.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * CMT.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. // CMT.cpp : Defines the entry point for the console application.
  11. #include "StdInc.h"
  12. #include "CMT.h"
  13. #include "CGameInfo.h"
  14. #include "mainmenu/CMainMenu.h"
  15. #include "mainmenu/CPrologEpilogVideo.h"
  16. #include "gui/CursorHandler.h"
  17. #include "CPlayerInterface.h"
  18. #include "CVideoHandler.h"
  19. #include "CMusicHandler.h"
  20. #include "gui/CGuiHandler.h"
  21. #include "gui/WindowHandler.h"
  22. #include "CServerHandler.h"
  23. #include "gui/NotificationHandler.h"
  24. #include "ClientCommandManager.h"
  25. #include "windows/CMessage.h"
  26. #include "render/IScreenHandler.h"
  27. #include "../lib/filesystem/Filesystem.h"
  28. #include "../lib/CConsoleHandler.h"
  29. #include "../lib/CGeneralTextHandler.h"
  30. #include "../lib/VCMIDirs.h"
  31. #include "../lib/mapping/CCampaignHandler.h"
  32. #include "../lib/logging/CBasicLogConfigurator.h"
  33. #include <boost/program_options.hpp>
  34. #include <vstd/StringUtils.h>
  35. #include <SDL_events.h>
  36. #include <SDL_hints.h>
  37. #include <SDL_main.h>
  38. #ifdef VCMI_WINDOWS
  39. #include <SDL_syswm.h>
  40. #endif
  41. #ifdef VCMI_ANDROID
  42. #include "../lib/CAndroidVMHelper.h"
  43. #include <SDL_system.h>
  44. #endif
  45. #if __MINGW32__
  46. #undef main
  47. #endif
  48. namespace po = boost::program_options;
  49. namespace po_style = boost::program_options::command_line_style;
  50. namespace bfs = boost::filesystem;
  51. extern boost::thread_specific_ptr<bool> inGuiThread;
  52. std::queue<SDL_Event> SDLEventsQueue;
  53. boost::mutex eventsM;
  54. static po::variables_map vm;
  55. #ifndef VCMI_IOS
  56. void processCommand(const std::string &message);
  57. #endif
  58. void playIntro();
  59. static void mainLoop();
  60. static CBasicLogConfigurator *logConfig;
  61. void init()
  62. {
  63. CStopWatch tmh;
  64. loadDLLClasses();
  65. const_cast<CGameInfo*>(CGI)->setFromLib();
  66. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  67. // Debug code to load all maps on start
  68. //ClientCommandManager commandController;
  69. //commandController.processCommand("convert txt", false);
  70. }
  71. static void prog_version()
  72. {
  73. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  74. std::cout << VCMIDirs::get().genHelpString();
  75. }
  76. static void prog_help(const po::options_description &opts)
  77. {
  78. auto time = std::time(0);
  79. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  80. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  81. printf("This is free software; see the source for copying conditions. There is NO\n");
  82. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  83. printf("\n");
  84. std::cout << opts;
  85. }
  86. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  87. int wmain(int argc, wchar_t* argv[])
  88. #elif defined(VCMI_MOBILE)
  89. int SDL_main(int argc, char *argv[])
  90. #else
  91. int main(int argc, char * argv[])
  92. #endif
  93. {
  94. #ifdef VCMI_ANDROID
  95. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  96. // boost will crash without this
  97. setenv("LANG", "C", 1);
  98. #endif
  99. #if !defined(VCMI_MOBILE)
  100. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  101. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  102. #endif
  103. std::cout << "Starting... " << std::endl;
  104. po::options_description opts("Allowed options");
  105. opts.add_options()
  106. ("help,h", "display help and exit")
  107. ("version,v", "display version information and exit")
  108. ("disable-shm", "force disable shared memory usage")
  109. ("enable-shm-uuid", "use UUID for shared memory identifier")
  110. ("testmap", po::value<std::string>(), "")
  111. ("testsave", po::value<std::string>(), "")
  112. ("spectate,s", "enable spectator interface for AI-only games")
  113. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  114. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  115. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  116. ("spectate-skip-battle", "skip battles in spectator view")
  117. ("spectate-skip-battle-result", "skip battle result window")
  118. ("onlyAI", "allow to run without human player, all players will be default AI")
  119. ("headless", "runs without GUI, implies --onlyAI")
  120. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  121. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  122. ("autoSkip", "automatically skip turns in GUI")
  123. ("disable-video", "disable video player")
  124. ("nointro,i", "skips intro movies")
  125. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  126. ("serverport", po::value<si64>(), "override port specified in config file")
  127. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  128. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  129. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  130. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  131. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  132. ("lobby-host", "if this client hosts session")
  133. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  134. ("lobby-connections", po::value<ui16>(), "connections of server")
  135. ("lobby-username", po::value<std::string>(), "player name")
  136. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  137. ("uuid", po::value<std::string>(), "uuid for the client");
  138. if(argc > 1)
  139. {
  140. try
  141. {
  142. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  143. }
  144. catch(std::exception &e)
  145. {
  146. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  147. }
  148. }
  149. po::notify(vm);
  150. if(vm.count("help"))
  151. {
  152. prog_help(opts);
  153. #ifdef VCMI_IOS
  154. exit(0);
  155. #else
  156. return 0;
  157. #endif
  158. }
  159. if(vm.count("version"))
  160. {
  161. prog_version();
  162. #ifdef VCMI_IOS
  163. exit(0);
  164. #else
  165. return 0;
  166. #endif
  167. }
  168. // Init old logging system and new (temporary) logging system
  169. CStopWatch total, pomtime;
  170. std::cout.flags(std::ios::unitbuf);
  171. #ifndef VCMI_IOS
  172. console = new CConsoleHandler();
  173. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  174. {
  175. ClientCommandManager commandController;
  176. commandController.processCommand(buffer, calledFromIngameConsole);
  177. };
  178. *console->cb = callbackFunction;
  179. console->start();
  180. #endif
  181. const bfs::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  182. logConfig = new CBasicLogConfigurator(logPath, console);
  183. logConfig->configureDefault();
  184. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  185. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  186. logGlobal->info("The log file will be saved to %s", logPath);
  187. // Init filesystem and settings
  188. preinitDLL(::console);
  189. Settings session = settings.write["session"];
  190. auto setSettingBool = [](std::string key, std::string arg) {
  191. Settings s = settings.write(vstd::split(key, "/"));
  192. if(::vm.count(arg))
  193. s->Bool() = true;
  194. else if(s->isNull())
  195. s->Bool() = false;
  196. };
  197. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  198. Settings s = settings.write(vstd::split(key, "/"));
  199. if(::vm.count(arg))
  200. s->Integer() = ::vm[arg].as<si64>();
  201. else if(s->isNull())
  202. s->Integer() = defaultValue;
  203. };
  204. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  205. Settings s = settings.write(vstd::split(key, "/"));
  206. if(::vm.count(arg))
  207. s->String() = ::vm[arg].as<std::string>();
  208. else if(s->isNull())
  209. s->String() = defaultValue;
  210. };
  211. setSettingBool("session/onlyai", "onlyAI");
  212. if(vm.count("headless"))
  213. {
  214. session["headless"].Bool() = true;
  215. session["onlyai"].Bool() = true;
  216. }
  217. else if(vm.count("spectate"))
  218. {
  219. session["spectate"].Bool() = true;
  220. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  221. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  222. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  223. if(vm.count("spectate-hero-speed"))
  224. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  225. if(vm.count("spectate-battle-speed"))
  226. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  227. }
  228. // Server settings
  229. setSettingBool("session/donotstartserver", "donotstartserver");
  230. // Shared memory options
  231. setSettingBool("session/disable-shm", "disable-shm");
  232. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  233. // Init special testing settings
  234. setSettingInteger("session/serverport", "serverport", 0);
  235. setSettingString("session/saveprefix", "saveprefix", "");
  236. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  237. // Initialize logging based on settings
  238. logConfig->configure();
  239. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  240. // Some basic data validation to produce better error messages in cases of incorrect install
  241. auto testFile = [](std::string filename, std::string message) -> bool
  242. {
  243. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  244. return true;
  245. logGlobal->error("Error: %s was not found!", message);
  246. return false;
  247. };
  248. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  249. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  250. {
  251. exit(1); // These are unrecoverable errors
  252. }
  253. // these two are optional + some installs have them on CD and not in data directory
  254. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  255. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  256. srand ( (unsigned int)time(nullptr) );
  257. if(!settings["session"]["headless"].Bool())
  258. GH.init();
  259. CCS = new CClientState();
  260. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  261. CSH = new CServerHandler();
  262. // Initialize video
  263. #ifdef DISABLE_VIDEO
  264. CCS->videoh = new CEmptyVideoPlayer();
  265. #else
  266. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  267. CCS->videoh = new CVideoPlayer();
  268. else
  269. CCS->videoh = new CEmptyVideoPlayer();
  270. #endif
  271. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  272. if(!settings["session"]["headless"].Bool())
  273. {
  274. //initializing audio
  275. CCS->soundh = new CSoundHandler();
  276. CCS->soundh->init();
  277. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  278. CCS->musich = new CMusicHandler();
  279. CCS->musich->init();
  280. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  281. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  282. }
  283. #ifdef VCMI_MAC
  284. // Ctrl+click should be treated as a right click on Mac OS X
  285. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  286. #endif
  287. #ifdef SDL_HINT_MOUSE_TOUCH_EVENTS
  288. if(GH.isPointerRelativeMode)
  289. {
  290. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
  291. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  292. }
  293. #endif
  294. #ifndef VCMI_NO_THREADED_LOAD
  295. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  296. boost::thread loading(init);
  297. #else
  298. init();
  299. #endif
  300. if(!settings["session"]["headless"].Bool())
  301. {
  302. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  303. playIntro();
  304. GH.screenHandler().clearScreen();
  305. }
  306. #ifndef VCMI_NO_THREADED_LOAD
  307. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  308. {
  309. CAndroidVMHelper vmHelper;
  310. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  311. #endif // ANDROID
  312. loading.join();
  313. #ifdef VCMI_ANDROID
  314. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  315. }
  316. #endif // ANDROID
  317. #endif // THREADED
  318. if(!settings["session"]["headless"].Bool())
  319. {
  320. pomtime.getDiff();
  321. graphics = new Graphics(); // should be before curh
  322. CCS->curh = new CursorHandler();
  323. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  324. CMessage::init();
  325. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  326. CCS->curh->show();
  327. }
  328. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  329. session["autoSkip"].Bool() = vm.count("autoSkip");
  330. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  331. session["aiSolo"].Bool() = false;
  332. std::shared_ptr<CMainMenu> mmenu;
  333. if(vm.count("testmap"))
  334. {
  335. session["testmap"].String() = vm["testmap"].as<std::string>();
  336. session["onlyai"].Bool() = true;
  337. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  338. }
  339. else if(vm.count("testsave"))
  340. {
  341. session["testsave"].String() = vm["testsave"].as<std::string>();
  342. session["onlyai"].Bool() = true;
  343. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  344. }
  345. else
  346. {
  347. mmenu = CMainMenu::create();
  348. GH.curInt = mmenu.get();
  349. }
  350. std::vector<std::string> names;
  351. session["lobby"].Bool() = false;
  352. if(vm.count("lobby"))
  353. {
  354. session["lobby"].Bool() = true;
  355. session["host"].Bool() = false;
  356. session["address"].String() = vm["lobby-address"].as<std::string>();
  357. if(vm.count("lobby-username"))
  358. session["username"].String() = vm["lobby-username"].as<std::string>();
  359. else
  360. session["username"].String() = settings["launcher"]["lobbyUsername"].String();
  361. if(vm.count("lobby-gamemode"))
  362. session["gamemode"].Integer() = vm["lobby-gamemode"].as<ui16>();
  363. else
  364. session["gamemode"].Integer() = 0;
  365. CSH->uuid = vm["uuid"].as<std::string>();
  366. session["port"].Integer() = vm["lobby-port"].as<ui16>();
  367. logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
  368. if(vm.count("lobby-host"))
  369. {
  370. session["host"].Bool() = true;
  371. session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
  372. session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
  373. logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
  374. }
  375. //we should not reconnect to previous game in online mode
  376. Settings saveSession = settings.write["server"]["reconnect"];
  377. saveSession->Bool() = false;
  378. //start lobby immediately
  379. names.push_back(session["username"].String());
  380. ESelectionScreen sscreen = session["gamemode"].Integer() == 0 ? ESelectionScreen::newGame : ESelectionScreen::loadGame;
  381. mmenu->openLobby(sscreen, session["host"].Bool(), &names, ELoadMode::MULTI);
  382. }
  383. // Restore remote session - start game immediately
  384. if(settings["server"]["reconnect"].Bool())
  385. {
  386. CSH->restoreLastSession();
  387. }
  388. if(!settings["session"]["headless"].Bool())
  389. {
  390. mainLoop();
  391. }
  392. else
  393. {
  394. while(true)
  395. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  396. }
  397. return 0;
  398. }
  399. //plays intro, ends when intro is over or button has been pressed (handles events)
  400. void playIntro()
  401. {
  402. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  403. {
  404. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  405. }
  406. }
  407. static void handleEvent(SDL_Event & ev)
  408. {
  409. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  410. {
  411. #ifdef VCMI_ANDROID
  412. handleQuit(false);
  413. #else
  414. handleQuit();
  415. #endif
  416. return;
  417. }
  418. #ifdef VCMI_ANDROID
  419. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  420. {
  421. handleQuit(true);
  422. }
  423. #endif
  424. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  425. {
  426. Settings full = settings.write["video"]["fullscreen"];
  427. full->Bool() = !full->Bool();
  428. return;
  429. }
  430. else if(ev.type == SDL_USEREVENT)
  431. {
  432. switch(static_cast<EUserEvent>(ev.user.code))
  433. {
  434. case EUserEvent::FORCE_QUIT:
  435. {
  436. handleQuit(false);
  437. return;
  438. }
  439. break;
  440. case EUserEvent::RETURN_TO_MAIN_MENU:
  441. {
  442. CSH->endGameplay();
  443. GH.defActionsDef = 63;
  444. CMM->menu->switchToTab("main");
  445. }
  446. break;
  447. case EUserEvent::RESTART_GAME:
  448. {
  449. CSH->sendRestartGame();
  450. }
  451. break;
  452. case EUserEvent::CAMPAIGN_START_SCENARIO:
  453. {
  454. CSH->campaignServerRestartLock.set(true);
  455. CSH->endGameplay();
  456. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  457. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  458. auto finisher = [=]()
  459. {
  460. if(ourCampaign->mapsRemaining.size())
  461. {
  462. GH.windows().pushWindow(CMM);
  463. GH.windows().pushWindow(CMM->menu);
  464. CMM->openCampaignLobby(ourCampaign);
  465. }
  466. };
  467. if(epilogue.hasPrologEpilog)
  468. {
  469. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  470. }
  471. else
  472. {
  473. CSH->campaignServerRestartLock.waitUntil(false);
  474. finisher();
  475. }
  476. }
  477. break;
  478. case EUserEvent::RETURN_TO_MENU_LOAD:
  479. CSH->endGameplay();
  480. GH.defActionsDef = 63;
  481. CMM->menu->switchToTab("load");
  482. break;
  483. case EUserEvent::FULLSCREEN_TOGGLED:
  484. {
  485. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  486. GH.onScreenResize();
  487. break;
  488. }
  489. default:
  490. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  491. break;
  492. }
  493. return;
  494. }
  495. else if(ev.type == SDL_WINDOWEVENT)
  496. {
  497. switch (ev.window.event) {
  498. case SDL_WINDOWEVENT_RESTORED:
  499. #ifndef VCMI_IOS
  500. {
  501. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  502. GH.onScreenResize();
  503. }
  504. #endif
  505. break;
  506. }
  507. return;
  508. }
  509. else if(ev.type == SDL_SYSWMEVENT)
  510. {
  511. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  512. {
  513. NotificationHandler::handleSdlEvent(ev);
  514. }
  515. }
  516. //preprocessing
  517. if(ev.type == SDL_MOUSEMOTION)
  518. {
  519. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  520. }
  521. {
  522. boost::unique_lock<boost::mutex> lock(eventsM);
  523. SDLEventsQueue.push(ev);
  524. }
  525. }
  526. static void mainLoop()
  527. {
  528. SettingsListener resChanged = settings.listen["video"]["resolution"];
  529. SettingsListener fsChanged = settings.listen["video"]["fullscreen"];
  530. resChanged([](const JsonNode &newState){ CGuiHandler::pushUserEvent(EUserEvent::FULLSCREEN_TOGGLED); });
  531. fsChanged([](const JsonNode &newState){ CGuiHandler::pushUserEvent(EUserEvent::FULLSCREEN_TOGGLED); });
  532. inGuiThread.reset(new bool(true));
  533. while(1) //main SDL events loop
  534. {
  535. SDL_Event ev;
  536. while(1 == SDL_PollEvent(&ev))
  537. {
  538. handleEvent(ev);
  539. }
  540. CSH->applyPacksOnLobbyScreen();
  541. GH.renderFrame();
  542. }
  543. }
  544. static void quitApplication()
  545. {
  546. if(!settings["session"]["headless"].Bool())
  547. {
  548. if(CSH->client)
  549. CSH->endGameplay();
  550. }
  551. GH.windows().clear();
  552. CMM.reset();
  553. if(!settings["session"]["headless"].Bool())
  554. {
  555. // cleanup, mostly to remove false leaks from analyzer
  556. if(CCS)
  557. {
  558. CCS->musich->release();
  559. CCS->soundh->release();
  560. vstd::clear_pointer(CCS);
  561. }
  562. CMessage::dispose();
  563. vstd::clear_pointer(graphics);
  564. }
  565. vstd::clear_pointer(VLC);
  566. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  567. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  568. if(!settings["session"]["headless"].Bool())
  569. GH.screenHandler().close();
  570. if(logConfig != nullptr)
  571. {
  572. logConfig->deconfigure();
  573. delete logConfig;
  574. logConfig = nullptr;
  575. }
  576. std::cout << "Ending...\n";
  577. exit(0);
  578. }
  579. void handleQuit(bool ask)
  580. {
  581. if(CSH->client && LOCPLINT && ask)
  582. {
  583. CCS->curh->set(Cursor::Map::POINTER);
  584. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], [](){
  585. // Workaround for assertion failure on exit:
  586. // handleQuit() is alway called during SDL event processing
  587. // during which, eventsM is kept locked
  588. // this leads to assertion failure if boost::mutex is in locked state
  589. eventsM.unlock();
  590. quitApplication();
  591. }, nullptr);
  592. }
  593. else
  594. {
  595. quitApplication();
  596. }
  597. }