CMT.cpp 44 KB

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