CMT.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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 "CGameInfo.h"
  14. #include "mainmenu/CMainMenu.h"
  15. #include "lobby/CSelectionBase.h"
  16. #include "windows/CCastleInterface.h"
  17. #include "gui/CursorHandler.h"
  18. #include "CPlayerInterface.h"
  19. #include "CVideoHandler.h"
  20. #include "CMusicHandler.h"
  21. #include "Client.h"
  22. #include "gui/CGuiHandler.h"
  23. #include "CServerHandler.h"
  24. #include "gui/NotificationHandler.h"
  25. #include "ClientCommandManager.h"
  26. #include "windows/CMessage.h"
  27. #include "renderSDL/SDL_Extensions.h"
  28. #include "../lib/filesystem/Filesystem.h"
  29. #include "../lib/filesystem/FileStream.h"
  30. #include "../lib/CConsoleHandler.h"
  31. #include "../lib/CGameState.h"
  32. #include "../lib/CBuildingHandler.h"
  33. #include "../CCallback.h"
  34. #include "../lib/CHeroHandler.h"
  35. #include "../lib/spells/CSpellHandler.h"
  36. #include "../lib/CGeneralTextHandler.h"
  37. #include "../lib/serializer/BinaryDeserializer.h"
  38. #include "../lib/serializer/BinarySerializer.h"
  39. #include "../lib/VCMIDirs.h"
  40. #include "../lib/NetPacks.h"
  41. #include "../lib/CModHandler.h"
  42. #include "../lib/CTownHandler.h"
  43. #include "../lib/logging/CBasicLogConfigurator.h"
  44. #include "../lib/CPlayerState.h"
  45. #include "../lib/serializer/Connection.h"
  46. #include <boost/asio.hpp>
  47. #include <boost/program_options.hpp>
  48. #include "mainmenu/CPrologEpilogVideo.h"
  49. #include <vstd/StringUtils.h>
  50. #include <SDL.h>
  51. #ifdef VCMI_WINDOWS
  52. #include <SDL_syswm.h>
  53. #endif
  54. #ifdef VCMI_ANDROID
  55. #include "../lib/CAndroidVMHelper.h"
  56. #endif
  57. #include "CMT.h"
  58. #if __MINGW32__
  59. #undef main
  60. #endif
  61. namespace po = boost::program_options;
  62. namespace po_style = boost::program_options::command_line_style;
  63. namespace bfs = boost::filesystem;
  64. std::string NAME_AFFIX = "client";
  65. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  66. CGuiHandler GH;
  67. int preferredDriverIndex = -1;
  68. SDL_Window * mainWindow = nullptr;
  69. SDL_Renderer * mainRenderer = nullptr;
  70. SDL_Texture * screenTexture = nullptr;
  71. extern boost::thread_specific_ptr<bool> inGuiThread;
  72. SDL_Surface *screen = nullptr, //main screen surface
  73. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  74. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  75. std::queue<SDL_Event> SDLEventsQueue;
  76. boost::mutex eventsM;
  77. static po::variables_map vm;
  78. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  79. #ifndef VCMI_IOS
  80. void processCommand(const std::string &message);
  81. #endif
  82. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  83. void playIntro();
  84. static void mainLoop();
  85. static CBasicLogConfigurator *logConfig;
  86. #ifndef VCMI_WINDOWS
  87. #ifndef _GNU_SOURCE
  88. #define _GNU_SOURCE
  89. #endif
  90. #include <getopt.h>
  91. #endif
  92. void init()
  93. {
  94. CStopWatch tmh;
  95. loadDLLClasses();
  96. const_cast<CGameInfo*>(CGI)->setFromLib();
  97. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  98. }
  99. static void prog_version()
  100. {
  101. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  102. std::cout << VCMIDirs::get().genHelpString();
  103. }
  104. static void prog_help(const po::options_description &opts)
  105. {
  106. auto time = std::time(0);
  107. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  108. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  109. printf("This is free software; see the source for copying conditions. There is NO\n");
  110. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  111. printf("\n");
  112. std::cout << opts;
  113. }
  114. static void SDLLogCallback(void* userdata,
  115. int category,
  116. SDL_LogPriority priority,
  117. const char* message)
  118. {
  119. //todo: convert SDL log priority to vcmi log priority
  120. //todo: make separate log domain for SDL
  121. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  122. }
  123. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  124. int wmain(int argc, wchar_t* argv[])
  125. #elif defined(VCMI_IOS) || defined(VCMI_ANDROID)
  126. int SDL_main(int argc, char *argv[])
  127. #else
  128. int main(int argc, char * argv[])
  129. #endif
  130. {
  131. #ifdef VCMI_ANDROID
  132. // boost will crash without this
  133. setenv("LANG", "C", 1);
  134. #endif
  135. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  136. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  137. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  138. #endif
  139. std::cout << "Starting... " << std::endl;
  140. po::options_description opts("Allowed options");
  141. opts.add_options()
  142. ("help,h", "display help and exit")
  143. ("version,v", "display version information and exit")
  144. ("disable-shm", "force disable shared memory usage")
  145. ("enable-shm-uuid", "use UUID for shared memory identifier")
  146. ("testmap", po::value<std::string>(), "")
  147. ("testsave", po::value<std::string>(), "")
  148. ("spectate,s", "enable spectator interface for AI-only games")
  149. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  150. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  151. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  152. ("spectate-skip-battle", "skip battles in spectator view")
  153. ("spectate-skip-battle-result", "skip battle result window")
  154. ("onlyAI", "allow to run without human player, all players will be default AI")
  155. ("headless", "runs without GUI, implies --onlyAI")
  156. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  157. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  158. ("autoSkip", "automatically skip turns in GUI")
  159. ("disable-video", "disable video player")
  160. ("nointro,i", "skips intro movies")
  161. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  162. ("serverport", po::value<si64>(), "override port specified in config file")
  163. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  164. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  165. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  166. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  167. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  168. ("lobby-host", "if this client hosts session")
  169. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  170. ("lobby-connections", po::value<ui16>(), "connections of server")
  171. ("lobby-username", po::value<std::string>(), "player name")
  172. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  173. ("uuid", po::value<std::string>(), "uuid for the client");
  174. if(argc > 1)
  175. {
  176. try
  177. {
  178. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  179. }
  180. catch(std::exception &e)
  181. {
  182. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  183. }
  184. }
  185. po::notify(vm);
  186. if(vm.count("help"))
  187. {
  188. prog_help(opts);
  189. #ifdef VCMI_IOS
  190. exit(0);
  191. #else
  192. return 0;
  193. #endif
  194. }
  195. if(vm.count("version"))
  196. {
  197. prog_version();
  198. #ifdef VCMI_IOS
  199. exit(0);
  200. #else
  201. return 0;
  202. #endif
  203. }
  204. // Init old logging system and new (temporary) logging system
  205. CStopWatch total, pomtime;
  206. std::cout.flags(std::ios::unitbuf);
  207. #ifndef VCMI_IOS
  208. console = new CConsoleHandler();
  209. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  210. {
  211. ClientCommandManager commandController;
  212. commandController.processCommand(buffer, calledFromIngameConsole);
  213. };
  214. *console->cb = callbackFunction;
  215. console->start();
  216. #endif
  217. const bfs::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  218. logConfig = new CBasicLogConfigurator(logPath, console);
  219. logConfig->configureDefault();
  220. logGlobal->info(NAME);
  221. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  222. logGlobal->info("The log file will be saved to %s", logPath);
  223. // Init filesystem and settings
  224. preinitDLL(::console);
  225. settings.init();
  226. Settings session = settings.write["session"];
  227. auto setSettingBool = [](std::string key, std::string arg) {
  228. Settings s = settings.write(vstd::split(key, "/"));
  229. if(::vm.count(arg))
  230. s->Bool() = true;
  231. else if(s->isNull())
  232. s->Bool() = false;
  233. };
  234. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  235. Settings s = settings.write(vstd::split(key, "/"));
  236. if(::vm.count(arg))
  237. s->Integer() = ::vm[arg].as<si64>();
  238. else if(s->isNull())
  239. s->Integer() = defaultValue;
  240. };
  241. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  242. Settings s = settings.write(vstd::split(key, "/"));
  243. if(::vm.count(arg))
  244. s->String() = ::vm[arg].as<std::string>();
  245. else if(s->isNull())
  246. s->String() = defaultValue;
  247. };
  248. setSettingBool("session/onlyai", "onlyAI");
  249. if(vm.count("headless"))
  250. {
  251. session["headless"].Bool() = true;
  252. session["onlyai"].Bool() = true;
  253. }
  254. else if(vm.count("spectate"))
  255. {
  256. session["spectate"].Bool() = true;
  257. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  258. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  259. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  260. if(vm.count("spectate-hero-speed"))
  261. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  262. if(vm.count("spectate-battle-speed"))
  263. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  264. }
  265. // Server settings
  266. setSettingBool("session/donotstartserver", "donotstartserver");
  267. // Shared memory options
  268. setSettingBool("session/disable-shm", "disable-shm");
  269. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  270. // Init special testing settings
  271. setSettingInteger("session/serverport", "serverport", 0);
  272. setSettingString("session/saveprefix", "saveprefix", "");
  273. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  274. // Initialize logging based on settings
  275. logConfig->configure();
  276. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  277. // Some basic data validation to produce better error messages in cases of incorrect install
  278. auto testFile = [](std::string filename, std::string message) -> bool
  279. {
  280. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  281. return true;
  282. logGlobal->error("Error: %s was not found!", message);
  283. return false;
  284. };
  285. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  286. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  287. {
  288. exit(1); // These are unrecoverable errors
  289. }
  290. // these two are optional + some installs have them on CD and not in data directory
  291. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  292. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  293. conf.init();
  294. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  295. srand ( (unsigned int)time(nullptr) );
  296. const JsonNode& video = settings["video"];
  297. const JsonNode& res = video["screenRes"];
  298. //something is really wrong...
  299. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  300. {
  301. logGlobal->error("Fatal error: failed to load settings!");
  302. logGlobal->error("Possible reasons:");
  303. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  304. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  305. logGlobal->error("VCMI will now exit...");
  306. exit(EXIT_FAILURE);
  307. }
  308. if(!settings["session"]["headless"].Bool())
  309. {
  310. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  311. {
  312. logGlobal->error("Something was wrong: %s", SDL_GetError());
  313. exit(-1);
  314. }
  315. #ifdef VCMI_ANDROID
  316. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  317. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  318. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  319. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  320. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  321. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  322. #endif // VCMI_ANDROID
  323. //(!)init here AFTER SDL_Init() while using SDL for FPS management
  324. GH.init();
  325. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  326. int driversCount = SDL_GetNumRenderDrivers();
  327. std::string preferredDriverName = video["driver"].String();
  328. logGlobal->info("Found %d render drivers", driversCount);
  329. for(int it = 0; it < driversCount; it++)
  330. {
  331. SDL_RendererInfo info;
  332. SDL_GetRenderDriverInfo(it,&info);
  333. std::string driverName(info.name);
  334. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  335. {
  336. preferredDriverIndex = it;
  337. logGlobal->info("\t%s (active)", driverName);
  338. }
  339. else
  340. logGlobal->info("\t%s", driverName);
  341. }
  342. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  343. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  344. }
  345. CCS = new CClientState();
  346. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  347. CSH = new CServerHandler();
  348. // Initialize video
  349. #ifdef DISABLE_VIDEO
  350. CCS->videoh = new CEmptyVideoPlayer();
  351. #else
  352. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  353. CCS->videoh = new CVideoPlayer();
  354. else
  355. CCS->videoh = new CEmptyVideoPlayer();
  356. #endif
  357. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  358. if(!settings["session"]["headless"].Bool())
  359. {
  360. //initializing audio
  361. CCS->soundh = new CSoundHandler();
  362. CCS->soundh->init();
  363. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  364. CCS->musich = new CMusicHandler();
  365. CCS->musich->init();
  366. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  367. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  368. }
  369. #ifdef VCMI_MAC
  370. // Ctrl+click should be treated as a right click on Mac OS X
  371. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  372. #endif
  373. #ifdef SDL_HINT_MOUSE_TOUCH_EVENTS
  374. if(GH.isPointerRelativeMode)
  375. {
  376. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
  377. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  378. }
  379. #endif
  380. #ifndef VCMI_NO_THREADED_LOAD
  381. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  382. boost::thread loading(init);
  383. #else
  384. init();
  385. #endif
  386. if(!settings["session"]["headless"].Bool())
  387. {
  388. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  389. playIntro();
  390. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  391. SDL_RenderClear(mainRenderer);
  392. SDL_RenderPresent(mainRenderer);
  393. }
  394. #ifndef VCMI_NO_THREADED_LOAD
  395. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  396. {
  397. CAndroidVMHelper vmHelper;
  398. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  399. #endif // ANDROID
  400. loading.join();
  401. #ifdef VCMI_ANDROID
  402. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  403. }
  404. #endif // ANDROID
  405. #endif // THREADED
  406. if(!settings["session"]["headless"].Bool())
  407. {
  408. pomtime.getDiff();
  409. graphics = new Graphics(); // should be before curh
  410. CCS->curh = new CursorHandler();
  411. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  412. pomtime.getDiff();
  413. graphics->load();//must be after Content loading but should be in main thread
  414. logGlobal->info("Main graphics: %d ms", pomtime.getDiff());
  415. CMessage::init();
  416. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  417. CCS->curh->show();
  418. }
  419. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  420. session["autoSkip"].Bool() = vm.count("autoSkip");
  421. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  422. session["aiSolo"].Bool() = false;
  423. std::shared_ptr<CMainMenu> mmenu;
  424. if(vm.count("testmap"))
  425. {
  426. session["testmap"].String() = vm["testmap"].as<std::string>();
  427. session["onlyai"].Bool() = true;
  428. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  429. }
  430. else if(vm.count("testsave"))
  431. {
  432. session["testsave"].String() = vm["testsave"].as<std::string>();
  433. session["onlyai"].Bool() = true;
  434. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  435. }
  436. else
  437. {
  438. mmenu = CMainMenu::create();
  439. GH.curInt = mmenu.get();
  440. }
  441. std::vector<std::string> names;
  442. session["lobby"].Bool() = false;
  443. if(vm.count("lobby"))
  444. {
  445. session["lobby"].Bool() = true;
  446. session["host"].Bool() = false;
  447. session["address"].String() = vm["lobby-address"].as<std::string>();
  448. if(vm.count("lobby-username"))
  449. session["username"].String() = vm["lobby-username"].as<std::string>();
  450. else
  451. session["username"].String() = settings["launcher"]["lobbyUsername"].String();
  452. if(vm.count("lobby-gamemode"))
  453. session["gamemode"].Integer() = vm["lobby-gamemode"].as<ui16>();
  454. else
  455. session["gamemode"].Integer() = 0;
  456. CSH->uuid = vm["uuid"].as<std::string>();
  457. session["port"].Integer() = vm["lobby-port"].as<ui16>();
  458. logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
  459. if(vm.count("lobby-host"))
  460. {
  461. session["host"].Bool() = true;
  462. session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
  463. session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
  464. logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
  465. }
  466. //we should not reconnect to previous game in online mode
  467. Settings saveSession = settings.write["server"]["reconnect"];
  468. saveSession->Bool() = false;
  469. //start lobby immediately
  470. names.push_back(session["username"].String());
  471. ESelectionScreen sscreen = session["gamemode"].Integer() == 0 ? ESelectionScreen::newGame : ESelectionScreen::loadGame;
  472. mmenu->openLobby(sscreen, session["host"].Bool(), &names, ELoadMode::MULTI);
  473. }
  474. // Restore remote session - start game immediately
  475. if(settings["server"]["reconnect"].Bool())
  476. {
  477. CSH->restoreLastSession();
  478. }
  479. if(!settings["session"]["headless"].Bool())
  480. {
  481. mainLoop();
  482. }
  483. else
  484. {
  485. while(true)
  486. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  487. }
  488. return 0;
  489. }
  490. //plays intro, ends when intro is over or button has been pressed (handles events)
  491. void playIntro()
  492. {
  493. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  494. {
  495. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  496. }
  497. }
  498. #if !defined(VCMI_IOS) && !defined(VCMI_ANDROID)
  499. static bool checkVideoMode(int monitorIndex, int w, int h)
  500. {
  501. //we only check that our desired window size fits on screen
  502. SDL_DisplayMode mode;
  503. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  504. {
  505. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  506. logGlobal->error(SDL_GetError());
  507. return false;
  508. }
  509. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  510. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  511. {
  512. return true;
  513. }
  514. return false;
  515. }
  516. #endif
  517. static void cleanupRenderer()
  518. {
  519. screenBuf = nullptr; //it`s a link - just nullify
  520. if(nullptr != screen2)
  521. {
  522. SDL_FreeSurface(screen2);
  523. screen2 = nullptr;
  524. }
  525. if(nullptr != screen)
  526. {
  527. SDL_FreeSurface(screen);
  528. screen = nullptr;
  529. }
  530. if(nullptr != screenTexture)
  531. {
  532. SDL_DestroyTexture(screenTexture);
  533. screenTexture = nullptr;
  534. }
  535. }
  536. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  537. {
  538. // VCMI will only work with 2 or 4 bytes per pixel
  539. vstd::amax(bpp, 16);
  540. vstd::amin(bpp, 32);
  541. if(bpp>16)
  542. bpp = 32;
  543. if(displayIndex < 0)
  544. {
  545. if (mainWindow != nullptr)
  546. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  547. if (displayIndex < 0)
  548. displayIndex = 0;
  549. }
  550. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  551. SDL_GetWindowSize(mainWindow, &w, &h);
  552. #else
  553. if(!checkVideoMode(displayIndex, w, h))
  554. {
  555. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  556. }
  557. #endif
  558. bool bufOnScreen = (screenBuf == screen);
  559. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  560. /* match best rendering resolution */
  561. int renderWidth = 0, renderHeight = 0;
  562. auto aspectRatio = (float)w / (float)h;
  563. auto minDiff = 10.f;
  564. for (const auto& pair : conf.guiOptions)
  565. {
  566. int pWidth, pHeight;
  567. std::tie(pWidth, pHeight) = pair.first;
  568. /* filter out resolution which is larger than window */
  569. if (pWidth > w || pHeight > h)
  570. {
  571. continue;
  572. }
  573. auto ratio = (float)pWidth / (float)pHeight;
  574. auto diff = fabs(aspectRatio - ratio);
  575. /* select closest aspect ratio */
  576. if (diff < minDiff)
  577. {
  578. renderWidth = pWidth;
  579. renderHeight = pHeight;
  580. minDiff = diff;
  581. }
  582. /* select largest resolution meets prior conditions.
  583. * since there are resolutions like 1366x768(not exactly 16:9), a deviation of 0.005 is allowed. */
  584. else if (fabs(diff - minDiff) < 0.005f && pWidth > renderWidth)
  585. {
  586. renderWidth = pWidth;
  587. renderHeight = pHeight;
  588. }
  589. }
  590. if (renderWidth == 0)
  591. {
  592. // no matching resolution for upscaling - complain & fallback to default resolution.
  593. logGlobal->error("Failed to match rendering resolution for %dx%d!", w, h);
  594. Settings newRes = settings.write["video"]["screenRes"];
  595. std::tie(w, h) = conf.guiOptions.begin()->first;
  596. newRes["width"].Float() = w;
  597. newRes["height"].Float() = h;
  598. conf.SetResolution(w, h);
  599. logGlobal->error("Falling back to %dx%d", w, h);
  600. renderWidth = w;
  601. renderHeight = h;
  602. }
  603. else
  604. {
  605. logGlobal->info("Set logical rendering resolution to %dx%d", renderWidth, renderHeight);
  606. }
  607. cleanupRenderer();
  608. if(nullptr == mainWindow)
  609. {
  610. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  611. auto createWindow = [displayIndex](uint32_t extraFlags) -> bool {
  612. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN | extraFlags);
  613. return mainWindow != nullptr;
  614. };
  615. # ifdef VCMI_IOS
  616. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  617. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  618. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  619. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  620. if(!createWindow(windowFlags | SDL_WINDOW_METAL))
  621. {
  622. logGlobal->warn("Metal unavailable, using OpenGLES");
  623. createWindow(windowFlags);
  624. }
  625. # else
  626. createWindow(0);
  627. # endif // VCMI_IOS
  628. // 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
  629. // 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
  630. SDL_Rect screenRect;
  631. if(SDL_GetDisplayBounds(0, &screenRect) == 0)
  632. {
  633. const auto screenWidth = screenRect.w;
  634. const auto screenHeight = screenRect.h;
  635. const auto aspect = static_cast<double>(screenWidth) / screenHeight;
  636. logGlobal->info("Screen size and aspect ratio: %dx%d (%lf)", screenWidth, screenHeight, aspect);
  637. if((double)w / aspect > (double)h)
  638. {
  639. h = (int)round((double)w / aspect);
  640. }
  641. else
  642. {
  643. w = (int)round((double)h * aspect);
  644. }
  645. logGlobal->info("Changing logical screen size to %dx%d", w, h);
  646. }
  647. else
  648. {
  649. logGlobal->error("Can't fix aspect ratio for screen");
  650. }
  651. #else
  652. if(fullscreen)
  653. {
  654. if(realFullscreen)
  655. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), renderWidth, renderHeight, SDL_WINDOW_FULLSCREEN);
  656. else //in windowed full-screen mode use desktop resolution
  657. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  658. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  659. }
  660. else
  661. {
  662. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  663. }
  664. #endif // defined(VCMI_ANDROID) || defined(VCMI_IOS)
  665. if(nullptr == mainWindow)
  666. {
  667. throw std::runtime_error("Unable to create window\n");
  668. }
  669. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  670. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  671. if(nullptr == mainRenderer)
  672. {
  673. throw std::runtime_error("Unable to create renderer\n");
  674. }
  675. SDL_RendererInfo info;
  676. SDL_GetRendererInfo(mainRenderer, &info);
  677. logGlobal->info("Created renderer %s", info.name);
  678. }
  679. else
  680. {
  681. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  682. if(fullscreen)
  683. {
  684. if(realFullscreen)
  685. {
  686. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  687. SDL_DisplayMode mode;
  688. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  689. mode.w = renderWidth;
  690. mode.h = renderHeight;
  691. SDL_SetWindowDisplayMode(mainWindow, &mode);
  692. }
  693. else
  694. {
  695. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  696. }
  697. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  698. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  699. }
  700. else
  701. {
  702. SDL_SetWindowFullscreen(mainWindow, 0);
  703. SDL_SetWindowSize(mainWindow, w, h);
  704. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  705. }
  706. #endif
  707. }
  708. if(!(fullscreen && realFullscreen))
  709. {
  710. SDL_RenderSetLogicalSize(mainRenderer, renderWidth, renderHeight);
  711. //following line is bugged not only on android, do not re-enable without checking
  712. //#ifndef VCMI_ANDROID
  713. // // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  714. // SDL_RenderSetViewport(mainRenderer, nullptr);
  715. //#endif
  716. }
  717. #ifdef VCMI_ENDIAN_BIG
  718. int bmask = 0xff000000;
  719. int gmask = 0x00ff0000;
  720. int rmask = 0x0000ff00;
  721. int amask = 0x000000ff;
  722. #else
  723. int bmask = 0x000000ff;
  724. int gmask = 0x0000ff00;
  725. int rmask = 0x00ff0000;
  726. int amask = 0xFF000000;
  727. #endif
  728. screen = SDL_CreateRGBSurface(0,renderWidth,renderHeight,bpp,rmask,gmask,bmask,amask);
  729. if(nullptr == screen)
  730. {
  731. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", renderWidth, renderHeight, bpp, SDL_GetError());
  732. throw std::runtime_error("Unable to create surface");
  733. }
  734. //No blending for screen itself. Required for proper cursor rendering.
  735. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  736. screenTexture = SDL_CreateTexture(mainRenderer,
  737. SDL_PIXELFORMAT_ARGB8888,
  738. SDL_TEXTUREACCESS_STREAMING,
  739. renderWidth, renderHeight);
  740. if(nullptr == screenTexture)
  741. {
  742. logGlobal->error("Unable to create screen texture");
  743. logGlobal->error(SDL_GetError());
  744. throw std::runtime_error("Unable to create screen texture");
  745. }
  746. screen2 = CSDL_Ext::copySurface(screen);
  747. if(nullptr == screen2)
  748. {
  749. throw std::runtime_error("Unable to copy surface\n");
  750. }
  751. screenBuf = bufOnScreen ? screen : screen2;
  752. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  753. SDL_RenderClear(mainRenderer);
  754. SDL_RenderPresent(mainRenderer);
  755. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  756. {
  757. NotificationHandler::init(mainWindow);
  758. }
  759. return true;
  760. }
  761. //used only once during initialization
  762. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  763. {
  764. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  765. {
  766. throw std::runtime_error("Requested screen resolution is not available\n");
  767. }
  768. }
  769. static void fullScreenChanged()
  770. {
  771. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  772. Settings full = settings.write["video"]["fullscreen"];
  773. const bool toFullscreen = full->Bool();
  774. auto bitsPerPixel = screen->format->BitsPerPixel;
  775. auto w = screen->w;
  776. auto h = screen->h;
  777. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  778. {
  779. //will return false and report error if video mode is not supported
  780. return;
  781. }
  782. GH.totalRedraw();
  783. }
  784. static void handleEvent(SDL_Event & ev)
  785. {
  786. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  787. {
  788. #ifdef VCMI_ANDROID
  789. handleQuit(false);
  790. #else
  791. handleQuit();
  792. #endif
  793. return;
  794. }
  795. #ifdef VCMI_ANDROID
  796. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  797. {
  798. handleQuit(true);
  799. }
  800. #endif
  801. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  802. {
  803. Settings full = settings.write["video"]["fullscreen"];
  804. full->Bool() = !full->Bool();
  805. return;
  806. }
  807. else if(ev.type == SDL_USEREVENT)
  808. {
  809. switch(static_cast<EUserEvent>(ev.user.code))
  810. {
  811. case EUserEvent::FORCE_QUIT:
  812. {
  813. handleQuit(false);
  814. return;
  815. }
  816. break;
  817. case EUserEvent::RETURN_TO_MAIN_MENU:
  818. {
  819. CSH->endGameplay();
  820. GH.defActionsDef = 63;
  821. CMM->menu->switchToTab("main");
  822. }
  823. break;
  824. case EUserEvent::RESTART_GAME:
  825. {
  826. CSH->sendRestartGame();
  827. }
  828. break;
  829. case EUserEvent::CAMPAIGN_START_SCENARIO:
  830. {
  831. CSH->campaignServerRestartLock.set(true);
  832. CSH->endGameplay();
  833. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  834. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  835. auto finisher = [=]()
  836. {
  837. if(ourCampaign->mapsRemaining.size())
  838. {
  839. GH.pushInt(CMM);
  840. GH.pushInt(CMM->menu);
  841. CMM->openCampaignLobby(ourCampaign);
  842. }
  843. };
  844. if(epilogue.hasPrologEpilog)
  845. {
  846. GH.pushIntT<CPrologEpilogVideo>(epilogue, finisher);
  847. }
  848. else
  849. {
  850. CSH->campaignServerRestartLock.waitUntil(false);
  851. finisher();
  852. }
  853. }
  854. break;
  855. case EUserEvent::RETURN_TO_MENU_LOAD:
  856. CSH->endGameplay();
  857. GH.defActionsDef = 63;
  858. CMM->menu->switchToTab("load");
  859. break;
  860. case EUserEvent::FULLSCREEN_TOGGLED:
  861. fullScreenChanged();
  862. break;
  863. case EUserEvent::INTERFACE_CHANGED:
  864. if(LOCPLINT)
  865. LOCPLINT->updateAmbientSounds();
  866. break;
  867. default:
  868. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  869. break;
  870. }
  871. return;
  872. }
  873. else if(ev.type == SDL_WINDOWEVENT)
  874. {
  875. switch (ev.window.event) {
  876. case SDL_WINDOWEVENT_RESTORED:
  877. #ifndef VCMI_IOS
  878. fullScreenChanged();
  879. #endif
  880. break;
  881. }
  882. return;
  883. }
  884. else if(ev.type == SDL_SYSWMEVENT)
  885. {
  886. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  887. {
  888. NotificationHandler::handleSdlEvent(ev);
  889. }
  890. }
  891. //preprocessing
  892. if(ev.type == SDL_MOUSEMOTION)
  893. {
  894. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  895. }
  896. {
  897. boost::unique_lock<boost::mutex> lock(eventsM);
  898. SDLEventsQueue.push(ev);
  899. }
  900. }
  901. static void mainLoop()
  902. {
  903. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  904. resChanged([](const JsonNode &newState){ CGuiHandler::pushUserEvent(EUserEvent::FULLSCREEN_TOGGLED); });
  905. inGuiThread.reset(new bool(true));
  906. GH.mainFPSmng->init();
  907. while(1) //main SDL events loop
  908. {
  909. SDL_Event ev;
  910. while(1 == SDL_PollEvent(&ev))
  911. {
  912. handleEvent(ev);
  913. }
  914. CSH->applyPacksOnLobbyScreen();
  915. GH.renderFrame();
  916. }
  917. }
  918. static void quitApplication()
  919. {
  920. if(!settings["session"]["headless"].Bool())
  921. {
  922. if(CSH->client)
  923. CSH->endGameplay();
  924. }
  925. GH.listInt.clear();
  926. GH.objsToBlit.clear();
  927. CMM.reset();
  928. if(!settings["session"]["headless"].Bool())
  929. {
  930. // cleanup, mostly to remove false leaks from analyzer
  931. if(CCS)
  932. {
  933. CCS->musich->release();
  934. CCS->soundh->release();
  935. vstd::clear_pointer(CCS);
  936. }
  937. CMessage::dispose();
  938. vstd::clear_pointer(graphics);
  939. }
  940. vstd::clear_pointer(VLC);
  941. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  942. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  943. if(!settings["session"]["headless"].Bool())
  944. {
  945. if(settings["general"]["notifications"].Bool())
  946. {
  947. NotificationHandler::destroy();
  948. }
  949. cleanupRenderer();
  950. if(nullptr != mainRenderer)
  951. {
  952. SDL_DestroyRenderer(mainRenderer);
  953. mainRenderer = nullptr;
  954. }
  955. if(nullptr != mainWindow)
  956. {
  957. SDL_DestroyWindow(mainWindow);
  958. mainWindow = nullptr;
  959. }
  960. SDL_Quit();
  961. }
  962. if(logConfig != nullptr)
  963. {
  964. logConfig->deconfigure();
  965. delete logConfig;
  966. logConfig = nullptr;
  967. }
  968. std::cout << "Ending...\n";
  969. exit(0);
  970. }
  971. void handleQuit(bool ask)
  972. {
  973. if(CSH->client && LOCPLINT && ask)
  974. {
  975. CCS->curh->set(Cursor::Map::POINTER);
  976. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], [](){
  977. // Workaround for assertion failure on exit:
  978. // handleQuit() is alway called during SDL event processing
  979. // during which, eventsM is kept locked
  980. // this leads to assertion failure if boost::mutex is in locked state
  981. eventsM.unlock();
  982. quitApplication();
  983. }, nullptr);
  984. }
  985. else
  986. {
  987. quitApplication();
  988. }
  989. }