CMT.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. // Debug code to load all maps on start
  99. //ClientCommandManager commandController;
  100. //commandController.processCommand("convert txt", false);
  101. }
  102. static void prog_version()
  103. {
  104. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  105. std::cout << VCMIDirs::get().genHelpString();
  106. }
  107. static void prog_help(const po::options_description &opts)
  108. {
  109. auto time = std::time(0);
  110. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  111. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  112. printf("This is free software; see the source for copying conditions. There is NO\n");
  113. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  114. printf("\n");
  115. std::cout << opts;
  116. }
  117. static void SDLLogCallback(void* userdata,
  118. int category,
  119. SDL_LogPriority priority,
  120. const char* message)
  121. {
  122. //todo: convert SDL log priority to vcmi log priority
  123. //todo: make separate log domain for SDL
  124. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  125. }
  126. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  127. int wmain(int argc, wchar_t* argv[])
  128. #elif defined(VCMI_MOBILE)
  129. int SDL_main(int argc, char *argv[])
  130. #else
  131. int main(int argc, char * argv[])
  132. #endif
  133. {
  134. #ifdef VCMI_ANDROID
  135. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  136. // boost will crash without this
  137. setenv("LANG", "C", 1);
  138. #endif
  139. #if !defined(VCMI_MOBILE)
  140. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  141. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  142. #endif
  143. std::cout << "Starting... " << std::endl;
  144. po::options_description opts("Allowed options");
  145. opts.add_options()
  146. ("help,h", "display help and exit")
  147. ("version,v", "display version information and exit")
  148. ("disable-shm", "force disable shared memory usage")
  149. ("enable-shm-uuid", "use UUID for shared memory identifier")
  150. ("testmap", po::value<std::string>(), "")
  151. ("testsave", po::value<std::string>(), "")
  152. ("spectate,s", "enable spectator interface for AI-only games")
  153. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  154. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  155. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  156. ("spectate-skip-battle", "skip battles in spectator view")
  157. ("spectate-skip-battle-result", "skip battle result window")
  158. ("onlyAI", "allow to run without human player, all players will be default AI")
  159. ("headless", "runs without GUI, implies --onlyAI")
  160. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  161. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  162. ("autoSkip", "automatically skip turns in GUI")
  163. ("disable-video", "disable video player")
  164. ("nointro,i", "skips intro movies")
  165. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  166. ("serverport", po::value<si64>(), "override port specified in config file")
  167. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  168. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  169. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  170. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  171. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  172. ("lobby-host", "if this client hosts session")
  173. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  174. ("lobby-connections", po::value<ui16>(), "connections of server")
  175. ("lobby-username", po::value<std::string>(), "player name")
  176. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  177. ("uuid", po::value<std::string>(), "uuid for the client");
  178. if(argc > 1)
  179. {
  180. try
  181. {
  182. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  183. }
  184. catch(std::exception &e)
  185. {
  186. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  187. }
  188. }
  189. po::notify(vm);
  190. if(vm.count("help"))
  191. {
  192. prog_help(opts);
  193. #ifdef VCMI_IOS
  194. exit(0);
  195. #else
  196. return 0;
  197. #endif
  198. }
  199. if(vm.count("version"))
  200. {
  201. prog_version();
  202. #ifdef VCMI_IOS
  203. exit(0);
  204. #else
  205. return 0;
  206. #endif
  207. }
  208. // Init old logging system and new (temporary) logging system
  209. CStopWatch total, pomtime;
  210. std::cout.flags(std::ios::unitbuf);
  211. #ifndef VCMI_IOS
  212. console = new CConsoleHandler();
  213. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  214. {
  215. ClientCommandManager commandController;
  216. commandController.processCommand(buffer, calledFromIngameConsole);
  217. };
  218. *console->cb = callbackFunction;
  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 session = settings.write["session"];
  230. auto setSettingBool = [](std::string key, std::string arg) {
  231. Settings s = settings.write(vstd::split(key, "/"));
  232. if(::vm.count(arg))
  233. s->Bool() = true;
  234. else if(s->isNull())
  235. s->Bool() = false;
  236. };
  237. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  238. Settings s = settings.write(vstd::split(key, "/"));
  239. if(::vm.count(arg))
  240. s->Integer() = ::vm[arg].as<si64>();
  241. else if(s->isNull())
  242. s->Integer() = defaultValue;
  243. };
  244. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  245. Settings s = settings.write(vstd::split(key, "/"));
  246. if(::vm.count(arg))
  247. s->String() = ::vm[arg].as<std::string>();
  248. else if(s->isNull())
  249. s->String() = defaultValue;
  250. };
  251. setSettingBool("session/onlyai", "onlyAI");
  252. if(vm.count("headless"))
  253. {
  254. session["headless"].Bool() = true;
  255. session["onlyai"].Bool() = true;
  256. }
  257. else if(vm.count("spectate"))
  258. {
  259. session["spectate"].Bool() = true;
  260. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  261. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  262. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  263. if(vm.count("spectate-hero-speed"))
  264. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  265. if(vm.count("spectate-battle-speed"))
  266. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  267. }
  268. // Server settings
  269. setSettingBool("session/donotstartserver", "donotstartserver");
  270. // Shared memory options
  271. setSettingBool("session/disable-shm", "disable-shm");
  272. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  273. // Init special testing settings
  274. setSettingInteger("session/serverport", "serverport", 0);
  275. setSettingString("session/saveprefix", "saveprefix", "");
  276. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  277. // Initialize logging based on settings
  278. logConfig->configure();
  279. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  280. // Some basic data validation to produce better error messages in cases of incorrect install
  281. auto testFile = [](std::string filename, std::string message) -> bool
  282. {
  283. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  284. return true;
  285. logGlobal->error("Error: %s was not found!", message);
  286. return false;
  287. };
  288. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  289. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  290. {
  291. exit(1); // These are unrecoverable errors
  292. }
  293. // these two are optional + some installs have them on CD and not in data directory
  294. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  295. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  296. conf.init();
  297. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  298. srand ( (unsigned int)time(nullptr) );
  299. const JsonNode& video = settings["video"];
  300. const JsonNode& res = video["screenRes"];
  301. //something is really wrong...
  302. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  303. {
  304. logGlobal->error("Fatal error: failed to load settings!");
  305. logGlobal->error("Possible reasons:");
  306. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  307. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  308. logGlobal->error("VCMI will now exit...");
  309. exit(EXIT_FAILURE);
  310. }
  311. if(!settings["session"]["headless"].Bool())
  312. {
  313. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  314. {
  315. logGlobal->error("Something was wrong: %s", SDL_GetError());
  316. exit(-1);
  317. }
  318. #ifdef VCMI_ANDROID
  319. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  320. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  321. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  322. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  323. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  324. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  325. #endif // VCMI_ANDROID
  326. //(!)init here AFTER SDL_Init() while using SDL for FPS management
  327. GH.init();
  328. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  329. int driversCount = SDL_GetNumRenderDrivers();
  330. std::string preferredDriverName = video["driver"].String();
  331. logGlobal->info("Found %d render drivers", driversCount);
  332. for(int it = 0; it < driversCount; it++)
  333. {
  334. SDL_RendererInfo info;
  335. SDL_GetRenderDriverInfo(it,&info);
  336. std::string driverName(info.name);
  337. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  338. {
  339. preferredDriverIndex = it;
  340. logGlobal->info("\t%s (active)", driverName);
  341. }
  342. else
  343. logGlobal->info("\t%s", driverName);
  344. }
  345. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  346. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  347. }
  348. CCS = new CClientState();
  349. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  350. CSH = new CServerHandler();
  351. // Initialize video
  352. #ifdef DISABLE_VIDEO
  353. CCS->videoh = new CEmptyVideoPlayer();
  354. #else
  355. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  356. CCS->videoh = new CVideoPlayer();
  357. else
  358. CCS->videoh = new CEmptyVideoPlayer();
  359. #endif
  360. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  361. if(!settings["session"]["headless"].Bool())
  362. {
  363. //initializing audio
  364. CCS->soundh = new CSoundHandler();
  365. CCS->soundh->init();
  366. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  367. CCS->musich = new CMusicHandler();
  368. CCS->musich->init();
  369. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  370. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  371. }
  372. #ifdef VCMI_MAC
  373. // Ctrl+click should be treated as a right click on Mac OS X
  374. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  375. #endif
  376. #ifdef SDL_HINT_MOUSE_TOUCH_EVENTS
  377. if(GH.isPointerRelativeMode)
  378. {
  379. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
  380. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  381. }
  382. #endif
  383. #ifndef VCMI_NO_THREADED_LOAD
  384. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  385. boost::thread loading(init);
  386. #else
  387. init();
  388. #endif
  389. if(!settings["session"]["headless"].Bool())
  390. {
  391. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  392. playIntro();
  393. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  394. SDL_RenderClear(mainRenderer);
  395. SDL_RenderPresent(mainRenderer);
  396. }
  397. #ifndef VCMI_NO_THREADED_LOAD
  398. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  399. {
  400. CAndroidVMHelper vmHelper;
  401. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  402. #endif // ANDROID
  403. loading.join();
  404. #ifdef VCMI_ANDROID
  405. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  406. }
  407. #endif // ANDROID
  408. #endif // THREADED
  409. if(!settings["session"]["headless"].Bool())
  410. {
  411. pomtime.getDiff();
  412. graphics = new Graphics(); // should be before curh
  413. CCS->curh = new CursorHandler();
  414. logGlobal->info("Screen handler: %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_MOBILE)
  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_MOBILE)
  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_MOBILE)
  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_MOBILE)
  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_MOBILE)
  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. default:
  864. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  865. break;
  866. }
  867. return;
  868. }
  869. else if(ev.type == SDL_WINDOWEVENT)
  870. {
  871. switch (ev.window.event) {
  872. case SDL_WINDOWEVENT_RESTORED:
  873. #ifndef VCMI_IOS
  874. fullScreenChanged();
  875. #endif
  876. break;
  877. }
  878. return;
  879. }
  880. else if(ev.type == SDL_SYSWMEVENT)
  881. {
  882. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  883. {
  884. NotificationHandler::handleSdlEvent(ev);
  885. }
  886. }
  887. //preprocessing
  888. if(ev.type == SDL_MOUSEMOTION)
  889. {
  890. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  891. }
  892. {
  893. boost::unique_lock<boost::mutex> lock(eventsM);
  894. SDLEventsQueue.push(ev);
  895. }
  896. }
  897. static void mainLoop()
  898. {
  899. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  900. resChanged([](const JsonNode &newState){ CGuiHandler::pushUserEvent(EUserEvent::FULLSCREEN_TOGGLED); });
  901. inGuiThread.reset(new bool(true));
  902. assert(GH.mainFPSmng);
  903. GH.mainFPSmng->init(settings["video"]["targetfps"].Integer());
  904. while(1) //main SDL events loop
  905. {
  906. SDL_Event ev;
  907. while(1 == SDL_PollEvent(&ev))
  908. {
  909. handleEvent(ev);
  910. }
  911. CSH->applyPacksOnLobbyScreen();
  912. GH.renderFrame();
  913. }
  914. }
  915. static void quitApplication()
  916. {
  917. if(!settings["session"]["headless"].Bool())
  918. {
  919. if(CSH->client)
  920. CSH->endGameplay();
  921. }
  922. GH.listInt.clear();
  923. GH.objsToBlit.clear();
  924. CMM.reset();
  925. if(!settings["session"]["headless"].Bool())
  926. {
  927. // cleanup, mostly to remove false leaks from analyzer
  928. if(CCS)
  929. {
  930. CCS->musich->release();
  931. CCS->soundh->release();
  932. vstd::clear_pointer(CCS);
  933. }
  934. CMessage::dispose();
  935. vstd::clear_pointer(graphics);
  936. }
  937. vstd::clear_pointer(VLC);
  938. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  939. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  940. if(!settings["session"]["headless"].Bool())
  941. {
  942. if(settings["general"]["notifications"].Bool())
  943. {
  944. NotificationHandler::destroy();
  945. }
  946. cleanupRenderer();
  947. if(nullptr != mainRenderer)
  948. {
  949. SDL_DestroyRenderer(mainRenderer);
  950. mainRenderer = nullptr;
  951. }
  952. if(nullptr != mainWindow)
  953. {
  954. SDL_DestroyWindow(mainWindow);
  955. mainWindow = nullptr;
  956. }
  957. SDL_Quit();
  958. }
  959. if(logConfig != nullptr)
  960. {
  961. logConfig->deconfigure();
  962. delete logConfig;
  963. logConfig = nullptr;
  964. }
  965. std::cout << "Ending...\n";
  966. exit(0);
  967. }
  968. void handleQuit(bool ask)
  969. {
  970. if(CSH->client && LOCPLINT && ask)
  971. {
  972. CCS->curh->set(Cursor::Map::POINTER);
  973. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], [](){
  974. // Workaround for assertion failure on exit:
  975. // handleQuit() is alway called during SDL event processing
  976. // during which, eventsM is kept locked
  977. // this leads to assertion failure if boost::mutex is in locked state
  978. eventsM.unlock();
  979. quitApplication();
  980. }, nullptr);
  981. }
  982. else
  983. {
  984. quitApplication();
  985. }
  986. }