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