CMT.cpp 45 KB

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