CMT.cpp 34 KB

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