2
0

CMT.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. // CMT.cpp : Defines the entry point for the console application.
  2. //
  3. #include "StdInc.h"
  4. #include <SDL_mixer.h>
  5. #include <boost/program_options.hpp>
  6. #include "gui/SDL_Extensions.h"
  7. #include "CGameInfo.h"
  8. #include "mapHandler.h"
  9. #include "../lib/filesystem/Filesystem.h"
  10. #include "../lib/filesystem/FileStream.h"
  11. #include "CPreGame.h"
  12. #include "windows/CCastleInterface.h"
  13. #include "../lib/CConsoleHandler.h"
  14. #include "gui/CCursorHandler.h"
  15. #include "../lib/CGameState.h"
  16. #include "../CCallback.h"
  17. #include "CPlayerInterface.h"
  18. #include "windows/CAdvmapInterface.h"
  19. #include "../lib/CBuildingHandler.h"
  20. #include "CVideoHandler.h"
  21. #include "../lib/CHeroHandler.h"
  22. #include "../lib/CCreatureHandler.h"
  23. #include "../lib/spells/CSpellHandler.h"
  24. #include "CMusicHandler.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "Graphics.h"
  27. #include "Client.h"
  28. #include "../lib/CConfigHandler.h"
  29. #include "../lib/serializer/BinaryDeserializer.h"
  30. #include "../lib/serializer/BinarySerializer.h"
  31. #include "../lib/VCMI_Lib.h"
  32. #include "../lib/VCMIDirs.h"
  33. #include "../lib/NetPacks.h"
  34. #include "CMessage.h"
  35. #include "../lib/CModHandler.h"
  36. #include "../lib/CTownHandler.h"
  37. #include "../lib/CArtHandler.h"
  38. #include "../lib/CScriptingModule.h"
  39. #include "../lib/GameConstants.h"
  40. #include "gui/CGuiHandler.h"
  41. #include "../lib/logging/CBasicLogConfigurator.h"
  42. #include "../lib/StringConstants.h"
  43. #include "../lib/CPlayerState.h"
  44. #include "gui/CAnimation.h"
  45. #ifdef VCMI_WINDOWS
  46. #include "SDL_syswm.h"
  47. #endif
  48. #include "../lib/UnlockGuard.h"
  49. #include "CMT.h"
  50. #if __MINGW32__
  51. #undef main
  52. #endif
  53. namespace po = boost::program_options;
  54. namespace bfs = boost::filesystem;
  55. /*
  56. * CMT.cpp, part of VCMI engine
  57. *
  58. * Authors: listed in file AUTHORS in main folder
  59. *
  60. * License: GNU General Public License v2.0 or later
  61. * Full text of license available in license.txt file, in main folder
  62. *
  63. */
  64. std::string NAME_AFFIX = "client";
  65. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  66. CGuiHandler GH;
  67. static CClient *client = nullptr;
  68. int preferredDriverIndex = -1;
  69. SDL_Window * mainWindow = nullptr;
  70. SDL_Renderer * mainRenderer = nullptr;
  71. SDL_Texture * screenTexture = nullptr;
  72. extern boost::thread_specific_ptr<bool> inGuiThread;
  73. SDL_Surface *screen = nullptr, //main screen surface
  74. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  75. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  76. std::queue<SDL_Event> events;
  77. boost::mutex eventsM;
  78. bool gNoGUI = false;
  79. CondSh<bool> serverAlive(false);
  80. static po::variables_map vm;
  81. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  82. static bool ermInteractiveMode = false; //structurize when time is right
  83. void processCommand(const std::string &message);
  84. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  85. void dispose();
  86. void playIntro();
  87. static void mainLoop();
  88. //void requestChangingResolution();
  89. void startGame(StartInfo * options, CConnection *serv = nullptr);
  90. void endGame();
  91. #ifndef VCMI_WINDOWS
  92. #ifndef _GNU_SOURCE
  93. #define _GNU_SOURCE
  94. #endif
  95. #include <getopt.h>
  96. #endif
  97. void startGameFromFile(const bfs::path &fname)
  98. {
  99. StartInfo si;
  100. try //attempt retrieving start info from given file
  101. {
  102. if(fname.empty() || !bfs::exists(fname))
  103. throw std::runtime_error("Startfile \"" + fname.string() + "\" does not exist!");
  104. CLoadFile out(fname);
  105. if (!out.sfile || !*out.sfile)
  106. throw std::runtime_error("Cannot read from startfile \"" + fname.string() +"\"!");
  107. out >> si;
  108. }
  109. catch(std::exception &e)
  110. {
  111. logGlobal->errorStream() << "Failed to start from the file: " << fname << ". Error: " << e.what()
  112. << " Falling back to main menu.";
  113. GH.curInt = CGPreGame::create();
  114. return;
  115. }
  116. while(GH.topInt())
  117. GH.popIntTotally(GH.topInt());
  118. startGame(&si);
  119. }
  120. void init()
  121. {
  122. CStopWatch tmh, pomtime;
  123. loadDLLClasses();
  124. const_cast<CGameInfo*>(CGI)->setFromLib();
  125. logGlobal->infoStream()<<"Initializing VCMI_Lib: "<<tmh.getDiff();
  126. if(!gNoGUI)
  127. {
  128. pomtime.getDiff();
  129. CCS->curh = new CCursorHandler;
  130. graphics = new Graphics(); // should be before curh->init()
  131. CCS->curh->initCursor();
  132. CCS->curh->show();
  133. logGlobal->infoStream()<<"Screen handler: "<<pomtime.getDiff();
  134. pomtime.getDiff();
  135. graphics->load();
  136. logGlobal->infoStream()<<"\tMain graphics: "<<pomtime.getDiff();
  137. logGlobal->infoStream()<<"Initializing game graphics: "<<tmh.getDiff();
  138. CMessage::init();
  139. logGlobal->infoStream()<<"Message handler: "<<tmh.getDiff();
  140. }
  141. }
  142. static void prog_version(void)
  143. {
  144. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  145. std::cout << VCMIDirs::get().genHelpString();
  146. }
  147. static void prog_help(const po::options_description &opts)
  148. {
  149. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  150. printf("Copyright (C) 2007-2017 VCMI dev team - see AUTHORS file\n");
  151. printf("This is free software; see the source for copying conditions. There is NO\n");
  152. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  153. printf("\n");
  154. printf("Usage:\n");
  155. std::cout << opts;
  156. // printf(" -h, --help display this help and exit\n");
  157. // printf(" -v, --version display version information and exit\n");
  158. }
  159. static void SDLLogCallback(void* userdata,
  160. int category,
  161. SDL_LogPriority priority,
  162. const char* message)
  163. {
  164. //todo: convert SDL log priority to vcmi log priority
  165. //todo: make separate log domain for SDL
  166. logGlobal->debugStream() << "SDL(category " << category << "; priority " <<priority <<") "<<message;
  167. }
  168. #ifdef VCMI_APPLE
  169. void OSX_checkForUpdates();
  170. #endif
  171. #if defined(VCMI_WINDOWS) && !defined (__GNUC__)
  172. int wmain(int argc, wchar_t* argv[])
  173. #elif defined(VCMI_APPLE)
  174. int SDL_main(int argc, char *argv[])
  175. #else
  176. int main(int argc, char** argv)
  177. #endif
  178. {
  179. #ifdef VCMI_ANDROID
  180. // boost will crash without this
  181. setenv("LANG", "C", 1);
  182. #endif
  183. #ifdef VCMI_APPLE
  184. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  185. std::string executablePath = argv[0];
  186. std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
  187. chdir(workDir.c_str());
  188. // Check for updates
  189. OSX_checkForUpdates();
  190. // Check that game data is prepared. Otherwise run vcmibuilder helper application
  191. FILE* check = fopen((VCMIDirs::get().userDataPath() / "game_data_prepared").string().c_str(), "r");
  192. if (check == nullptr) {
  193. system("open ./vcmibuilder.app");
  194. return 0;
  195. }
  196. fclose(check);
  197. #endif
  198. std::cout << "Starting... " << std::endl;
  199. po::options_description opts("Allowed options");
  200. opts.add_options()
  201. ("help,h", "display help and exit")
  202. ("version,v", "display version information and exit")
  203. ("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
  204. ("start", po::value<bfs::path>(), "starts game from saved StartInfo file")
  205. ("onlyAI", "runs without human player, all players will be default AI")
  206. ("noGUI", "runs without GUI, implies --onlyAI")
  207. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  208. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  209. ("autoSkip", "automatically skip turns in GUI")
  210. ("disable-video", "disable video player")
  211. ("nointro,i", "skips intro movies")
  212. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  213. ("loadserver","specifies we are the multiplayer server for loaded games")
  214. ("loadnumplayers",po::value<int>(),"specifies the number of players connecting to a multiplayer game")
  215. ("loadhumanplayerindices",po::value<std::vector<int>>(),"Indexes of human players (0=Red, etc.)")
  216. ("loadplayer", po::value<int>(),"specifies which player we are in multiplayer loaded games (0=Red, etc.)")
  217. ("loadserverip",po::value<std::string>(),"IP for loaded game server")
  218. ("loadserverport",po::value<std::string>(),"port for loaded game server")
  219. ("testingport",po::value<std::string>(),"port for testing, override specified in config file")
  220. ("testingfileprefix",po::value<std::string>(),"prefix for auto save files")
  221. ("testingsavefrequency",po::value<int>(),"how often auto save should be created");
  222. if(argc > 1)
  223. {
  224. try
  225. {
  226. po::store(po::parse_command_line(argc, argv, opts), vm);
  227. }
  228. catch(std::exception &e)
  229. {
  230. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  231. }
  232. }
  233. po::notify(vm);
  234. if(vm.count("help"))
  235. {
  236. prog_help(opts);
  237. return 0;
  238. }
  239. if(vm.count("version"))
  240. {
  241. prog_version();
  242. return 0;
  243. }
  244. if(vm.count("noGUI"))
  245. {
  246. gNoGUI = true;
  247. vm.insert(std::pair<std::string, po::variable_value>("onlyAI", po::variable_value()));
  248. }
  249. if(vm.count("donotstartserver"))
  250. {
  251. CServerHandler::DO_NOT_START_SERVER = true;
  252. }
  253. // Have effect on X11 system only (Linux).
  254. // For whatever reason in fullscreen mode SDL takes "raw" mouse input from DGA X11 extension
  255. // (DGA = Direct graphics access). Because this is raw input (before any speed\acceleration proceesing)
  256. // it may result in very small \ very fast mouse when game in fullscreen mode
  257. putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0");
  258. // Init old logging system and new (temporary) logging system
  259. CStopWatch total, pomtime;
  260. std::cout.flags(std::ios::unitbuf);
  261. console = new CConsoleHandler;
  262. *console->cb = processCommand;
  263. console->start();
  264. const bfs::path logPath = VCMIDirs::get().userCachePath() / "VCMI_Client_log.txt";
  265. CBasicLogConfigurator logConfig(logPath, console);
  266. logConfig.configureDefault();
  267. logGlobal->infoStream() << NAME;
  268. logGlobal->infoStream() << "Creating console and configuring logger: " << pomtime.getDiff();
  269. logGlobal->infoStream() << "The log file will be saved to " << logPath;
  270. // Init filesystem and settings
  271. preinitDLL(::console);
  272. settings.init();
  273. // Init special testing settings
  274. Settings testingSettings = settings.write["testing"];
  275. if(vm.count("testingport") && vm.count("testingfileprefix"))
  276. {
  277. testingSettings["enabled"].Bool() = true;
  278. testingSettings["port"].String() = vm["testingport"].as<std::string>();
  279. testingSettings["prefix"].String() = vm["testingfileprefix"].as<std::string>();
  280. testingSettings["savefrequency"].Float() = vm.count("testingsavefrequency") ? vm["testingsavefrequency"].as<int>() : 1;
  281. }
  282. // Initialize logging based on settings
  283. logConfig.configure();
  284. // Some basic data validation to produce better error messages in cases of incorrect install
  285. auto testFile = [](std::string filename, std::string message) -> bool
  286. {
  287. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  288. return true;
  289. logGlobal->errorStream() << "Error: " << message << " was not found!";
  290. return false;
  291. };
  292. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  293. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  294. {
  295. exit(1); // These are unrecoverable errors
  296. }
  297. // these two are optional + some installs have them on CD and not in data directory
  298. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  299. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  300. conf.init();
  301. logGlobal->infoStream() << "Loading settings: " << pomtime.getDiff();
  302. srand ( time(nullptr) );
  303. const JsonNode& video = settings["video"];
  304. const JsonNode& res = video["screenRes"];
  305. //something is really wrong...
  306. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  307. {
  308. logGlobal->errorStream() << "Fatal error: failed to load settings!";
  309. logGlobal->errorStream() << "Possible reasons:";
  310. logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().userConfigPath() << "/settings.json";
  311. logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().userConfigPath() << "/schemas/settings.json";
  312. logGlobal->errorStream() << "VCMI will now exit...";
  313. exit(EXIT_FAILURE);
  314. }
  315. if(!gNoGUI)
  316. {
  317. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  318. {
  319. logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
  320. exit(-1);
  321. }
  322. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  323. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  324. int driversCount = SDL_GetNumRenderDrivers();
  325. std::string preferredDriverName = video["driver"].String();
  326. logGlobal->infoStream() << "Found " << driversCount << " render drivers";
  327. for(int it = 0; it < driversCount; it++)
  328. {
  329. SDL_RendererInfo info;
  330. SDL_GetRenderDriverInfo(it,&info);
  331. std::string driverName(info.name);
  332. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  333. {
  334. preferredDriverIndex = it;
  335. logGlobal->infoStream() << "\t" << driverName << " (active)";
  336. }
  337. else
  338. logGlobal->infoStream() << "\t" << driverName;
  339. }
  340. config::CConfigHandler::GuiOptionsMap::key_type resPair(res["width"].Float(), res["height"].Float());
  341. if (conf.guiOptions.count(resPair) == 0)
  342. {
  343. // selected resolution was not found - complain & fallback to something that we do have.
  344. logGlobal->errorStream() << "Selected resolution " << resPair.first << "x" << resPair.second << " was not found!";
  345. if (conf.guiOptions.empty())
  346. {
  347. logGlobal->errorStream() << "Unable to continue - no valid resolutions found! Please reinstall VCMI to fix this";
  348. exit(1);
  349. }
  350. else
  351. {
  352. Settings newRes = settings.write["video"]["screenRes"];
  353. newRes["width"].Float() = conf.guiOptions.begin()->first.first;
  354. newRes["height"].Float() = conf.guiOptions.begin()->first.second;
  355. conf.SetResolution(newRes["width"].Float(), newRes["height"].Float());
  356. logGlobal->errorStream() << "Falling back to " << newRes["width"].Float() << "x" << newRes["height"].Float();
  357. }
  358. }
  359. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), video["displayIndex"].Float());
  360. logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
  361. }
  362. CCS = new CClientState;
  363. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  364. // Initialize video
  365. #ifdef DISABLE_VIDEO
  366. CCS->videoh = new CEmptyVideoPlayer;
  367. #else
  368. if (!gNoGUI && !vm.count("disable-video"))
  369. CCS->videoh = new CVideoPlayer;
  370. else
  371. CCS->videoh = new CEmptyVideoPlayer;
  372. #endif
  373. logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();
  374. #if defined(VCMI_ANDROID)
  375. //on Android threaded init is broken
  376. #define VCMI_NO_THREADED_LOAD
  377. #endif // defined
  378. //initializing audio
  379. CCS->soundh = new CSoundHandler;
  380. CCS->soundh->init();
  381. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  382. CCS->musich = new CMusicHandler;
  383. CCS->musich->init();
  384. CCS->musich->setVolume(settings["general"]["music"].Float());
  385. logGlobal->infoStream()<<"Initializing screen and sound handling: "<<pomtime.getDiff();
  386. #ifdef __APPLE__
  387. // Ctrl+click should be treated as a right click on Mac OS X
  388. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  389. #endif
  390. #ifndef VCMI_NO_THREADED_LOAD
  391. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  392. boost::thread loading(init);
  393. #else
  394. init();
  395. #endif
  396. if(!gNoGUI )
  397. {
  398. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  399. playIntro();
  400. SDL_FillRect(screen,nullptr,0);
  401. }
  402. CSDL_Ext::update(screen);
  403. #ifndef VCMI_NO_THREADED_LOAD
  404. loading.join();
  405. #endif
  406. logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();
  407. if(!vm.count("battle"))
  408. {
  409. Settings session = settings.write["session"];
  410. session["autoSkip"].Bool() = vm.count("autoSkip");
  411. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  412. session["aiSolo"].Bool() = false;
  413. bfs::path fileToStartFrom; //none by default
  414. if(vm.count("start"))
  415. fileToStartFrom = vm["start"].as<bfs::path>();
  416. if(!fileToStartFrom.empty() && bfs::exists(fileToStartFrom))
  417. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from file
  418. else
  419. {
  420. if(!fileToStartFrom.empty())
  421. {
  422. logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
  423. << "). Falling back to main menu.";
  424. }
  425. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  426. }
  427. }
  428. else
  429. {
  430. auto si = new StartInfo();
  431. si->mode = StartInfo::DUEL;
  432. si->mapname = vm["battle"].as<std::string>();
  433. si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
  434. si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
  435. startGame(si);
  436. }
  437. if(!gNoGUI)
  438. {
  439. mainLoop();
  440. }
  441. else
  442. {
  443. while(true)
  444. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  445. }
  446. return 0;
  447. }
  448. void printInfoAboutIntObject(const CIntObject *obj, int level)
  449. {
  450. std::stringstream sbuffer;
  451. sbuffer << std::string(level, '\t');
  452. sbuffer << typeid(*obj).name() << " *** ";
  453. if (obj->active)
  454. {
  455. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  456. PRINT(LCLICK, 'L');
  457. PRINT(RCLICK, 'R');
  458. PRINT(HOVER, 'H');
  459. PRINT(MOVE, 'M');
  460. PRINT(KEYBOARD, 'K');
  461. PRINT(TIME, 'T');
  462. PRINT(GENERAL, 'A');
  463. PRINT(WHEEL, 'W');
  464. PRINT(DOUBLECLICK, 'D');
  465. #undef PRINT
  466. }
  467. else
  468. sbuffer << "inactive";
  469. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  470. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  471. logGlobal->infoStream() << sbuffer.str();
  472. for(const CIntObject *child : obj->children)
  473. printInfoAboutIntObject(child, level+1);
  474. }
  475. void processCommand(const std::string &message)
  476. {
  477. std::istringstream readed;
  478. readed.str(message);
  479. std::string cn; //command name
  480. readed >> cn;
  481. // Check mantis issue 2292 for details
  482. // if(LOCPLINT && LOCPLINT->cingconsole)
  483. // LOCPLINT->cingconsole->print(message);
  484. if(ermInteractiveMode)
  485. {
  486. if(cn == "exit")
  487. {
  488. ermInteractiveMode = false;
  489. return;
  490. }
  491. else
  492. {
  493. if(client && client->erm)
  494. client->erm->executeUserCommand(message);
  495. std::cout << "erm>";
  496. }
  497. }
  498. else if(message==std::string("die, fool"))
  499. {
  500. exit(EXIT_SUCCESS);
  501. }
  502. else if(cn == "erm")
  503. {
  504. ermInteractiveMode = true;
  505. std::cout << "erm>";
  506. }
  507. else if(cn==std::string("activate"))
  508. {
  509. int what;
  510. readed >> what;
  511. switch (what)
  512. {
  513. case 0:
  514. GH.topInt()->activate();
  515. break;
  516. case 1:
  517. adventureInt->activate();
  518. break;
  519. case 2:
  520. LOCPLINT->castleInt->activate();
  521. break;
  522. }
  523. }
  524. else if(cn=="redraw")
  525. {
  526. GH.totalRedraw();
  527. }
  528. else if(cn=="screen")
  529. {
  530. std::cout << "Screenbuf points to ";
  531. if(screenBuf == screen)
  532. logGlobal->errorStream() << "screen";
  533. else if(screenBuf == screen2)
  534. logGlobal->errorStream() << "screen2";
  535. else
  536. logGlobal->errorStream() << "?!?";
  537. SDL_SaveBMP(screen, "Screen_c.bmp");
  538. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  539. }
  540. else if(cn=="save")
  541. {
  542. if(!client)
  543. {
  544. std::cout << "Game in not active";
  545. return;
  546. }
  547. std::string fname;
  548. readed >> fname;
  549. client->save(fname);
  550. }
  551. // else if(cn=="load")
  552. // {
  553. // // TODO: this code should end the running game and manage to call startGame instead
  554. // std::string fname;
  555. // readed >> fname;
  556. // client->loadGame(fname);
  557. // }
  558. else if(message=="get txt")
  559. {
  560. std::cout << "Command accepted.\t";
  561. const bfs::path outPath =
  562. VCMIDirs::get().userCachePath() / "extracted";
  563. auto list = CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  564. {
  565. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  566. });
  567. for (auto & filename : list)
  568. {
  569. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  570. bfs::create_directories(filePath.parent_path());
  571. bfs::ofstream file(filePath);
  572. auto text = CResourceHandler::get()->load(filename)->readAll();
  573. file.write((char*)text.first.get(), text.second);
  574. }
  575. std::cout << "\rExtracting done :)\n";
  576. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  577. }
  578. else if(cn=="crash")
  579. {
  580. int *ptr = nullptr;
  581. *ptr = 666;
  582. //disaster!
  583. }
  584. else if(cn == "onlyai")
  585. {
  586. vm.insert(std::pair<std::string, po::variable_value>("onlyAI", po::variable_value()));
  587. }
  588. else if(cn == "mp" && adventureInt)
  589. {
  590. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  591. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  592. }
  593. else if(cn == "bonuses")
  594. {
  595. std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
  596. << adventureInt->selection->getBonusList() << std::endl;
  597. std::cout << "\nInherited bonuses:\n";
  598. TCNodes parents;
  599. adventureInt->selection->getParents(parents);
  600. for(const CBonusSystemNode *parent : parents)
  601. {
  602. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  603. }
  604. }
  605. else if(cn == "not dialog")
  606. {
  607. LOCPLINT->showingDialog->setn(false);
  608. }
  609. else if(cn == "gui")
  610. {
  611. for(const IShowActivatable *child : GH.listInt)
  612. {
  613. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  614. printInfoAboutIntObject(obj, 0);
  615. else
  616. std::cout << typeid(*child).name() << std::endl;
  617. }
  618. }
  619. else if(cn=="tell")
  620. {
  621. std::string what;
  622. int id1, id2;
  623. readed >> what >> id1 >> id2;
  624. if(what == "hs")
  625. {
  626. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  627. if(h->type->ID.getNum() == id1)
  628. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  629. std::cout << a->nodeName();
  630. }
  631. }
  632. else if (cn == "set")
  633. {
  634. std::string what, value;
  635. readed >> what;
  636. Settings conf = settings.write["session"][what];
  637. readed >> value;
  638. if (value == "on")
  639. {
  640. conf->Bool() = true;
  641. logGlobal->info("Option %s enabled!", what);
  642. }
  643. else if (value == "off")
  644. {
  645. conf->Bool() = false;
  646. logGlobal->info("Option %s disabled!", what);
  647. }
  648. }
  649. else if(cn == "sinfo")
  650. {
  651. std::string fname;
  652. readed >> fname;
  653. if(fname.size() && SEL)
  654. {
  655. CSaveFile out(fname);
  656. out << SEL->sInfo;
  657. }
  658. }
  659. else if(cn == "start")
  660. {
  661. std::string fname;
  662. readed >> fname;
  663. startGameFromFile(fname);
  664. }
  665. else if(cn == "unlock")
  666. {
  667. std::string mxname;
  668. readed >> mxname;
  669. if(mxname == "pim" && LOCPLINT)
  670. LOCPLINT->pim->unlock();
  671. }
  672. else if(cn == "def2bmp")
  673. {
  674. std::string URI;
  675. readed >> URI;
  676. std::unique_ptr<CAnimation> anim = make_unique<CAnimation>(URI);
  677. anim->preload();
  678. anim->exportBitmaps(VCMIDirs::get().userCachePath() / "extracted");
  679. }
  680. else if(cn == "extract")
  681. {
  682. std::string URI;
  683. readed >> URI;
  684. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  685. {
  686. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  687. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  688. bfs::create_directories(outPath.parent_path());
  689. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  690. outFile.write((char*)data.first.get(), data.second);
  691. }
  692. else
  693. logGlobal->errorStream() << "File not found!";
  694. }
  695. else if(cn == "setBattleAI")
  696. {
  697. std::string fname;
  698. readed >> fname;
  699. std::cout << "Will try loading that AI to see if it is correct name...\n";
  700. try
  701. {
  702. if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  703. {
  704. Settings neutralAI = settings.write["server"]["neutralAI"];
  705. neutralAI->String() = fname;
  706. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  707. }
  708. }
  709. catch(std::exception &e)
  710. {
  711. logGlobal->warnStream() << "Failed opening " << fname << ": " << e.what();
  712. logGlobal->warnStream() << "Setting not changes, AI not found or invalid!";
  713. }
  714. }
  715. auto removeGUI = [&]()
  716. {
  717. // CClient::endGame
  718. GH.curInt = nullptr;
  719. if(GH.topInt())
  720. GH.topInt()->deactivate();
  721. GH.listInt.clear();
  722. GH.objsToBlit.clear();
  723. GH.statusbar = nullptr;
  724. logNetwork->infoStream() << "Removed GUI.";
  725. LOCPLINT = nullptr;
  726. };
  727. auto giveTurn = [&](PlayerColor player)
  728. {
  729. YourTurn yt;
  730. yt.player = player;
  731. yt.daysWithoutCastle = client->getPlayer(player)->daysWithoutCastle;
  732. yt.applyCl(client);
  733. };
  734. Settings session = settings.write["session"];
  735. if(cn == "autoskip")
  736. {
  737. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  738. }
  739. else if(cn == "gosolo")
  740. {
  741. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  742. if(!client)
  743. {
  744. std::cout << "Game in not active";
  745. return;
  746. }
  747. PlayerColor color;
  748. if(session["aiSolo"].Bool())
  749. {
  750. for(auto & elem : client->gameState()->players)
  751. {
  752. if(elem.second.human)
  753. client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  754. }
  755. }
  756. else
  757. {
  758. color = LOCPLINT->playerID;
  759. removeGUI();
  760. for(auto & elem : client->gameState()->players)
  761. {
  762. if(elem.second.human)
  763. {
  764. auto AiToGive = client->aiNameForPlayer(*client->getPlayerSettings(elem.first), false);
  765. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % elem.first % AiToGive;
  766. client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  767. }
  768. }
  769. GH.totalRedraw();
  770. giveTurn(color);
  771. }
  772. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  773. }
  774. else if(cn == "controlai")
  775. {
  776. std::string colorName;
  777. readed >> colorName;
  778. boost::to_lower(colorName);
  779. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  780. if(!client)
  781. {
  782. std::cout << "Game in not active";
  783. return;
  784. }
  785. PlayerColor color;
  786. if(LOCPLINT)
  787. color = LOCPLINT->playerID;
  788. for(auto & elem : client->gameState()->players)
  789. {
  790. if(elem.second.human || (colorName.length() &&
  791. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  792. {
  793. continue;
  794. }
  795. removeGUI();
  796. client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  797. }
  798. GH.totalRedraw();
  799. if(color != PlayerColor::NEUTRAL)
  800. giveTurn(color);
  801. }
  802. // Check mantis issue 2292 for details
  803. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  804. {
  805. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  806. LOCPLINT->cb->sendMessage(message);
  807. }*/
  808. }
  809. //plays intro, ends when intro is over or button has been pressed (handles events)
  810. void playIntro()
  811. {
  812. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true, true))
  813. {
  814. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true, true);
  815. }
  816. }
  817. void dispose()
  818. {
  819. if(VLC)
  820. {
  821. delete VLC;
  822. VLC = nullptr;
  823. }
  824. // cleanup, mostly to remove false leaks from analyzer
  825. CResourceHandler::clear();
  826. if(CCS)
  827. {
  828. CCS->musich->release();
  829. CCS->soundh->release();
  830. }
  831. CMessage::dispose();
  832. vstd::clear_pointer(graphics);
  833. if(console)
  834. {
  835. delete console; // should be removed after everything else since used by logging
  836. console = nullptr;
  837. }
  838. }
  839. static bool checkVideoMode(int monitorIndex, int w, int h)
  840. {
  841. //we only check that our desired window size fits on screen
  842. SDL_DisplayMode mode;
  843. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  844. {
  845. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  846. logGlobal->error(SDL_GetError());
  847. return false;
  848. }
  849. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  850. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  851. {
  852. return true;
  853. }
  854. return false;
  855. }
  856. static void cleanupRenderer()
  857. {
  858. screenBuf = nullptr; //it`s a link - just nullify
  859. if(nullptr != screen2)
  860. {
  861. SDL_FreeSurface(screen2);
  862. screen2 = nullptr;
  863. }
  864. if(nullptr != screen)
  865. {
  866. SDL_FreeSurface(screen);
  867. screen = nullptr;
  868. }
  869. if(nullptr != screenTexture)
  870. {
  871. SDL_DestroyTexture(screenTexture);
  872. screenTexture = nullptr;
  873. }
  874. if(nullptr != mainRenderer)
  875. {
  876. SDL_DestroyRenderer(mainRenderer);
  877. mainRenderer = nullptr;
  878. }
  879. if(nullptr != mainWindow)
  880. {
  881. SDL_DestroyWindow(mainWindow);
  882. mainWindow = nullptr;
  883. }
  884. }
  885. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  886. {
  887. // VCMI will only work with 2 or 4 bytes per pixel
  888. vstd::amax(bpp, 16);
  889. vstd::amin(bpp, 32);
  890. if(bpp>16)
  891. bpp = 32;
  892. if(displayIndex < 0)
  893. {
  894. if (mainWindow != nullptr)
  895. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  896. if (displayIndex < 0)
  897. displayIndex = 0;
  898. }
  899. if(!checkVideoMode(displayIndex, w, h))
  900. {
  901. logGlobal->errorStream() << "Error: SDL says that " << w << "x" << h << " resolution is not available!";
  902. return false;
  903. }
  904. bool bufOnScreen = (screenBuf == screen);
  905. cleanupRenderer();
  906. if(fullscreen)
  907. {
  908. //in full-screen mode always use desktop resolution
  909. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  910. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  911. }
  912. else
  913. {
  914. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  915. }
  916. if(nullptr == mainWindow)
  917. {
  918. throw std::runtime_error("Unable to create window\n");
  919. }
  920. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  921. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  922. if(nullptr == mainRenderer)
  923. {
  924. throw std::runtime_error("Unable to create renderer\n");
  925. }
  926. SDL_RendererInfo info;
  927. SDL_GetRendererInfo(mainRenderer,&info);
  928. logGlobal->infoStream() << "Created renderer " << info.name;
  929. SDL_RenderSetLogicalSize(mainRenderer, w, h);
  930. SDL_RenderSetViewport(mainRenderer, nullptr);
  931. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  932. int bmask = 0xff000000;
  933. int gmask = 0x00ff0000;
  934. int rmask = 0x0000ff00;
  935. int amask = 0x000000ff;
  936. #else
  937. int bmask = 0x000000ff;
  938. int gmask = 0x0000ff00;
  939. int rmask = 0x00ff0000;
  940. int amask = 0xFF000000;
  941. #endif
  942. screen = SDL_CreateRGBSurface(0,w,h,bpp,rmask,gmask,bmask,amask);
  943. if(nullptr == screen)
  944. {
  945. logGlobal->errorStream() << "Unable to create surface";
  946. logGlobal->errorStream() << w << " "<< h << " "<< bpp;
  947. logGlobal->errorStream() << SDL_GetError();
  948. throw std::runtime_error("Unable to create surface");
  949. }
  950. //No blending for screen itself. Required for proper cursor rendering.
  951. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  952. screenTexture = SDL_CreateTexture(mainRenderer,
  953. SDL_PIXELFORMAT_ARGB8888,
  954. SDL_TEXTUREACCESS_STREAMING,
  955. w, h);
  956. if(nullptr == screenTexture)
  957. {
  958. logGlobal->errorStream() << "Unable to create screen texture";
  959. logGlobal->errorStream() << SDL_GetError();
  960. throw std::runtime_error("Unable to create screen texture");
  961. }
  962. screen2 = CSDL_Ext::copySurface(screen);
  963. if(nullptr == screen2)
  964. {
  965. throw std::runtime_error("Unable to copy surface\n");
  966. }
  967. screenBuf = bufOnScreen ? screen : screen2;
  968. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  969. SDL_RenderClear(mainRenderer);
  970. SDL_RenderPresent(mainRenderer);
  971. return true;
  972. }
  973. //used only once during initialization
  974. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  975. {
  976. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  977. {
  978. throw std::runtime_error("Requested screen resolution is not available\n");
  979. }
  980. }
  981. static void fullScreenChanged()
  982. {
  983. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  984. Settings full = settings.write["video"]["fullscreen"];
  985. const bool toFullscreen = full->Bool();
  986. auto bitsPerPixel = screen->format->BitsPerPixel;
  987. auto w = screen->w;
  988. auto h = screen->h;
  989. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  990. {
  991. //will return false and report error if video mode is not supported
  992. return;
  993. }
  994. GH.totalRedraw();
  995. }
  996. static void handleEvent(SDL_Event & ev)
  997. {
  998. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  999. {
  1000. handleQuit();
  1001. return;
  1002. }
  1003. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  1004. {
  1005. Settings full = settings.write["video"]["fullscreen"];
  1006. full->Bool() = !full->Bool();
  1007. return;
  1008. }
  1009. else if(ev.type == SDL_USEREVENT)
  1010. {
  1011. switch(ev.user.code)
  1012. {
  1013. case FORCE_QUIT:
  1014. {
  1015. handleQuit(false);
  1016. return;
  1017. }
  1018. break;
  1019. case RETURN_TO_MAIN_MENU:
  1020. {
  1021. endGame();
  1022. GH.curInt = CGPreGame::create();
  1023. GH.defActionsDef = 63;
  1024. }
  1025. break;
  1026. case RESTART_GAME:
  1027. {
  1028. StartInfo si = *client->getStartInfo(true);
  1029. si.seedToBeUsed = 0; //server gives new random generator seed if 0
  1030. endGame();
  1031. startGame(&si);
  1032. }
  1033. break;
  1034. case PREPARE_RESTART_CAMPAIGN:
  1035. {
  1036. auto si = reinterpret_cast<StartInfo *>(ev.user.data1);
  1037. endGame();
  1038. startGame(si);
  1039. }
  1040. break;
  1041. case RETURN_TO_MENU_LOAD:
  1042. endGame();
  1043. CGPreGame::create();
  1044. GH.defActionsDef = 63;
  1045. CGP->update();
  1046. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  1047. GH.curInt = CGP;
  1048. break;
  1049. case FULLSCREEN_TOGGLED:
  1050. fullScreenChanged();
  1051. break;
  1052. default:
  1053. logGlobal->errorStream() << "Unknown user event. Code " << ev.user.code;
  1054. break;
  1055. }
  1056. return;
  1057. }
  1058. else if(ev.type == SDL_WINDOWEVENT)
  1059. {
  1060. switch (ev.window.event) {
  1061. case SDL_WINDOWEVENT_RESTORED:
  1062. fullScreenChanged();
  1063. break;
  1064. }
  1065. return;
  1066. }
  1067. {
  1068. boost::unique_lock<boost::mutex> lock(eventsM);
  1069. events.push(ev);
  1070. }
  1071. }
  1072. static void mainLoop()
  1073. {
  1074. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  1075. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
  1076. inGuiThread.reset(new bool(true));
  1077. GH.mainFPSmng->init();
  1078. while(1) //main SDL events loop
  1079. {
  1080. SDL_Event ev;
  1081. while(1 == SDL_PollEvent(&ev))
  1082. {
  1083. handleEvent(ev);
  1084. }
  1085. GH.renderFrame();
  1086. }
  1087. }
  1088. void startGame(StartInfo * options, CConnection *serv/* = nullptr*/)
  1089. {
  1090. serverAlive.waitWhileTrue();
  1091. serverAlive.setn(true);
  1092. if(vm.count("onlyAI"))
  1093. {
  1094. auto ais = vm.count("ai") ? vm["ai"].as<std::vector<std::string>>() : std::vector<std::string>();
  1095. int i = 0;
  1096. for(auto & elem : options->playerInfos)
  1097. {
  1098. elem.second.playerID = PlayerSettings::PLAYER_AI;
  1099. if(i < ais.size())
  1100. elem.second.name = ais[i++];
  1101. }
  1102. }
  1103. client = new CClient();
  1104. CPlayerInterface::howManyPeople = 0;
  1105. switch(options->mode) //new game
  1106. {
  1107. case StartInfo::NEW_GAME:
  1108. case StartInfo::CAMPAIGN:
  1109. case StartInfo::DUEL:
  1110. client->newGame(serv, options);
  1111. break;
  1112. case StartInfo::LOAD_GAME:
  1113. std::string fname = options->mapname;
  1114. boost::algorithm::erase_last(fname,".vlgm1");
  1115. if(!vm.count("loadplayer"))
  1116. client->loadGame(fname);
  1117. else
  1118. client->loadGame(fname,vm.count("loadserver"),vm.count("loadhumanplayerindices") ? vm["loadhumanplayerindices"].as<std::vector<int>>() : std::vector<int>(),vm.count("loadnumplayers") ? vm["loadnumplayers"].as<int>() : 1,vm["loadplayer"].as<int>(),vm.count("loadserverip") ? vm["loadserverip"].as<std::string>() : "", vm.count("loadserverport") ? vm["loadserverport"].as<std::string>() : "3030");
  1119. break;
  1120. }
  1121. client->connectionHandler = new boost::thread(&CClient::run, client);
  1122. }
  1123. void endGame()
  1124. {
  1125. client->endGame();
  1126. vstd::clear_pointer(client);
  1127. }
  1128. void handleQuit(bool ask/* = true*/)
  1129. {
  1130. auto quitApplication = []()
  1131. {
  1132. if(client)
  1133. endGame();
  1134. dispose();
  1135. vstd::clear_pointer(console);
  1136. boost::this_thread::sleep(boost::posix_time::milliseconds(750));
  1137. if(!gNoGUI)
  1138. {
  1139. cleanupRenderer();
  1140. SDL_Quit();
  1141. }
  1142. std::cout << "Ending...\n";
  1143. exit(0);
  1144. };
  1145. if(client && LOCPLINT && ask)
  1146. {
  1147. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  1148. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, 0);
  1149. }
  1150. else
  1151. {
  1152. quitApplication();
  1153. }
  1154. }