CMT.cpp 34 KB

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