CMT.cpp 41 KB

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