CMT.cpp 36 KB

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