CMT.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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 <boost/program_options.hpp>
  14. #include <vcmi/scripting/Service.h>
  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/ScriptHandler.h"
  47. #include "../lib/CTownHandler.h"
  48. #include "../lib/CArtHandler.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 "gui/NotificationHandler.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_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. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  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().userLogsPath() / "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. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  327. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  328. }
  329. CCS = new CClientState();
  330. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  331. CSH = new CServerHandler();
  332. // Initialize video
  333. #ifdef DISABLE_VIDEO
  334. CCS->videoh = new CEmptyVideoPlayer();
  335. #else
  336. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  337. CCS->videoh = new CVideoPlayer();
  338. else
  339. CCS->videoh = new CEmptyVideoPlayer();
  340. #endif
  341. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  342. if(!settings["session"]["headless"].Bool())
  343. {
  344. //initializing audio
  345. CCS->soundh = new CSoundHandler();
  346. CCS->soundh->init();
  347. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  348. CCS->musich = new CMusicHandler();
  349. CCS->musich->init();
  350. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  351. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  352. }
  353. #ifdef __APPLE__
  354. // Ctrl+click should be treated as a right click on Mac OS X
  355. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  356. #endif
  357. #ifndef VCMI_NO_THREADED_LOAD
  358. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  359. boost::thread loading(init);
  360. #else
  361. init();
  362. #endif
  363. if(!settings["session"]["headless"].Bool())
  364. {
  365. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  366. playIntro();
  367. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  368. SDL_RenderClear(mainRenderer);
  369. SDL_RenderPresent(mainRenderer);
  370. }
  371. #ifndef VCMI_NO_THREADED_LOAD
  372. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  373. {
  374. CAndroidVMHelper vmHelper;
  375. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  376. #endif // ANDROID
  377. loading.join();
  378. #ifdef VCMI_ANDROID
  379. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  380. }
  381. #endif // ANDROID
  382. #endif // THREADED
  383. if(!settings["session"]["headless"].Bool())
  384. {
  385. pomtime.getDiff();
  386. CCS->curh = new CCursorHandler();
  387. graphics = new Graphics(); // should be before curh->init()
  388. CCS->curh->initCursor();
  389. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  390. pomtime.getDiff();
  391. graphics->load();//must be after Content loading but should be in main thread
  392. logGlobal->info("Main graphics: %d ms", pomtime.getDiff());
  393. CMessage::init();
  394. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  395. CCS->curh->show();
  396. }
  397. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  398. session["autoSkip"].Bool() = vm.count("autoSkip");
  399. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  400. session["aiSolo"].Bool() = false;
  401. if(vm.count("testmap"))
  402. {
  403. session["testmap"].String() = vm["testmap"].as<std::string>();
  404. session["onlyai"].Bool() = true;
  405. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  406. }
  407. else if(vm.count("testsave"))
  408. {
  409. session["testsave"].String() = vm["testsave"].as<std::string>();
  410. session["onlyai"].Bool() = true;
  411. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  412. }
  413. else
  414. {
  415. GH.curInt = CMainMenu::create().get();
  416. }
  417. if(!settings["session"]["headless"].Bool())
  418. {
  419. mainLoop();
  420. }
  421. else
  422. {
  423. while(true)
  424. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  425. }
  426. return 0;
  427. }
  428. void printInfoAboutIntObject(const CIntObject *obj, int level)
  429. {
  430. std::stringstream sbuffer;
  431. sbuffer << std::string(level, '\t');
  432. sbuffer << typeid(*obj).name() << " *** ";
  433. if (obj->active)
  434. {
  435. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  436. PRINT(LCLICK, 'L');
  437. PRINT(RCLICK, 'R');
  438. PRINT(HOVER, 'H');
  439. PRINT(MOVE, 'M');
  440. PRINT(KEYBOARD, 'K');
  441. PRINT(TIME, 'T');
  442. PRINT(GENERAL, 'A');
  443. PRINT(WHEEL, 'W');
  444. PRINT(DOUBLECLICK, 'D');
  445. #undef PRINT
  446. }
  447. else
  448. sbuffer << "inactive";
  449. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  450. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  451. logGlobal->info(sbuffer.str());
  452. for(const CIntObject *child : obj->children)
  453. printInfoAboutIntObject(child, level+1);
  454. }
  455. void removeGUI()
  456. {
  457. // CClient::endGame
  458. GH.curInt = nullptr;
  459. if(GH.topInt())
  460. GH.topInt()->deactivate();
  461. GH.listInt.clear();
  462. GH.objsToBlit.clear();
  463. GH.statusbar = nullptr;
  464. logGlobal->info("Removed GUI.");
  465. LOCPLINT = nullptr;
  466. }
  467. void processCommand(const std::string &message)
  468. {
  469. std::istringstream readed;
  470. readed.str(message);
  471. std::string cn; //command name
  472. readed >> cn;
  473. // Check mantis issue 2292 for details
  474. // if(LOCPLINT && LOCPLINT->cingconsole)
  475. // LOCPLINT->cingconsole->print(message);
  476. if(message==std::string("die, fool"))
  477. {
  478. exit(EXIT_SUCCESS);
  479. }
  480. else if(cn==std::string("activate"))
  481. {
  482. int what;
  483. readed >> what;
  484. switch (what)
  485. {
  486. case 0:
  487. GH.topInt()->activate();
  488. break;
  489. case 1:
  490. adventureInt->activate();
  491. break;
  492. case 2:
  493. LOCPLINT->castleInt->activate();
  494. break;
  495. }
  496. }
  497. else if(cn=="redraw")
  498. {
  499. GH.totalRedraw();
  500. }
  501. else if(cn=="screen")
  502. {
  503. std::cout << "Screenbuf points to ";
  504. if(screenBuf == screen)
  505. logGlobal->error("screen");
  506. else if(screenBuf == screen2)
  507. logGlobal->error("screen2");
  508. else
  509. logGlobal->error("?!?");
  510. SDL_SaveBMP(screen, "Screen_c.bmp");
  511. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  512. }
  513. else if(cn=="save")
  514. {
  515. if(!CSH->client)
  516. {
  517. std::cout << "Game in not active";
  518. return;
  519. }
  520. std::string fname;
  521. readed >> fname;
  522. CSH->client->save(fname);
  523. }
  524. // else if(cn=="load")
  525. // {
  526. // // TODO: this code should end the running game and manage to call startGame instead
  527. // std::string fname;
  528. // readed >> fname;
  529. // CSH->client->loadGame(fname);
  530. // }
  531. else if(message=="convert txt")
  532. {
  533. std::cout << "Command accepted.\t";
  534. const bfs::path outPath =
  535. VCMIDirs::get().userCachePath() / "extracted";
  536. bfs::create_directories(outPath);
  537. auto extractVector = [=](const std::vector<std::string> & source, const std::string & name)
  538. {
  539. JsonNode data(JsonNode::JsonType::DATA_VECTOR);
  540. size_t index = 0;
  541. for(auto & line : source)
  542. {
  543. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  544. lineNode["text"].String() = line;
  545. lineNode["index"].Integer() = index++;
  546. data.Vector().push_back(lineNode);
  547. }
  548. const bfs::path filePath = outPath / (name + ".json");
  549. bfs::ofstream file(filePath);
  550. file << data.toJson();
  551. };
  552. extractVector(VLC->generaltexth->allTexts, "generalTexts");
  553. extractVector(VLC->generaltexth->jktexts, "jkTexts");
  554. extractVector(VLC->generaltexth->arraytxt, "arrayTexts");
  555. std::cout << "\rExtracting done :)\n";
  556. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  557. }
  558. else if(message=="get config")
  559. {
  560. std::cout << "Command accepted.\t";
  561. const bfs::path outPath =
  562. VCMIDirs::get().userCachePath() / "extracted" / "configuration";
  563. bfs::create_directories(outPath);
  564. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  565. for(auto contentName : contentNames)
  566. {
  567. auto & content = (*VLC->modh->content)[contentName];
  568. auto contentOutPath = outPath / contentName;
  569. bfs::create_directories(contentOutPath);
  570. for(auto & iter : content.modData)
  571. {
  572. const JsonNode & modData = iter.second.modData;
  573. for(auto & nameAndObject : modData.Struct())
  574. {
  575. const JsonNode & object = nameAndObject.second;
  576. std::string name = CModHandler::normalizeIdentifier(object.meta, "core", nameAndObject.first);
  577. boost::algorithm::replace_all(name,":","_");
  578. const bfs::path filePath = contentOutPath / (name + ".json");
  579. bfs::ofstream file(filePath);
  580. file << object.toJson();
  581. }
  582. }
  583. }
  584. std::cout << "\rExtracting done :)\n";
  585. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  586. }
  587. #if SCRIPTING_ENABLED
  588. else if(message=="get scripts")
  589. {
  590. std::cout << "Command accepted.\t";
  591. const bfs::path outPath =
  592. VCMIDirs::get().userCachePath() / "extracted" / "scripts";
  593. bfs::create_directories(outPath);
  594. for(auto & kv : VLC->scriptHandler->objects)
  595. {
  596. std::string name = kv.first;
  597. boost::algorithm::replace_all(name,":","_");
  598. const scripting::ScriptImpl * script = kv.second.get();
  599. bfs::path filePath = outPath / (name + ".lua");
  600. bfs::ofstream file(filePath);
  601. file << script->getSource();
  602. }
  603. std::cout << "\rExtracting done :)\n";
  604. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  605. }
  606. #endif
  607. else if(message=="get txt")
  608. {
  609. std::cout << "Command accepted.\t";
  610. const bfs::path outPath =
  611. VCMIDirs::get().userCachePath() / "extracted";
  612. auto list = CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  613. {
  614. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  615. });
  616. for (auto & filename : list)
  617. {
  618. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  619. bfs::create_directories(filePath.parent_path());
  620. bfs::ofstream file(filePath);
  621. auto text = CResourceHandler::get()->load(filename)->readAll();
  622. file.write((char*)text.first.get(), text.second);
  623. }
  624. std::cout << "\rExtracting done :)\n";
  625. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  626. }
  627. else if(cn=="crash")
  628. {
  629. int *ptr = nullptr;
  630. *ptr = 666;
  631. //disaster!
  632. }
  633. else if(cn == "mp" && adventureInt)
  634. {
  635. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  636. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  637. }
  638. else if(cn == "bonuses")
  639. {
  640. bool jsonFormat = (message == "bonuses json");
  641. auto format = [jsonFormat](const BonusList & b) -> std::string
  642. {
  643. if(jsonFormat)
  644. return b.toJsonNode().toJson(true);
  645. std::ostringstream ss;
  646. ss << b;
  647. return ss.str();
  648. };
  649. std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
  650. << format(adventureInt->selection->getBonusList()) << std::endl;
  651. std::cout << "\nInherited bonuses:\n";
  652. TCNodes parents;
  653. adventureInt->selection->getParents(parents);
  654. for(const CBonusSystemNode *parent : parents)
  655. {
  656. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << format(*parent->getAllBonuses(Selector::all, Selector::all)) << std::endl;
  657. }
  658. }
  659. else if(cn == "not dialog")
  660. {
  661. LOCPLINT->showingDialog->setn(false);
  662. }
  663. else if(cn == "gui")
  664. {
  665. for(auto & child : GH.listInt)
  666. {
  667. const auto childPtr = child.get();
  668. if(const CIntObject * obj = dynamic_cast<const CIntObject *>(childPtr))
  669. printInfoAboutIntObject(obj, 0);
  670. else
  671. std::cout << typeid(childPtr).name() << std::endl;
  672. }
  673. }
  674. else if(cn=="tell")
  675. {
  676. std::string what;
  677. int id1, id2;
  678. readed >> what >> id1 >> id2;
  679. if(what == "hs")
  680. {
  681. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  682. if(h->type->ID.getNum() == id1)
  683. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  684. std::cout << a->nodeName();
  685. }
  686. }
  687. else if (cn == "set")
  688. {
  689. std::string what, value;
  690. readed >> what;
  691. Settings conf = settings.write["session"][what];
  692. readed >> value;
  693. if (value == "on")
  694. {
  695. conf->Bool() = true;
  696. logGlobal->info("Option %s enabled!", what);
  697. }
  698. else if (value == "off")
  699. {
  700. conf->Bool() = false;
  701. logGlobal->info("Option %s disabled!", what);
  702. }
  703. }
  704. else if(cn == "unlock")
  705. {
  706. std::string mxname;
  707. readed >> mxname;
  708. if(mxname == "pim" && LOCPLINT)
  709. LOCPLINT->pim->unlock();
  710. }
  711. else if(cn == "def2bmp")
  712. {
  713. std::string URI;
  714. readed >> URI;
  715. std::unique_ptr<CAnimation> anim = make_unique<CAnimation>(URI);
  716. anim->preload();
  717. anim->exportBitmaps(VCMIDirs::get().userCachePath() / "extracted");
  718. }
  719. else if(cn == "extract")
  720. {
  721. std::string URI;
  722. readed >> URI;
  723. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  724. {
  725. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  726. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  727. bfs::create_directories(outPath.parent_path());
  728. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  729. outFile.write((char*)data.first.get(), data.second);
  730. }
  731. else
  732. logGlobal->error("File not found!");
  733. }
  734. else if(cn == "setBattleAI")
  735. {
  736. std::string fname;
  737. readed >> fname;
  738. std::cout << "Will try loading that AI to see if it is correct name...\n";
  739. try
  740. {
  741. 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
  742. {
  743. Settings neutralAI = settings.write["server"]["neutralAI"];
  744. neutralAI->String() = fname;
  745. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  746. }
  747. }
  748. catch(std::exception &e)
  749. {
  750. logGlobal->warn("Failed opening %s: %s", fname, e.what());
  751. logGlobal->warn("Setting not changes, AI not found or invalid!");
  752. }
  753. }
  754. auto giveTurn = [&](PlayerColor player)
  755. {
  756. YourTurn yt;
  757. yt.player = player;
  758. yt.daysWithoutCastle = CSH->client->getPlayerState(player)->daysWithoutCastle;
  759. yt.applyCl(CSH->client);
  760. };
  761. Settings session = settings.write["session"];
  762. if(cn == "autoskip")
  763. {
  764. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  765. }
  766. else if(cn == "gosolo")
  767. {
  768. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  769. if(!CSH->client)
  770. {
  771. std::cout << "Game in not active";
  772. return;
  773. }
  774. PlayerColor color;
  775. if(session["aiSolo"].Bool())
  776. {
  777. for(auto & elem : CSH->client->gameState()->players)
  778. {
  779. if(elem.second.human)
  780. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  781. }
  782. }
  783. else
  784. {
  785. color = LOCPLINT->playerID;
  786. removeGUI();
  787. for(auto & elem : CSH->client->gameState()->players)
  788. {
  789. if(elem.second.human)
  790. {
  791. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  792. logNetwork->info("Player %s will be lead by %s", elem.first, AiToGive);
  793. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  794. }
  795. }
  796. GH.totalRedraw();
  797. giveTurn(color);
  798. }
  799. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  800. }
  801. else if(cn == "controlai")
  802. {
  803. std::string colorName;
  804. readed >> colorName;
  805. boost::to_lower(colorName);
  806. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  807. if(!CSH->client)
  808. {
  809. std::cout << "Game in not active";
  810. return;
  811. }
  812. PlayerColor color;
  813. if(LOCPLINT)
  814. color = LOCPLINT->playerID;
  815. for(auto & elem : CSH->client->gameState()->players)
  816. {
  817. if(elem.second.human || (colorName.length() &&
  818. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  819. {
  820. continue;
  821. }
  822. removeGUI();
  823. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  824. }
  825. GH.totalRedraw();
  826. if(color != PlayerColor::NEUTRAL)
  827. giveTurn(color);
  828. }
  829. // Check mantis issue 2292 for details
  830. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  831. {
  832. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  833. LOCPLINT->cb->sendMessage(message);
  834. }*/
  835. }
  836. //plays intro, ends when intro is over or button has been pressed (handles events)
  837. void playIntro()
  838. {
  839. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  840. {
  841. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  842. }
  843. }
  844. static bool checkVideoMode(int monitorIndex, int w, int h)
  845. {
  846. //we only check that our desired window size fits on screen
  847. SDL_DisplayMode mode;
  848. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  849. {
  850. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  851. logGlobal->error(SDL_GetError());
  852. return false;
  853. }
  854. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  855. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  856. {
  857. return true;
  858. }
  859. return false;
  860. }
  861. static void cleanupRenderer()
  862. {
  863. screenBuf = nullptr; //it`s a link - just nullify
  864. if(nullptr != screen2)
  865. {
  866. SDL_FreeSurface(screen2);
  867. screen2 = nullptr;
  868. }
  869. if(nullptr != screen)
  870. {
  871. SDL_FreeSurface(screen);
  872. screen = nullptr;
  873. }
  874. if(nullptr != screenTexture)
  875. {
  876. SDL_DestroyTexture(screenTexture);
  877. screenTexture = nullptr;
  878. }
  879. }
  880. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  881. {
  882. // VCMI will only work with 2 or 4 bytes per pixel
  883. vstd::amax(bpp, 16);
  884. vstd::amin(bpp, 32);
  885. if(bpp>16)
  886. bpp = 32;
  887. if(displayIndex < 0)
  888. {
  889. if (mainWindow != nullptr)
  890. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  891. if (displayIndex < 0)
  892. displayIndex = 0;
  893. }
  894. if(!checkVideoMode(displayIndex, w, h))
  895. {
  896. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  897. return false;
  898. }
  899. bool bufOnScreen = (screenBuf == screen);
  900. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  901. /* match best rendering resolution */
  902. int renderWidth = 0, renderHeight = 0;
  903. auto aspectRatio = (float)w / (float)h;
  904. auto minDiff = 10.f;
  905. for (const auto& pair : conf.guiOptions)
  906. {
  907. int pWidth, pHeight;
  908. std::tie(pWidth, pHeight) = pair.first;
  909. /* filter out resolution which is larger than window */
  910. if (pWidth > w || pHeight > h)
  911. {
  912. continue;
  913. }
  914. auto ratio = (float)pWidth / (float)pHeight;
  915. auto diff = fabs(aspectRatio - ratio);
  916. /* select closest aspect ratio */
  917. if (diff < minDiff)
  918. {
  919. renderWidth = pWidth;
  920. renderHeight = pHeight;
  921. minDiff = diff;
  922. }
  923. /* select largest resolution meets prior conditions.
  924. * since there are resolutions like 1366x768(not exactly 16:9), a deviation of 0.005 is allowed. */
  925. else if (fabs(diff - minDiff) < 0.005f && pWidth > renderWidth)
  926. {
  927. renderWidth = pWidth;
  928. renderHeight = pHeight;
  929. }
  930. }
  931. if (renderWidth == 0)
  932. {
  933. // no matching resolution for upscaling - complain & fallback to default resolution.
  934. logGlobal->error("Failed to match rendering resolution for %dx%d!", w, h);
  935. Settings newRes = settings.write["video"]["screenRes"];
  936. std::tie(w, h) = conf.guiOptions.begin()->first;
  937. newRes["width"].Float() = w;
  938. newRes["height"].Float() = h;
  939. conf.SetResolution(w, h);
  940. logGlobal->error("Falling back to %dx%d", w, h);
  941. renderWidth = w;
  942. renderHeight = h;
  943. }
  944. else
  945. {
  946. logGlobal->info("Set logical rendering resolution to %dx%d", renderWidth, renderHeight);
  947. }
  948. cleanupRenderer();
  949. if(nullptr == mainWindow)
  950. {
  951. #ifdef VCMI_ANDROID
  952. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN);
  953. // 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
  954. // 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
  955. SDL_Rect screenRect;
  956. if(SDL_GetDisplayBounds(0, &screenRect) == 0)
  957. {
  958. int screenWidth, screenHeight;
  959. double aspect;
  960. screenWidth = screenRect.w;
  961. screenHeight = screenRect.h;
  962. aspect = (double)screenWidth / (double)screenHeight;
  963. logGlobal->info("Screen size and aspect ration: %dx%d (%lf)", screenWidth, screenHeight, aspect);
  964. if((double)w / aspect > (double)h)
  965. {
  966. h = (int)round((double)w / aspect);
  967. }
  968. else
  969. {
  970. w = (int)round((double)h * aspect);
  971. }
  972. logGlobal->info("Changing logical screen size to %dx%d", w, h);
  973. }
  974. else
  975. {
  976. logGlobal->error("Can't fix aspect ratio for screen");
  977. }
  978. #else
  979. if(fullscreen)
  980. {
  981. if(realFullscreen)
  982. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), renderWidth, renderHeight, SDL_WINDOW_FULLSCREEN);
  983. else //in windowed full-screen mode use desktop resolution
  984. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  985. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  986. }
  987. else
  988. {
  989. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  990. }
  991. #endif
  992. if(nullptr == mainWindow)
  993. {
  994. throw std::runtime_error("Unable to create window\n");
  995. }
  996. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  997. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  998. if(nullptr == mainRenderer)
  999. {
  1000. throw std::runtime_error("Unable to create renderer\n");
  1001. }
  1002. SDL_RendererInfo info;
  1003. SDL_GetRendererInfo(mainRenderer, &info);
  1004. logGlobal->info("Created renderer %s", info.name);
  1005. }
  1006. else
  1007. {
  1008. #ifndef VCMI_ANDROID
  1009. if(fullscreen)
  1010. {
  1011. if(realFullscreen)
  1012. {
  1013. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  1014. SDL_DisplayMode mode;
  1015. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  1016. mode.w = renderWidth;
  1017. mode.h = renderHeight;
  1018. SDL_SetWindowDisplayMode(mainWindow, &mode);
  1019. }
  1020. else
  1021. {
  1022. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  1023. }
  1024. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  1025. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1026. }
  1027. else
  1028. {
  1029. SDL_SetWindowFullscreen(mainWindow, 0);
  1030. SDL_SetWindowSize(mainWindow, w, h);
  1031. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  1032. }
  1033. #endif
  1034. }
  1035. if(!(fullscreen && realFullscreen))
  1036. {
  1037. SDL_RenderSetLogicalSize(mainRenderer, renderWidth, renderHeight);
  1038. //following line is bugged not only on android, do not re-enable without checking
  1039. //#ifndef VCMI_ANDROID
  1040. // // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  1041. // SDL_RenderSetViewport(mainRenderer, nullptr);
  1042. //#endif
  1043. }
  1044. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  1045. int bmask = 0xff000000;
  1046. int gmask = 0x00ff0000;
  1047. int rmask = 0x0000ff00;
  1048. int amask = 0x000000ff;
  1049. #else
  1050. int bmask = 0x000000ff;
  1051. int gmask = 0x0000ff00;
  1052. int rmask = 0x00ff0000;
  1053. int amask = 0xFF000000;
  1054. #endif
  1055. screen = SDL_CreateRGBSurface(0,renderWidth,renderHeight,bpp,rmask,gmask,bmask,amask);
  1056. if(nullptr == screen)
  1057. {
  1058. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", renderWidth, renderHeight, bpp, SDL_GetError());
  1059. throw std::runtime_error("Unable to create surface");
  1060. }
  1061. //No blending for screen itself. Required for proper cursor rendering.
  1062. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  1063. screenTexture = SDL_CreateTexture(mainRenderer,
  1064. SDL_PIXELFORMAT_ARGB8888,
  1065. SDL_TEXTUREACCESS_STREAMING,
  1066. renderWidth, renderHeight);
  1067. if(nullptr == screenTexture)
  1068. {
  1069. logGlobal->error("Unable to create screen texture");
  1070. logGlobal->error(SDL_GetError());
  1071. throw std::runtime_error("Unable to create screen texture");
  1072. }
  1073. screen2 = CSDL_Ext::copySurface(screen);
  1074. if(nullptr == screen2)
  1075. {
  1076. throw std::runtime_error("Unable to copy surface\n");
  1077. }
  1078. screenBuf = bufOnScreen ? screen : screen2;
  1079. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  1080. SDL_RenderClear(mainRenderer);
  1081. SDL_RenderPresent(mainRenderer);
  1082. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1083. {
  1084. NotificationHandler::init(mainWindow);
  1085. }
  1086. return true;
  1087. }
  1088. //used only once during initialization
  1089. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  1090. {
  1091. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  1092. {
  1093. throw std::runtime_error("Requested screen resolution is not available\n");
  1094. }
  1095. }
  1096. static void fullScreenChanged()
  1097. {
  1098. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  1099. Settings full = settings.write["video"]["fullscreen"];
  1100. const bool toFullscreen = full->Bool();
  1101. auto bitsPerPixel = screen->format->BitsPerPixel;
  1102. auto w = screen->w;
  1103. auto h = screen->h;
  1104. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  1105. {
  1106. //will return false and report error if video mode is not supported
  1107. return;
  1108. }
  1109. GH.totalRedraw();
  1110. }
  1111. static void handleEvent(SDL_Event & ev)
  1112. {
  1113. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  1114. {
  1115. #ifdef VCMI_ANDROID
  1116. handleQuit(false);
  1117. #else
  1118. handleQuit();
  1119. #endif
  1120. return;
  1121. }
  1122. #ifdef VCMI_ANDROID
  1123. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  1124. {
  1125. handleQuit(true);
  1126. }
  1127. #endif
  1128. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  1129. {
  1130. Settings full = settings.write["video"]["fullscreen"];
  1131. full->Bool() = !full->Bool();
  1132. return;
  1133. }
  1134. else if(ev.type == SDL_USEREVENT)
  1135. {
  1136. switch(ev.user.code)
  1137. {
  1138. case EUserEvent::FORCE_QUIT:
  1139. {
  1140. handleQuit(false);
  1141. return;
  1142. }
  1143. break;
  1144. case EUserEvent::RETURN_TO_MAIN_MENU:
  1145. {
  1146. CSH->endGameplay();
  1147. GH.defActionsDef = 63;
  1148. CMM->menu->switchToTab("main");
  1149. }
  1150. break;
  1151. case EUserEvent::RESTART_GAME:
  1152. {
  1153. CSH->sendStartGame();
  1154. }
  1155. break;
  1156. case EUserEvent::CAMPAIGN_START_SCENARIO:
  1157. {
  1158. CSH->campaignServerRestartLock.set(true);
  1159. CSH->endGameplay();
  1160. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  1161. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  1162. auto finisher = [=]()
  1163. {
  1164. if(ourCampaign->mapsRemaining.size())
  1165. {
  1166. CMM->openCampaignLobby(ourCampaign);
  1167. }
  1168. };
  1169. if(epilogue.hasPrologEpilog)
  1170. {
  1171. GH.pushIntT<CPrologEpilogVideo>(epilogue, finisher);
  1172. }
  1173. else
  1174. {
  1175. CSH->campaignServerRestartLock.waitUntil(false);
  1176. finisher();
  1177. }
  1178. }
  1179. break;
  1180. case EUserEvent::RETURN_TO_MENU_LOAD:
  1181. CSH->endGameplay();
  1182. GH.defActionsDef = 63;
  1183. CMM->menu->switchToTab("load");
  1184. break;
  1185. case EUserEvent::FULLSCREEN_TOGGLED:
  1186. fullScreenChanged();
  1187. break;
  1188. case EUserEvent::INTERFACE_CHANGED:
  1189. if(LOCPLINT)
  1190. LOCPLINT->updateAmbientSounds();
  1191. break;
  1192. default:
  1193. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  1194. break;
  1195. }
  1196. return;
  1197. }
  1198. else if(ev.type == SDL_WINDOWEVENT)
  1199. {
  1200. switch (ev.window.event) {
  1201. case SDL_WINDOWEVENT_RESTORED:
  1202. fullScreenChanged();
  1203. break;
  1204. }
  1205. return;
  1206. }
  1207. else if(ev.type == SDL_SYSWMEVENT)
  1208. {
  1209. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1210. {
  1211. NotificationHandler::handleSdlEvent(ev);
  1212. }
  1213. }
  1214. //preprocessing
  1215. if(ev.type == SDL_MOUSEMOTION)
  1216. {
  1217. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  1218. }
  1219. {
  1220. boost::unique_lock<boost::mutex> lock(eventsM);
  1221. SDLEventsQueue.push(ev);
  1222. }
  1223. }
  1224. static void mainLoop()
  1225. {
  1226. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  1227. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::FULLSCREEN_TOGGLED); });
  1228. inGuiThread.reset(new bool(true));
  1229. GH.mainFPSmng->init();
  1230. while(1) //main SDL events loop
  1231. {
  1232. SDL_Event ev;
  1233. while(1 == SDL_PollEvent(&ev))
  1234. {
  1235. handleEvent(ev);
  1236. }
  1237. CSH->applyPacksOnLobbyScreen();
  1238. GH.renderFrame();
  1239. }
  1240. }
  1241. void handleQuit(bool ask)
  1242. {
  1243. auto quitApplication = []()
  1244. {
  1245. if(!settings["session"]["headless"].Bool())
  1246. {
  1247. if(CSH->client)
  1248. CSH->endGameplay();
  1249. }
  1250. GH.listInt.clear();
  1251. GH.objsToBlit.clear();
  1252. CMM.reset();
  1253. if(!settings["session"]["headless"].Bool())
  1254. {
  1255. // cleanup, mostly to remove false leaks from analyzer
  1256. if(CCS)
  1257. {
  1258. CCS->musich->release();
  1259. CCS->soundh->release();
  1260. vstd::clear_pointer(CCS);
  1261. }
  1262. CMessage::dispose();
  1263. vstd::clear_pointer(graphics);
  1264. }
  1265. vstd::clear_pointer(VLC);
  1266. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  1267. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  1268. if(!settings["session"]["headless"].Bool())
  1269. {
  1270. if(settings["general"]["notifications"].Bool())
  1271. {
  1272. NotificationHandler::destroy();
  1273. }
  1274. cleanupRenderer();
  1275. if(nullptr != mainRenderer)
  1276. {
  1277. SDL_DestroyRenderer(mainRenderer);
  1278. mainRenderer = nullptr;
  1279. }
  1280. if(nullptr != mainWindow)
  1281. {
  1282. SDL_DestroyWindow(mainWindow);
  1283. mainWindow = nullptr;
  1284. }
  1285. SDL_Quit();
  1286. }
  1287. if(logConfig != nullptr)
  1288. {
  1289. logConfig->deconfigure();
  1290. delete logConfig;
  1291. logConfig = nullptr;
  1292. }
  1293. std::cout << "Ending...\n";
  1294. exit(0);
  1295. };
  1296. if(CSH->client && LOCPLINT && ask)
  1297. {
  1298. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  1299. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, nullptr);
  1300. }
  1301. else
  1302. {
  1303. quitApplication();
  1304. }
  1305. }