CMT.cpp 38 KB

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