CMT.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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. //
  12. #include "StdInc.h"
  13. #include <SDL_mixer.h>
  14. #include <boost/program_options.hpp>
  15. #include "gui/SDL_Extensions.h"
  16. #include "CGameInfo.h"
  17. #include "mapHandler.h"
  18. #include "../lib/filesystem/Filesystem.h"
  19. #include "../lib/filesystem/FileStream.h"
  20. #include "mainmenu/CMainMenu.h"
  21. #include "lobby/CSelectionBase.h"
  22. #include "windows/CCastleInterface.h"
  23. #include "../lib/CConsoleHandler.h"
  24. #include "gui/CCursorHandler.h"
  25. #include "../lib/CGameState.h"
  26. #include "../CCallback.h"
  27. #include "CPlayerInterface.h"
  28. #include "windows/CAdvmapInterface.h"
  29. #include "../lib/CBuildingHandler.h"
  30. #include "CVideoHandler.h"
  31. #include "../lib/CHeroHandler.h"
  32. #include "../lib/CCreatureHandler.h"
  33. #include "../lib/spells/CSpellHandler.h"
  34. #include "CMusicHandler.h"
  35. #include "../lib/CGeneralTextHandler.h"
  36. #include "Graphics.h"
  37. #include "Client.h"
  38. #include "../lib/CConfigHandler.h"
  39. #include "../lib/serializer/BinaryDeserializer.h"
  40. #include "../lib/serializer/BinarySerializer.h"
  41. #include "../lib/VCMI_Lib.h"
  42. #include "../lib/VCMIDirs.h"
  43. #include "../lib/NetPacks.h"
  44. #include "CMessage.h"
  45. #include "../lib/CModHandler.h"
  46. #include "../lib/CTownHandler.h"
  47. #include "../lib/CArtHandler.h"
  48. #include "../lib/CScriptingModule.h"
  49. #include "../lib/GameConstants.h"
  50. #include "gui/CGuiHandler.h"
  51. #include "../lib/logging/CBasicLogConfigurator.h"
  52. #include "../lib/StringConstants.h"
  53. #include "../lib/CPlayerState.h"
  54. #include "gui/CAnimation.h"
  55. #include "../lib/serializer/Connection.h"
  56. #include "CServerHandler.h"
  57. #include <boost/asio.hpp>
  58. #include "mainmenu/CPrologEpilogVideo.h"
  59. #ifdef VCMI_WINDOWS
  60. #include "SDL_syswm.h"
  61. #endif
  62. #ifdef VCMI_ANDROID
  63. #include "lib/CAndroidVMHelper.h"
  64. #endif
  65. #include "../lib/UnlockGuard.h"
  66. #include "CMT.h"
  67. #if __MINGW32__
  68. #undef main
  69. #endif
  70. namespace po = boost::program_options;
  71. namespace po_style = boost::program_options::command_line_style;
  72. namespace bfs = boost::filesystem;
  73. std::string NAME_AFFIX = "client";
  74. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  75. CGuiHandler GH;
  76. int preferredDriverIndex = -1;
  77. SDL_Window * mainWindow = nullptr;
  78. SDL_Renderer * mainRenderer = nullptr;
  79. SDL_Texture * screenTexture = nullptr;
  80. extern boost::thread_specific_ptr<bool> inGuiThread;
  81. SDL_Surface *screen = nullptr, //main screen surface
  82. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  83. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  84. std::queue<SDL_Event> events;
  85. boost::mutex eventsM;
  86. static po::variables_map vm;
  87. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  88. static bool ermInteractiveMode = false; //structurize when time is right
  89. void processCommand(const std::string &message);
  90. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  91. void dispose();
  92. void playIntro();
  93. static void mainLoop();
  94. #ifndef VCMI_WINDOWS
  95. #ifndef _GNU_SOURCE
  96. #define _GNU_SOURCE
  97. #endif
  98. #include <getopt.h>
  99. #endif
  100. void init()
  101. {
  102. CStopWatch tmh, pomtime;
  103. loadDLLClasses();
  104. const_cast<CGameInfo*>(CGI)->setFromLib();
  105. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  106. if(!settings["session"]["headless"].Bool())
  107. {
  108. pomtime.getDiff();
  109. CCS->curh = new CCursorHandler();
  110. graphics = new Graphics(); // should be before curh->init()
  111. CCS->curh->initCursor();
  112. CCS->curh->show();
  113. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  114. pomtime.getDiff();
  115. graphics->load();
  116. logGlobal->info("\tMain graphics: %d ms", pomtime.getDiff());
  117. logGlobal->info("Initializing game graphics: %d ms", tmh.getDiff());
  118. CMessage::init();
  119. logGlobal->info("Message handler: %d ms", tmh.getDiff());
  120. }
  121. }
  122. static void prog_version()
  123. {
  124. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  125. std::cout << VCMIDirs::get().genHelpString();
  126. }
  127. static void prog_help(const po::options_description &opts)
  128. {
  129. auto time = std::time(0);
  130. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  131. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  132. printf("This is free software; see the source for copying conditions. There is NO\n");
  133. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  134. printf("\n");
  135. std::cout << opts;
  136. }
  137. static void SDLLogCallback(void* userdata,
  138. int category,
  139. SDL_LogPriority priority,
  140. const char* message)
  141. {
  142. //todo: convert SDL log priority to vcmi log priority
  143. //todo: make separate log domain for SDL
  144. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  145. }
  146. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  147. int wmain(int argc, wchar_t* argv[])
  148. #elif defined(VCMI_APPLE) || defined(VCMI_ANDROID)
  149. int SDL_main(int argc, char *argv[])
  150. #else
  151. int main(int argc, char * argv[])
  152. #endif
  153. {
  154. #ifdef VCMI_ANDROID
  155. // boost will crash without this
  156. setenv("LANG", "C", 1);
  157. #endif
  158. #ifndef VCMI_ANDROID
  159. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  160. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  161. #endif
  162. std::cout << "Starting... " << std::endl;
  163. po::options_description opts("Allowed options");
  164. opts.add_options()
  165. ("help,h", "display help and exit")
  166. ("version,v", "display version information and exit")
  167. ("disable-shm", "force disable shared memory usage")
  168. ("enable-shm-uuid", "use UUID for shared memory identifier")
  169. ("testmap", po::value<std::string>(), "")
  170. ("testsave", po::value<std::string>(), "")
  171. ("spectate,s", "enable spectator interface for AI-only games")
  172. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  173. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  174. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  175. ("spectate-skip-battle", "skip battles in spectator view")
  176. ("spectate-skip-battle-result", "skip battle result window")
  177. ("onlyAI", "allow to run without human player, all players will be default AI")
  178. ("headless", "runs without GUI, implies --onlyAI")
  179. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  180. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  181. ("autoSkip", "automatically skip turns in GUI")
  182. ("disable-video", "disable video player")
  183. ("nointro,i", "skips intro movies")
  184. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  185. ("serverport", po::value<si64>(), "override port specified in config file")
  186. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  187. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
  188. if(argc > 1)
  189. {
  190. try
  191. {
  192. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  193. }
  194. catch(std::exception &e)
  195. {
  196. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  197. }
  198. }
  199. po::notify(vm);
  200. if(vm.count("help"))
  201. {
  202. prog_help(opts);
  203. return 0;
  204. }
  205. if(vm.count("version"))
  206. {
  207. prog_version();
  208. return 0;
  209. }
  210. // Init old logging system and new (temporary) logging system
  211. CStopWatch total, pomtime;
  212. std::cout.flags(std::ios::unitbuf);
  213. console = new CConsoleHandler();
  214. *console->cb = processCommand;
  215. console->start();
  216. const bfs::path logPath = VCMIDirs::get().userCachePath() / "VCMI_Client_log.txt";
  217. CBasicLogConfigurator logConfig(logPath, console);
  218. logConfig.configureDefault();
  219. logGlobal->info(NAME);
  220. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  221. logGlobal->info("The log file will be saved to %s", logPath);
  222. // Init filesystem and settings
  223. preinitDLL(::console);
  224. settings.init();
  225. Settings session = settings.write["session"];
  226. session["onlyai"].Bool() = vm.count("onlyAI");
  227. if(vm.count("headless"))
  228. {
  229. session["headless"].Bool() = true;
  230. session["onlyai"].Bool() = true;
  231. }
  232. else if(vm.count("spectate"))
  233. {
  234. session["spectate"].Bool() = true;
  235. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  236. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  237. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  238. if(vm.count("spectate-hero-speed"))
  239. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  240. if(vm.count("spectate-battle-speed"))
  241. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  242. }
  243. // Server settings
  244. session["donotstartserver"].Bool() = vm.count("donotstartserver");
  245. // Shared memory options
  246. session["disable-shm"].Bool() = vm.count("disable-shm");
  247. session["enable-shm-uuid"].Bool() = vm.count("enable-shm-uuid");
  248. // Init special testing settings
  249. session["serverport"].Integer() = vm.count("serverport") ? vm["serverport"].as<si64>() : 0;
  250. session["saveprefix"].String() = vm.count("saveprefix") ? vm["saveprefix"].as<std::string>() : "";
  251. session["savefrequency"].Integer() = vm.count("savefrequency") ? vm["savefrequency"].as<si64>() : 1;
  252. // Initialize logging based on settings
  253. logConfig.configure();
  254. // Some basic data validation to produce better error messages in cases of incorrect install
  255. auto testFile = [](std::string filename, std::string message) -> bool
  256. {
  257. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  258. return true;
  259. logGlobal->error("Error: %s was not found!", message);
  260. return false;
  261. };
  262. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  263. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  264. {
  265. exit(1); // These are unrecoverable errors
  266. }
  267. // these two are optional + some installs have them on CD and not in data directory
  268. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  269. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  270. conf.init();
  271. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  272. srand ( time(nullptr) );
  273. const JsonNode& video = settings["video"];
  274. const JsonNode& res = video["screenRes"];
  275. //something is really wrong...
  276. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  277. {
  278. logGlobal->error("Fatal error: failed to load settings!");
  279. logGlobal->error("Possible reasons:");
  280. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  281. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  282. logGlobal->error("VCMI will now exit...");
  283. exit(EXIT_FAILURE);
  284. }
  285. if(!settings["session"]["headless"].Bool())
  286. {
  287. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  288. {
  289. logGlobal->error("Something was wrong: %s", SDL_GetError());
  290. exit(-1);
  291. }
  292. #ifdef VCMI_ANDROID
  293. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  294. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  295. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  296. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  297. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  298. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  299. #endif // VCMI_ANDROID
  300. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  301. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  302. int driversCount = SDL_GetNumRenderDrivers();
  303. std::string preferredDriverName = video["driver"].String();
  304. logGlobal->info("Found %d render drivers", driversCount);
  305. for(int it = 0; it < driversCount; it++)
  306. {
  307. SDL_RendererInfo info;
  308. SDL_GetRenderDriverInfo(it,&info);
  309. std::string driverName(info.name);
  310. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  311. {
  312. preferredDriverIndex = it;
  313. logGlobal->info("\t%s (active)", driverName);
  314. }
  315. else
  316. logGlobal->info("\t%s", driverName);
  317. }
  318. config::CConfigHandler::GuiOptionsMap::key_type resPair(res["width"].Float(), res["height"].Float());
  319. if (conf.guiOptions.count(resPair) == 0)
  320. {
  321. // selected resolution was not found - complain & fallback to something that we do have.
  322. logGlobal->error("Selected resolution %dx%d was not found!", resPair.first, resPair.second);
  323. if (conf.guiOptions.empty())
  324. {
  325. logGlobal->error("Unable to continue - no valid resolutions found! Please reinstall VCMI to fix this");
  326. exit(1);
  327. }
  328. else
  329. {
  330. Settings newRes = settings.write["video"]["screenRes"];
  331. newRes["width"].Float() = conf.guiOptions.begin()->first.first;
  332. newRes["height"].Float() = conf.guiOptions.begin()->first.second;
  333. conf.SetResolution(newRes["width"].Float(), newRes["height"].Float());
  334. logGlobal->error("Falling back to %dx%d", newRes["width"].Integer(), newRes["height"].Integer());
  335. }
  336. }
  337. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), video["displayIndex"].Float());
  338. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  339. }
  340. CCS = new CClientState();
  341. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  342. CSH = new CServerHandler();
  343. // Initialize video
  344. #ifdef DISABLE_VIDEO
  345. CCS->videoh = new CEmptyVideoPlayer();
  346. #else
  347. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  348. CCS->videoh = new CVideoPlayer();
  349. else
  350. CCS->videoh = new CEmptyVideoPlayer();
  351. #endif
  352. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  353. if(!settings["session"]["headless"].Bool())
  354. {
  355. //initializing audio
  356. CCS->soundh = new CSoundHandler();
  357. CCS->soundh->init();
  358. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  359. CCS->musich = new CMusicHandler();
  360. CCS->musich->init();
  361. CCS->musich->setVolume(settings["general"]["music"].Float());
  362. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  363. }
  364. #ifdef __APPLE__
  365. // Ctrl+click should be treated as a right click on Mac OS X
  366. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  367. #endif
  368. #ifndef VCMI_NO_THREADED_LOAD
  369. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  370. boost::thread loading(init);
  371. #else
  372. init();
  373. #endif
  374. if(!settings["session"]["headless"].Bool())
  375. {
  376. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  377. playIntro();
  378. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  379. SDL_RenderClear(mainRenderer);
  380. }
  381. SDL_RenderPresent(mainRenderer);
  382. #ifndef VCMI_NO_THREADED_LOAD
  383. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  384. {
  385. CAndroidVMHelper vmHelper;
  386. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  387. #endif // ANDROID
  388. loading.join();
  389. #ifdef VCMI_ANDROID
  390. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  391. }
  392. #endif // ANDROID
  393. #endif // THREADED
  394. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  395. session["autoSkip"].Bool() = vm.count("autoSkip");
  396. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  397. session["aiSolo"].Bool() = false;
  398. if(vm.count("testmap"))
  399. {
  400. session["testmap"].String() = vm["testmap"].as<std::string>();
  401. session["onlyai"].Bool() = true;
  402. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  403. }
  404. else if(vm.count("testsave"))
  405. {
  406. session["testsave"].String() = vm["testsave"].as<std::string>();
  407. session["onlyai"].Bool() = true;
  408. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  409. }
  410. else
  411. {
  412. GH.curInt = CMainMenu::create();
  413. }
  414. if(!settings["session"]["headless"].Bool())
  415. {
  416. mainLoop();
  417. }
  418. else
  419. {
  420. while(true)
  421. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  422. }
  423. return 0;
  424. }
  425. void printInfoAboutIntObject(const CIntObject *obj, int level)
  426. {
  427. std::stringstream sbuffer;
  428. sbuffer << std::string(level, '\t');
  429. sbuffer << typeid(*obj).name() << " *** ";
  430. if (obj->active)
  431. {
  432. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  433. PRINT(LCLICK, 'L');
  434. PRINT(RCLICK, 'R');
  435. PRINT(HOVER, 'H');
  436. PRINT(MOVE, 'M');
  437. PRINT(KEYBOARD, 'K');
  438. PRINT(TIME, 'T');
  439. PRINT(GENERAL, 'A');
  440. PRINT(WHEEL, 'W');
  441. PRINT(DOUBLECLICK, 'D');
  442. #undef PRINT
  443. }
  444. else
  445. sbuffer << "inactive";
  446. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  447. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  448. logGlobal->info(sbuffer.str());
  449. for(const CIntObject *child : obj->children)
  450. printInfoAboutIntObject(child, level+1);
  451. }
  452. void removeGUI()
  453. {
  454. // CClient::endGame
  455. GH.curInt = nullptr;
  456. if(GH.topInt())
  457. GH.topInt()->deactivate();
  458. GH.listInt.clear();
  459. GH.objsToBlit.clear();
  460. GH.statusbar = nullptr;
  461. logGlobal->info("Removed GUI.");
  462. LOCPLINT = nullptr;
  463. }
  464. void processCommand(const std::string &message)
  465. {
  466. std::istringstream readed;
  467. readed.str(message);
  468. std::string cn; //command name
  469. readed >> cn;
  470. // Check mantis issue 2292 for details
  471. // if(LOCPLINT && LOCPLINT->cingconsole)
  472. // LOCPLINT->cingconsole->print(message);
  473. if(ermInteractiveMode)
  474. {
  475. if(cn == "exit")
  476. {
  477. ermInteractiveMode = false;
  478. return;
  479. }
  480. else
  481. {
  482. if(CSH->client && CSH->client->erm)
  483. CSH->client->erm->executeUserCommand(message);
  484. std::cout << "erm>";
  485. }
  486. }
  487. else if(message==std::string("die, fool"))
  488. {
  489. exit(EXIT_SUCCESS);
  490. }
  491. else if(cn == "erm")
  492. {
  493. ermInteractiveMode = true;
  494. std::cout << "erm>";
  495. }
  496. else if(cn==std::string("activate"))
  497. {
  498. int what;
  499. readed >> what;
  500. switch (what)
  501. {
  502. case 0:
  503. GH.topInt()->activate();
  504. break;
  505. case 1:
  506. adventureInt->activate();
  507. break;
  508. case 2:
  509. LOCPLINT->castleInt->activate();
  510. break;
  511. }
  512. }
  513. else if(cn=="redraw")
  514. {
  515. GH.totalRedraw();
  516. }
  517. else if(cn=="screen")
  518. {
  519. std::cout << "Screenbuf points to ";
  520. if(screenBuf == screen)
  521. logGlobal->error("screen");
  522. else if(screenBuf == screen2)
  523. logGlobal->error("screen2");
  524. else
  525. logGlobal->error("?!?");
  526. SDL_SaveBMP(screen, "Screen_c.bmp");
  527. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  528. }
  529. else if(cn=="save")
  530. {
  531. if(!CSH->client)
  532. {
  533. std::cout << "Game in not active";
  534. return;
  535. }
  536. std::string fname;
  537. readed >> fname;
  538. CSH->client->save(fname);
  539. }
  540. // else if(cn=="load")
  541. // {
  542. // // TODO: this code should end the running game and manage to call startGame instead
  543. // std::string fname;
  544. // readed >> fname;
  545. // CSH->client->loadGame(fname);
  546. // }
  547. else if(message=="convert txt")
  548. {
  549. std::cout << "Command accepted.\t";
  550. const bfs::path outPath =
  551. VCMIDirs::get().userCachePath() / "extracted";
  552. bfs::create_directories(outPath);
  553. auto extractVector = [=](const std::vector<std::string> & source, const std::string & name)
  554. {
  555. JsonNode data(JsonNode::JsonType::DATA_VECTOR);
  556. size_t index = 0;
  557. for(auto & line : source)
  558. {
  559. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  560. lineNode["text"].String() = line;
  561. lineNode["index"].Integer() = index++;
  562. data.Vector().push_back(lineNode);
  563. }
  564. const bfs::path filePath = outPath / (name + ".json");
  565. bfs::ofstream file(filePath);
  566. file << data.toJson();
  567. };
  568. extractVector(VLC->generaltexth->allTexts, "generalTexts");
  569. extractVector(VLC->generaltexth->jktexts, "jkTexts");
  570. extractVector(VLC->generaltexth->arraytxt, "arrayTexts");
  571. std::cout << "\rExtracting done :)\n";
  572. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  573. }
  574. else if(message=="get config")
  575. {
  576. std::cout << "Command accepted.\t";
  577. const bfs::path outPath =
  578. VCMIDirs::get().userCachePath() / "extracted" / "configuration";
  579. bfs::create_directories(outPath);
  580. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  581. for(auto contentName : contentNames)
  582. {
  583. auto & content = VLC->modh->content[contentName];
  584. auto contentOutPath = outPath / contentName;
  585. bfs::create_directories(contentOutPath);
  586. for(auto & iter : content.modData)
  587. {
  588. const JsonNode & modData = iter.second.modData;
  589. for(auto & nameAndObject : modData.Struct())
  590. {
  591. const JsonNode & object = nameAndObject.second;
  592. std::string name = CModHandler::normalizeIdentifier(object.meta, "core", nameAndObject.first);
  593. boost::algorithm::replace_all(name,":","_");
  594. const bfs::path filePath = contentOutPath / (name + ".json");
  595. bfs::ofstream file(filePath);
  596. file << object.toJson();
  597. }
  598. }
  599. }
  600. std::cout << "\rExtracting done :)\n";
  601. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  602. }
  603. else if(message=="get txt")
  604. {
  605. std::cout << "Command accepted.\t";
  606. const bfs::path outPath =
  607. VCMIDirs::get().userCachePath() / "extracted";
  608. auto list = CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  609. {
  610. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  611. });
  612. for (auto & filename : list)
  613. {
  614. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  615. bfs::create_directories(filePath.parent_path());
  616. bfs::ofstream file(filePath);
  617. auto text = CResourceHandler::get()->load(filename)->readAll();
  618. file.write((char*)text.first.get(), text.second);
  619. }
  620. std::cout << "\rExtracting done :)\n";
  621. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  622. }
  623. else if(cn=="crash")
  624. {
  625. int *ptr = nullptr;
  626. *ptr = 666;
  627. //disaster!
  628. }
  629. else if(cn == "mp" && adventureInt)
  630. {
  631. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  632. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  633. }
  634. else if(cn == "bonuses")
  635. {
  636. bool jsonFormat = (message == "bonuses json");
  637. auto format = [jsonFormat](const BonusList & b) -> std::string
  638. {
  639. if(jsonFormat)
  640. return b.toJsonNode().toJson(true);
  641. std::ostringstream ss;
  642. ss << b;
  643. return ss.str();
  644. };
  645. std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
  646. << format(adventureInt->selection->getBonusList()) << std::endl;
  647. std::cout << "\nInherited bonuses:\n";
  648. TCNodes parents;
  649. adventureInt->selection->getParents(parents);
  650. for(const CBonusSystemNode *parent : parents)
  651. {
  652. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << format(*parent->getAllBonuses(Selector::all, Selector::all)) << std::endl;
  653. }
  654. }
  655. else if(cn == "not dialog")
  656. {
  657. LOCPLINT->showingDialog->setn(false);
  658. }
  659. else if(cn == "gui")
  660. {
  661. for(const IShowActivatable *child : GH.listInt)
  662. {
  663. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  664. printInfoAboutIntObject(obj, 0);
  665. else
  666. std::cout << typeid(*child).name() << std::endl;
  667. }
  668. }
  669. else if(cn=="tell")
  670. {
  671. std::string what;
  672. int id1, id2;
  673. readed >> what >> id1 >> id2;
  674. if(what == "hs")
  675. {
  676. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  677. if(h->type->ID.getNum() == id1)
  678. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  679. std::cout << a->nodeName();
  680. }
  681. }
  682. else if (cn == "set")
  683. {
  684. std::string what, value;
  685. readed >> what;
  686. Settings conf = settings.write["session"][what];
  687. readed >> value;
  688. if (value == "on")
  689. {
  690. conf->Bool() = true;
  691. logGlobal->info("Option %s enabled!", what);
  692. }
  693. else if (value == "off")
  694. {
  695. conf->Bool() = false;
  696. logGlobal->info("Option %s disabled!", what);
  697. }
  698. }
  699. else if(cn == "unlock")
  700. {
  701. std::string mxname;
  702. readed >> mxname;
  703. if(mxname == "pim" && LOCPLINT)
  704. LOCPLINT->pim->unlock();
  705. }
  706. else if(cn == "def2bmp")
  707. {
  708. std::string URI;
  709. readed >> URI;
  710. std::unique_ptr<CAnimation> anim = make_unique<CAnimation>(URI);
  711. anim->preload();
  712. anim->exportBitmaps(VCMIDirs::get().userCachePath() / "extracted");
  713. }
  714. else if(cn == "extract")
  715. {
  716. std::string URI;
  717. readed >> URI;
  718. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  719. {
  720. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  721. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  722. bfs::create_directories(outPath.parent_path());
  723. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  724. outFile.write((char*)data.first.get(), data.second);
  725. }
  726. else
  727. logGlobal->error("File not found!");
  728. }
  729. else if(cn == "setBattleAI")
  730. {
  731. std::string fname;
  732. readed >> fname;
  733. std::cout << "Will try loading that AI to see if it is correct name...\n";
  734. try
  735. {
  736. if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  737. {
  738. Settings neutralAI = settings.write["server"]["neutralAI"];
  739. neutralAI->String() = fname;
  740. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  741. }
  742. }
  743. catch(std::exception &e)
  744. {
  745. logGlobal->warn("Failed opening %s: %s", fname, e.what());
  746. logGlobal->warn("Setting not changes, AI not found or invalid!");
  747. }
  748. }
  749. auto giveTurn = [&](PlayerColor player)
  750. {
  751. YourTurn yt;
  752. yt.player = player;
  753. yt.daysWithoutCastle = CSH->client->getPlayer(player)->daysWithoutCastle;
  754. yt.applyCl(CSH->client);
  755. };
  756. Settings session = settings.write["session"];
  757. if(cn == "autoskip")
  758. {
  759. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  760. }
  761. else if(cn == "gosolo")
  762. {
  763. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  764. if(!CSH->client)
  765. {
  766. std::cout << "Game in not active";
  767. return;
  768. }
  769. PlayerColor color;
  770. if(session["aiSolo"].Bool())
  771. {
  772. for(auto & elem : CSH->client->gameState()->players)
  773. {
  774. if(elem.second.human)
  775. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  776. }
  777. }
  778. else
  779. {
  780. color = LOCPLINT->playerID;
  781. removeGUI();
  782. for(auto & elem : CSH->client->gameState()->players)
  783. {
  784. if(elem.second.human)
  785. {
  786. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  787. logNetwork->info("Player %s will be lead by %s", elem.first, AiToGive);
  788. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  789. }
  790. }
  791. GH.totalRedraw();
  792. giveTurn(color);
  793. }
  794. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  795. }
  796. else if(cn == "controlai")
  797. {
  798. std::string colorName;
  799. readed >> colorName;
  800. boost::to_lower(colorName);
  801. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  802. if(!CSH->client)
  803. {
  804. std::cout << "Game in not active";
  805. return;
  806. }
  807. PlayerColor color;
  808. if(LOCPLINT)
  809. color = LOCPLINT->playerID;
  810. for(auto & elem : CSH->client->gameState()->players)
  811. {
  812. if(elem.second.human || (colorName.length() &&
  813. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  814. {
  815. continue;
  816. }
  817. removeGUI();
  818. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  819. }
  820. GH.totalRedraw();
  821. if(color != PlayerColor::NEUTRAL)
  822. giveTurn(color);
  823. }
  824. // Check mantis issue 2292 for details
  825. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  826. {
  827. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  828. LOCPLINT->cb->sendMessage(message);
  829. }*/
  830. }
  831. //plays intro, ends when intro is over or button has been pressed (handles events)
  832. void playIntro()
  833. {
  834. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, screen, true, true))
  835. {
  836. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, screen, true, true);
  837. }
  838. }
  839. void dispose()
  840. {
  841. if(VLC)
  842. {
  843. delete VLC;
  844. VLC = nullptr;
  845. }
  846. // cleanup, mostly to remove false leaks from analyzer
  847. CResourceHandler::clear();
  848. if(CCS)
  849. {
  850. CCS->musich->release();
  851. CCS->soundh->release();
  852. }
  853. CMessage::dispose();
  854. vstd::clear_pointer(graphics);
  855. if(console)
  856. {
  857. delete console; // should be removed after everything else since used by logging
  858. console = nullptr;
  859. }
  860. }
  861. static bool checkVideoMode(int monitorIndex, int w, int h)
  862. {
  863. //we only check that our desired window size fits on screen
  864. SDL_DisplayMode mode;
  865. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  866. {
  867. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  868. logGlobal->error(SDL_GetError());
  869. return false;
  870. }
  871. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  872. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  873. {
  874. return true;
  875. }
  876. return false;
  877. }
  878. static void cleanupRenderer()
  879. {
  880. screenBuf = nullptr; //it`s a link - just nullify
  881. if(nullptr != screen2)
  882. {
  883. SDL_FreeSurface(screen2);
  884. screen2 = nullptr;
  885. }
  886. if(nullptr != screen)
  887. {
  888. SDL_FreeSurface(screen);
  889. screen = nullptr;
  890. }
  891. if(nullptr != screenTexture)
  892. {
  893. SDL_DestroyTexture(screenTexture);
  894. screenTexture = nullptr;
  895. }
  896. if(nullptr != mainRenderer)
  897. {
  898. SDL_DestroyRenderer(mainRenderer);
  899. mainRenderer = nullptr;
  900. }
  901. if(nullptr != mainWindow)
  902. {
  903. SDL_DestroyWindow(mainWindow);
  904. mainWindow = nullptr;
  905. }
  906. }
  907. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  908. {
  909. // VCMI will only work with 2 or 4 bytes per pixel
  910. vstd::amax(bpp, 16);
  911. vstd::amin(bpp, 32);
  912. if(bpp>16)
  913. bpp = 32;
  914. if(displayIndex < 0)
  915. {
  916. if (mainWindow != nullptr)
  917. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  918. if (displayIndex < 0)
  919. displayIndex = 0;
  920. }
  921. if(!checkVideoMode(displayIndex, w, h))
  922. {
  923. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  924. return false;
  925. }
  926. bool bufOnScreen = (screenBuf == screen);
  927. cleanupRenderer();
  928. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  929. #ifdef VCMI_ANDROID
  930. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN);
  931. #else
  932. if(fullscreen)
  933. {
  934. if(realFullscreen)
  935. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), w, h, SDL_WINDOW_FULLSCREEN);
  936. else //in windowed full-screen mode use desktop resolution
  937. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  938. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  939. }
  940. else
  941. {
  942. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  943. }
  944. #endif
  945. if(nullptr == mainWindow)
  946. {
  947. throw std::runtime_error("Unable to create window\n");
  948. }
  949. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  950. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  951. if(nullptr == mainRenderer)
  952. {
  953. throw std::runtime_error("Unable to create renderer\n");
  954. }
  955. SDL_RendererInfo info;
  956. SDL_GetRendererInfo(mainRenderer, &info);
  957. logGlobal->info("Created renderer %s", info.name);
  958. if(!(fullscreen && realFullscreen))
  959. {
  960. SDL_RenderSetLogicalSize(mainRenderer, w, h);
  961. #ifndef VCMI_ANDROID
  962. // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  963. SDL_RenderSetViewport(mainRenderer, nullptr);
  964. #endif
  965. }
  966. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  967. int bmask = 0xff000000;
  968. int gmask = 0x00ff0000;
  969. int rmask = 0x0000ff00;
  970. int amask = 0x000000ff;
  971. #else
  972. int bmask = 0x000000ff;
  973. int gmask = 0x0000ff00;
  974. int rmask = 0x00ff0000;
  975. int amask = 0xFF000000;
  976. #endif
  977. screen = SDL_CreateRGBSurface(0,w,h,bpp,rmask,gmask,bmask,amask);
  978. if(nullptr == screen)
  979. {
  980. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", w, h, bpp, SDL_GetError());
  981. throw std::runtime_error("Unable to create surface");
  982. }
  983. //No blending for screen itself. Required for proper cursor rendering.
  984. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  985. screenTexture = SDL_CreateTexture(mainRenderer,
  986. SDL_PIXELFORMAT_ARGB8888,
  987. SDL_TEXTUREACCESS_STREAMING,
  988. w, h);
  989. if(nullptr == screenTexture)
  990. {
  991. logGlobal->error("Unable to create screen texture");
  992. logGlobal->error(SDL_GetError());
  993. throw std::runtime_error("Unable to create screen texture");
  994. }
  995. screen2 = CSDL_Ext::copySurface(screen);
  996. if(nullptr == screen2)
  997. {
  998. throw std::runtime_error("Unable to copy surface\n");
  999. }
  1000. screenBuf = bufOnScreen ? screen : screen2;
  1001. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  1002. SDL_RenderClear(mainRenderer);
  1003. SDL_RenderPresent(mainRenderer);
  1004. return true;
  1005. }
  1006. //used only once during initialization
  1007. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  1008. {
  1009. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  1010. {
  1011. throw std::runtime_error("Requested screen resolution is not available\n");
  1012. }
  1013. }
  1014. static void fullScreenChanged()
  1015. {
  1016. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  1017. Settings full = settings.write["video"]["fullscreen"];
  1018. const bool toFullscreen = full->Bool();
  1019. auto bitsPerPixel = screen->format->BitsPerPixel;
  1020. auto w = screen->w;
  1021. auto h = screen->h;
  1022. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  1023. {
  1024. //will return false and report error if video mode is not supported
  1025. return;
  1026. }
  1027. GH.totalRedraw();
  1028. }
  1029. static void handleEvent(SDL_Event & ev)
  1030. {
  1031. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  1032. {
  1033. #ifdef VCMI_ANDROID
  1034. handleQuit(false);
  1035. #else
  1036. handleQuit();
  1037. #endif
  1038. return;
  1039. }
  1040. #ifdef VCMI_ANDROID
  1041. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  1042. {
  1043. handleQuit(true);
  1044. }
  1045. #endif
  1046. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  1047. {
  1048. Settings full = settings.write["video"]["fullscreen"];
  1049. full->Bool() = !full->Bool();
  1050. return;
  1051. }
  1052. else if(ev.type == SDL_USEREVENT)
  1053. {
  1054. switch(ev.user.code)
  1055. {
  1056. case EUserEvent::FORCE_QUIT:
  1057. {
  1058. handleQuit(false);
  1059. return;
  1060. }
  1061. break;
  1062. case EUserEvent::RETURN_TO_MAIN_MENU:
  1063. {
  1064. CSH->endGameplay();
  1065. GH.curInt = CMainMenu::create();
  1066. GH.defActionsDef = 63;
  1067. }
  1068. break;
  1069. case EUserEvent::RESTART_GAME:
  1070. {
  1071. CSH->sendStartGame();
  1072. }
  1073. break;
  1074. case EUserEvent::CAMPAIGN_START_SCENARIO:
  1075. {
  1076. CSH->endGameplay();
  1077. GH.curInt = CMainMenu::create();
  1078. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  1079. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  1080. auto finisher = [=]()
  1081. {
  1082. if(ourCampaign->mapsRemaining.size())
  1083. {
  1084. CMM->openCampaignLobby(ourCampaign);
  1085. }
  1086. };
  1087. if(epilogue.hasPrologEpilog)
  1088. {
  1089. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  1090. }
  1091. else
  1092. {
  1093. finisher();
  1094. }
  1095. }
  1096. break;
  1097. case EUserEvent::RETURN_TO_MENU_LOAD:
  1098. CSH->endGameplay();
  1099. CMainMenu::create();
  1100. GH.defActionsDef = 63;
  1101. CMM->update();
  1102. CMM->menu->switchToTab(vstd::find_pos(CMM->menu->menuNameToEntry, "load"));
  1103. GH.curInt = CMM;
  1104. break;
  1105. case EUserEvent::FULLSCREEN_TOGGLED:
  1106. fullScreenChanged();
  1107. break;
  1108. case EUserEvent::INTERFACE_CHANGED:
  1109. if(LOCPLINT)
  1110. LOCPLINT->updateAmbientSounds();
  1111. break;
  1112. default:
  1113. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  1114. break;
  1115. }
  1116. return;
  1117. }
  1118. else if(ev.type == SDL_WINDOWEVENT)
  1119. {
  1120. switch (ev.window.event) {
  1121. case SDL_WINDOWEVENT_RESTORED:
  1122. fullScreenChanged();
  1123. break;
  1124. }
  1125. return;
  1126. }
  1127. {
  1128. boost::unique_lock<boost::mutex> lock(eventsM);
  1129. events.push(ev);
  1130. }
  1131. }
  1132. static void mainLoop()
  1133. {
  1134. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  1135. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::FULLSCREEN_TOGGLED); });
  1136. inGuiThread.reset(new bool(true));
  1137. GH.mainFPSmng->init();
  1138. while(1) //main SDL events loop
  1139. {
  1140. SDL_Event ev;
  1141. while(1 == SDL_PollEvent(&ev))
  1142. {
  1143. handleEvent(ev);
  1144. }
  1145. CSH->applyPacksOnLobbyScreen();
  1146. GH.renderFrame();
  1147. }
  1148. }
  1149. void handleQuit(bool ask)
  1150. {
  1151. auto quitApplication = []()
  1152. {
  1153. if(CSH->client)
  1154. CSH->endGameplay();
  1155. dispose();
  1156. vstd::clear_pointer(console);
  1157. boost::this_thread::sleep(boost::posix_time::milliseconds(750));
  1158. if(!settings["session"]["headless"].Bool())
  1159. {
  1160. cleanupRenderer();
  1161. SDL_Quit();
  1162. }
  1163. std::cout << "Ending...\n";
  1164. exit(0);
  1165. };
  1166. if(CSH->client && LOCPLINT && ask)
  1167. {
  1168. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  1169. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, 0);
  1170. }
  1171. else
  1172. {
  1173. quitApplication();
  1174. }
  1175. }