CMT.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. // CMT.cpp : Defines the entry point for the console application.
  2. //
  3. #include "StdInc.h"
  4. #include <boost/filesystem/operations.hpp>
  5. #include <SDL_mixer.h>
  6. #include "UIFramework/SDL_Extensions.h"
  7. #include "CGameInfo.h"
  8. #include "mapHandler.h"
  9. #include "../lib/filesystem/CResourceLoader.h"
  10. #include "CPreGame.h"
  11. #include "CCastleInterface.h"
  12. #include "../lib/CConsoleHandler.h"
  13. #include "UIFramework/CCursorHandler.h"
  14. #include "../lib/CGameState.h"
  15. #include "../CCallback.h"
  16. #include "CPlayerInterface.h"
  17. #include "CAdvmapInterface.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "CVideoHandler.h"
  20. #include "../lib/CHeroHandler.h"
  21. #include "../lib/CCreatureHandler.h"
  22. #include "../lib/CSpellHandler.h"
  23. #include "CMusicHandler.h"
  24. #include "CVideoHandler.h"
  25. #include "CDefHandler.h"
  26. #include "../lib/CGeneralTextHandler.h"
  27. #include "Graphics.h"
  28. #include "Client.h"
  29. #include "../lib/CConfigHandler.h"
  30. #include "../lib/Connection.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/CObjectHandler.h"
  37. #include "../lib/CArtHandler.h"
  38. #include "../lib/CScriptingModule.h"
  39. #include "../lib/GameConstants.h"
  40. #include "UIFramework/CGuiHandler.h"
  41. #ifdef _WIN32
  42. #include "SDL_syswm.h"
  43. #endif
  44. #include "../lib/CDefObjInfoHandler.h"
  45. #include "../lib/UnlockGuard.h"
  46. #if __MINGW32__
  47. #undef main
  48. #endif
  49. namespace po = boost::program_options;
  50. /*
  51. * CMT.cpp, part of VCMI engine
  52. *
  53. * Authors: listed in file AUTHORS in main folder
  54. *
  55. * License: GNU General Public License v2.0 or later
  56. * Full text of license available in license.txt file, in main folder
  57. *
  58. */
  59. std::string NAME_AFFIX = "client";
  60. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  61. CGuiHandler GH;
  62. static CClient *client=NULL;
  63. SDL_Surface *screen = NULL, //main screen surface
  64. *screen2 = NULL,//and hlp surface (used to store not-active interfaces layer)
  65. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  66. static boost::thread *mainGUIThread;
  67. std::queue<SDL_Event> events;
  68. boost::mutex eventsM;
  69. static bool gOnlyAI = false;
  70. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  71. static bool ermInteractiveMode = false; //structurize when time is right
  72. void processCommand(const std::string &message);
  73. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo=true);
  74. void dispose();
  75. void playIntro();
  76. static void listenForEvents();
  77. //void requestChangingResolution();
  78. void startGame(StartInfo * options, CConnection *serv = NULL);
  79. #ifndef _WIN32
  80. #ifndef _GNU_SOURCE
  81. #define _GNU_SOURCE
  82. #endif
  83. #include <getopt.h>
  84. #endif
  85. void startGameFromFile(const std::string &fname)
  86. {
  87. if(fname.size() && boost::filesystem::exists(fname))
  88. {
  89. StartInfo si;
  90. CLoadFile out(fname);
  91. if(!out.sfile || !*out.sfile)
  92. {
  93. tlog1 << "Failed to open startfile, falling back to the main menu!\n";
  94. GH.curInt = CGPreGame::create();
  95. return;
  96. }
  97. out >> si;
  98. while(GH.topInt())
  99. GH.popIntTotally(GH.topInt());
  100. startGame(&si);
  101. }
  102. }
  103. void init()
  104. {
  105. CStopWatch tmh, pomtime;
  106. tlog0 << "\tInitializing minors: " << pomtime.getDiff() << std::endl;
  107. //initializing audio
  108. // Note: because of interface button range, volume can only be a
  109. // multiple of 11, from 0 to 99.
  110. CCS->soundh = new CSoundHandler;
  111. CCS->soundh->init();
  112. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  113. CCS->musich = new CMusicHandler;
  114. CCS->musich->init();
  115. CCS->musich->setVolume(settings["general"]["music"].Float());
  116. tlog0<<"\tInitializing sound: "<<pomtime.getDiff()<<std::endl;
  117. tlog0<<"Initializing screen and sound handling: "<<tmh.getDiff()<<std::endl;
  118. loadDLLClasses();
  119. const_cast<CGameInfo*>(CGI)->setFromLib();
  120. CCS->soundh->initSpellsSounds(CGI->spellh->spells);
  121. tlog0<<"Initializing VCMI_Lib: "<<tmh.getDiff()<<std::endl;
  122. pomtime.getDiff();
  123. CCS->curh = new CCursorHandler;
  124. CCS->curh->initCursor();
  125. CCS->curh->show();
  126. tlog0<<"Screen handler: "<<pomtime.getDiff()<<std::endl;
  127. pomtime.getDiff();
  128. graphics = new Graphics();
  129. graphics->loadHeroAnims();
  130. tlog0<<"\tMain graphics: "<<tmh.getDiff()<<std::endl;
  131. tlog0<<"Initializing game graphics: "<<tmh.getDiff()<<std::endl;
  132. CMessage::init();
  133. tlog0<<"Message handler: "<<tmh.getDiff()<<std::endl;
  134. //CPG = new CPreGame(); //main menu and submenus
  135. //tlog0<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
  136. }
  137. static void prog_version(void)
  138. {
  139. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  140. printf(" data directory: %s\n", VCMIDirs::get().dataPath().c_str());
  141. printf(" library directory: %s\n", VCMIDirs::get().libraryPath().c_str());
  142. printf(" path to server: %s\n", VCMIDirs::get().serverPath().c_str());
  143. }
  144. static void prog_help(const po::options_description &opts)
  145. {
  146. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  147. printf("Copyright (C) 2007-2012 VCMI dev team - see AUTHORS file\n");
  148. printf("This is free software; see the source for copying conditions. There is NO\n");
  149. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  150. printf("\n");
  151. printf("Usage:\n");
  152. std::cout << opts;
  153. // printf(" -h, --help display this help and exit\n");
  154. // printf(" -v, --version display version information and exit\n");
  155. }
  156. #ifdef __APPLE__
  157. void OSX_checkForUpdates();
  158. #endif
  159. #ifdef _WIN32
  160. int _tmain(int argc, _TCHAR* argv[])
  161. #elif defined(__APPLE__)
  162. int SDL_main(int argc, char *argv[])
  163. #else
  164. int main(int argc, char** argv)
  165. #endif
  166. {
  167. #ifdef __APPLE__
  168. // Correct working dir executable folder (not bundle folder) so we can use executable relative pathes
  169. std::string executablePath = argv[0];
  170. std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
  171. chdir(workDir.c_str());
  172. // Check for updates
  173. OSX_checkForUpdates();
  174. // Check that game data is prepared. Otherwise run vcmibuilder helper application
  175. FILE* check = fopen((VCMIDirs::get().localPath() + "/game_data_prepared").c_str(), "r");
  176. if (check == NULL) {
  177. system("open ./vcmibuilder.app");
  178. return 0;
  179. }
  180. fclose(check);
  181. #endif
  182. tlog0 << "Starting... " << std::endl;
  183. po::options_description opts("Allowed options");
  184. opts.add_options()
  185. ("help,h", "display help and exit")
  186. ("version,v", "display version information and exit")
  187. ("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
  188. ("start", po::value<std::string>(), "starts game from saved StartInfo file")
  189. ("onlyAI", "runs without GUI, all players will be default AI")
  190. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  191. ("autoSkip", "automatically skip turns in GUI")
  192. ("disable-video", "disable video player")
  193. ("nointro,i", "skips intro movies");
  194. po::variables_map vm;
  195. if(argc > 1)
  196. {
  197. try
  198. {
  199. po::store(po::parse_command_line(argc, argv, opts), vm);
  200. }
  201. catch(std::exception &e)
  202. {
  203. tlog1 << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  204. }
  205. }
  206. po::notify(vm);
  207. if(vm.count("help"))
  208. {
  209. prog_help(opts);
  210. return 0;
  211. }
  212. if(vm.count("version"))
  213. {
  214. prog_version();
  215. return 0;
  216. }
  217. //Set environment vars to make window centered. Sometimes work, sometimes not. :/
  218. putenv((char*)"SDL_VIDEO_WINDOW_POS");
  219. putenv((char*)"SDL_VIDEO_CENTERED=1");
  220. // Have effect on X11 system only (Linux).
  221. // For whatever reason in fullscreen mode SDL takes "raw" mouse input from DGA X11 extension
  222. // (DGA = Direct graphics access). Because this is raw input (before any speed\acceleration proceesing)
  223. // it may result in very small \ very fast mouse when game in fullscreen mode
  224. putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0");
  225. CStopWatch total, pomtime;
  226. std::cout.flags(std::ios::unitbuf);
  227. logfile = new std::ofstream((VCMIDirs::get().localPath() + "/VCMI_Client_log.txt").c_str());
  228. console = new CConsoleHandler;
  229. *console->cb = boost::bind(&processCommand, _1);
  230. console->start();
  231. atexit(dispose);
  232. tlog0 <<"Creating console and logfile: "<<pomtime.getDiff() << std::endl;
  233. preinitDLL(::console, logfile);
  234. // Some basic data validation to produce better error messages in cases of incorrect install
  235. auto testFile = [](std::string filename, std::string message) -> bool
  236. {
  237. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  238. return true;
  239. tlog1 << "Error: " << message << " was not found!\n";
  240. return false;
  241. };
  242. if (!testFile("DATA/HELP.TXT", "Heroes III data") &&
  243. !testFile("DATA/ZELP.TXT", "In the Wake of Gods data") &&
  244. !testFile("MODS/VCMI/MOD.JSON", "VCMI mod") &&
  245. !testFile("DATA/StackQueueBgBig.PCX", "VCMI data"))
  246. exit(1); // These are unrecoverable errors
  247. // these two are optional + some installs have them on CD and not in data directory
  248. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  249. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  250. settings.init();
  251. conf.init();
  252. tlog0 <<"Loading settings: "<<pomtime.getDiff() << std::endl;
  253. tlog0 << NAME << std::endl;
  254. srand ( time(NULL) );
  255. CCS = new CClientState;
  256. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  257. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  258. {
  259. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  260. exit(-1);
  261. }
  262. atexit(SDL_Quit);
  263. const JsonNode& video = settings["video"];
  264. const JsonNode& res = video["screenRes"];
  265. //something is really wrong...
  266. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  267. {
  268. tlog0 << "Fatal error: failed to load settings!\n";
  269. tlog0 << "Possible reasons:\n";
  270. tlog0 << "\tCorrupted local configuration file at " << VCMIDirs::get().localPath() << "/config/settings.json\n";
  271. tlog0 << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().dataPath() << "/config/schemas/settings.json\n";
  272. tlog0 << "VCMI will now exit...\n";
  273. exit(EXIT_FAILURE);
  274. }
  275. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  276. tlog0 <<"\tInitializing screen: "<<pomtime.getDiff() << std::endl;
  277. // Initialize video
  278. #if DISABLE_VIDEO
  279. CCS->videoh = new CEmptyVideoPlayer;
  280. #else
  281. if (!vm.count("disable-video"))
  282. CCS->videoh = new CVideoPlayer;
  283. else
  284. CCS->videoh = new CEmptyVideoPlayer;
  285. #endif
  286. tlog0<<"\tInitializing video: "<<pomtime.getDiff()<<std::endl;
  287. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  288. boost::thread loading(init);
  289. if(!vm.count("battle") && !vm.count("nointro"))
  290. playIntro();
  291. SDL_FillRect(screen,NULL,0);
  292. CSDL_Ext::update(screen);
  293. loading.join();
  294. tlog0<<"Initialization of VCMI (together): "<<total.getDiff()<<std::endl;
  295. if(!vm.count("battle"))
  296. {
  297. gOnlyAI = vm.count("onlyAI");
  298. Settings session = settings.write["session"];
  299. session["autoSkip"].Bool() = vm.count("autoSkip");
  300. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  301. std::string fileToStartFrom; //none by default
  302. if(vm.count("start"))
  303. fileToStartFrom = vm["start"].as<std::string>();
  304. if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
  305. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
  306. else
  307. {
  308. if(fileToStartFrom.size())
  309. {
  310. tlog3 << "Warning: cannot find given file to start from (" << fileToStartFrom
  311. << "). Falling back to main menu.\n";
  312. }
  313. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  314. }
  315. }
  316. else
  317. {
  318. StartInfo *si = new StartInfo();
  319. si->mode = StartInfo::DUEL;
  320. si->mapname = vm["battle"].as<std::string>();
  321. si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
  322. si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
  323. startGame(si);
  324. }
  325. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  326. listenForEvents();
  327. return 0;
  328. }
  329. void printInfoAboutIntObject(const CIntObject *obj, int level)
  330. {
  331. tlog4 << std::string(level, '\t');
  332. tlog4 << typeid(*obj).name() << " *** ";
  333. if (obj->active)
  334. {
  335. #define PRINT(check, text) if (obj->active & CIntObject::check) tlog4 << text
  336. PRINT(LCLICK, 'L');
  337. PRINT(RCLICK, 'R');
  338. PRINT(HOVER, 'H');
  339. PRINT(MOVE, 'M');
  340. PRINT(KEYBOARD, 'K');
  341. PRINT(TIME, 'T');
  342. PRINT(GENERAL, 'A');
  343. PRINT(WHEEL, 'W');
  344. PRINT(DOUBLECLICK, 'D');
  345. #undef PRINT
  346. }
  347. else
  348. tlog4 << "inactive";
  349. tlog4 << " at " << obj->pos.x <<"x"<< obj->pos.y;
  350. tlog4 << " (" << obj->pos.w <<"x"<< obj->pos.h << ")\n";
  351. BOOST_FOREACH(const CIntObject *child, obj->children)
  352. printInfoAboutIntObject(child, level+1);
  353. }
  354. void processCommand(const std::string &message)
  355. {
  356. std::istringstream readed;
  357. readed.str(message);
  358. std::string cn; //command name
  359. readed >> cn;
  360. if(LOCPLINT && LOCPLINT->cingconsole)
  361. LOCPLINT->cingconsole->print(message);
  362. if(ermInteractiveMode)
  363. {
  364. if(cn == "exit")
  365. {
  366. ermInteractiveMode = false;
  367. return;
  368. }
  369. else
  370. {
  371. if(client && client->erm)
  372. client->erm->executeUserCommand(message);
  373. tlog0 << "erm>";
  374. }
  375. }
  376. else if(message==std::string("die, fool"))
  377. {
  378. exit(EXIT_SUCCESS);
  379. }
  380. else if(cn == "erm")
  381. {
  382. ermInteractiveMode = true;
  383. tlog0 << "erm>";
  384. }
  385. else if(cn==std::string("activate"))
  386. {
  387. int what;
  388. readed >> what;
  389. switch (what)
  390. {
  391. case 0:
  392. GH.topInt()->activate();
  393. break;
  394. case 1:
  395. adventureInt->activate();
  396. break;
  397. case 2:
  398. LOCPLINT->castleInt->activate();
  399. break;
  400. }
  401. }
  402. else if(cn=="redraw")
  403. {
  404. GH.totalRedraw();
  405. }
  406. else if(cn=="screen")
  407. {
  408. tlog0 << "Screenbuf points to ";
  409. if(screenBuf == screen)
  410. tlog1 << "screen";
  411. else if(screenBuf == screen2)
  412. tlog1 << "screen2";
  413. else
  414. tlog1 << "?!?";
  415. tlog1 << std::endl;
  416. SDL_SaveBMP(screen, "Screen_c.bmp");
  417. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  418. }
  419. else if(cn=="save")
  420. {
  421. std::string fname;
  422. readed >> fname;
  423. client->save(fname);
  424. }
  425. else if(cn=="load")
  426. {
  427. // TODO: this code should end the running game and manage to call startGame instead
  428. std::string fname;
  429. readed >> fname;
  430. client->loadGame(fname);
  431. }/*
  432. else if(cn=="resolution" || cn == "r")
  433. {
  434. if(LOCPLINT)
  435. {
  436. tlog1 << "Resolution can be set only before starting the game.\n";
  437. return;
  438. }
  439. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  440. int i=1;
  441. tlog4 << "Available screen resolutions:\n";
  442. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  443. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  444. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  445. std::cin >> i;
  446. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  447. {
  448. std::cin.clear();
  449. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  450. }
  451. else if(!i)
  452. {
  453. return;
  454. }
  455. else
  456. {
  457. auto j = conf.guiOptions.begin();
  458. std::advance(j, i - 1); //move j to the i-th resolution info
  459. const int w = j->first.first, h = j->first.second;
  460. Settings screen = settings.write["video"]["screenRes"];
  461. screen["width"].Float() = w;
  462. screen["height"].Float() = h;
  463. conf.SetResolution(screen["width"].Float(), screen["height"].Float());
  464. tlog0 << "Screen resolution set to " << (int)screen["width"].Float() << " x "
  465. << (int)screen["height"].Float() <<". It will be applied afters game restart.\n";
  466. }
  467. }*/
  468. else if(message=="get txt")
  469. {
  470. tlog0<<"Command accepted.\t";
  471. boost::filesystem::create_directory("Extracted_txts");
  472. auto iterator = CResourceHandler::get()->getIterator([](const ResourceID & ident)
  473. {
  474. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  475. });
  476. std::string basePath = CResourceHandler::get()->getResourceName(ResourceID("DATA")) + "/Extracted_txts/";
  477. while (iterator.hasNext())
  478. {
  479. std::ofstream file(basePath + iterator->getName() + ".TXT");
  480. auto text = CResourceHandler::get()->loadData(*iterator);
  481. file.write((char*)text.first.get(), text.second);
  482. ++iterator;
  483. }
  484. tlog0 << "\rExtracting done :)\n";
  485. tlog0 << " Extracted files can be found in " << basePath << " directory\n";
  486. }
  487. else if(cn=="crash")
  488. {
  489. int *ptr = NULL;
  490. *ptr = 666;
  491. //disaster!
  492. }
  493. else if(cn == "onlyai")
  494. {
  495. gOnlyAI = true;
  496. }
  497. else if (cn == "ai")
  498. {
  499. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  500. tlog4 << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  501. }
  502. else if(cn == "mp" && adventureInt)
  503. {
  504. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  505. tlog0 << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  506. }
  507. else if(cn == "bonuses")
  508. {
  509. tlog0 << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  510. << adventureInt->selection->getBonusList() << std::endl;
  511. tlog0 << "\nInherited bonuses:\n";
  512. TCNodes parents;
  513. adventureInt->selection->getParents(parents);
  514. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  515. {
  516. tlog0 << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  517. }
  518. }
  519. else if(cn == "not dialog")
  520. {
  521. LOCPLINT->showingDialog->setn(false);
  522. }
  523. else if(cn == "gui")
  524. {
  525. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  526. {
  527. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  528. printInfoAboutIntObject(obj, 0);
  529. else
  530. tlog4 << typeid(*obj).name() << std::endl;
  531. }
  532. }
  533. else if(cn=="tell")
  534. {
  535. std::string what;
  536. int id1, id2;
  537. readed >> what >> id1 >> id2;
  538. if(what == "hs")
  539. {
  540. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  541. if(h->type->ID == id1)
  542. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  543. tlog4 << a->nodeName();
  544. }
  545. }
  546. else if (cn == "set")
  547. {
  548. std::string what, value;
  549. readed >> what;
  550. Settings conf = settings.write["session"][what];
  551. readed >> value;
  552. if (value == "on")
  553. conf->Bool() = true;
  554. else if (value == "off")
  555. conf->Bool() = false;
  556. }
  557. else if(cn == "sinfo")
  558. {
  559. std::string fname;
  560. readed >> fname;
  561. if(fname.size() && SEL)
  562. {
  563. CSaveFile out(fname);
  564. out << SEL->sInfo;
  565. }
  566. }
  567. else if(cn == "start")
  568. {
  569. std::string fname;
  570. readed >> fname;
  571. startGameFromFile(fname);
  572. }
  573. else if(cn == "unlock")
  574. {
  575. std::string mxname;
  576. readed >> mxname;
  577. if(mxname == "pim" && LOCPLINT)
  578. LOCPLINT->pim->unlock();
  579. }
  580. else if(cn == "setBattleAI")
  581. {
  582. std::string fname;
  583. readed >> fname;
  584. tlog0 << "Will try loading that AI to see if it is correct name...\n";
  585. try
  586. {
  587. 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
  588. {
  589. delete ai;
  590. Settings neutralAI = settings.write["server"]["neutralAI"];
  591. neutralAI->String() = fname;
  592. tlog0 << "Setting changed, from now the battle ai will be " << fname << "!\n";
  593. }
  594. }
  595. catch(std::exception &e)
  596. {
  597. tlog3 << "Failed opening " << fname << ": " << e.what() << std::endl;
  598. tlog3 << "Setting not changes, AI not found or invalid!\n";
  599. }
  600. }
  601. else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  602. {
  603. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  604. LOCPLINT->cb->sendMessage(message);
  605. }
  606. }
  607. //plays intro, ends when intro is over or button has been pressed (handles events)
  608. void playIntro()
  609. {
  610. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  611. {
  612. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  613. }
  614. }
  615. void dispose()
  616. {
  617. if (console)
  618. delete console;
  619. delete logfile;
  620. }
  621. //used only once during initialization
  622. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo)
  623. {
  624. // VCMI will only work with 2, 3 or 4 bytes per pixel
  625. vstd::amax(bpp, 16);
  626. vstd::amin(bpp, 32);
  627. // Try to use the best screen depth for the display
  628. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  629. if(suggestedBpp == 0)
  630. {
  631. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  632. return;
  633. }
  634. bool bufOnScreen = (screenBuf == screen);
  635. if(suggestedBpp != bpp)
  636. {
  637. tlog2 << "Note: SDL suggests to use " << suggestedBpp << " bpp instead of" << bpp << " bpp " << std::endl;
  638. }
  639. //For some reason changing fullscreen via config window checkbox result in SDL_Quit event
  640. if (resetVideo)
  641. {
  642. if(screen) //screen has been already initialized
  643. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  644. SDL_InitSubSystem(SDL_INIT_VIDEO);
  645. }
  646. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  647. {
  648. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  649. throw std::runtime_error("Requested screen resolution is not available\n");
  650. }
  651. tlog0 << "New screen flags: " << screen->flags << std::endl;
  652. if(screen2)
  653. SDL_FreeSurface(screen2);
  654. screen2 = CSDL_Ext::copySurface(screen);
  655. SDL_EnableUNICODE(1);
  656. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  657. SDL_ShowCursor(SDL_DISABLE);
  658. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  659. #ifdef _WIN32
  660. SDL_SysWMinfo wm;
  661. SDL_VERSION(&wm.version);
  662. int getwm = SDL_GetWMInfo(&wm);
  663. if(getwm == 1)
  664. {
  665. int sw = GetSystemMetrics(SM_CXSCREEN),
  666. sh = GetSystemMetrics(SM_CYSCREEN);
  667. RECT curpos;
  668. GetWindowRect(wm.window,&curpos);
  669. int ourw = curpos.right - curpos.left,
  670. ourh = curpos.bottom - curpos.top;
  671. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  672. }
  673. else
  674. {
  675. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  676. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  677. tlog3 << "Window won't be centered.\n";
  678. }
  679. #endif
  680. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  681. screenBuf = bufOnScreen ? screen : screen2;
  682. //setResolution = true;
  683. }
  684. static void fullScreenChanged()
  685. {
  686. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  687. Settings full = settings.write["video"]["fullscreen"];
  688. const bool toFullscreen = full->Bool();
  689. int bitsPerPixel = screen->format->BitsPerPixel;
  690. bitsPerPixel = SDL_VideoModeOK(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  691. if(bitsPerPixel == 0)
  692. {
  693. tlog1 << "Error: SDL says that " << screen->w << "x" << screen->h << " resolution is not available!\n";
  694. return;
  695. }
  696. bool bufOnScreen = (screenBuf == screen);
  697. screen = SDL_SetVideoMode(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  698. screenBuf = bufOnScreen ? screen : screen2;
  699. GH.totalRedraw();
  700. }
  701. static void listenForEvents()
  702. {
  703. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  704. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
  705. while(1) //main SDL events loop
  706. {
  707. SDL_Event ev;
  708. //tlog0 << "Waiting... ";
  709. int ret = SDL_WaitEvent(&ev);
  710. //tlog0 << "got " << (int)ev.type;
  711. if (ret == 0 || (ev.type==SDL_QUIT) ||
  712. (ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  713. {
  714. if (client)
  715. client->endGame();
  716. if (mainGUIThread)
  717. {
  718. GH.terminate = true;
  719. mainGUIThread->join();
  720. delete mainGUIThread;
  721. mainGUIThread = NULL;
  722. }
  723. delete console;
  724. console = NULL;
  725. SDL_Delay(750);
  726. SDL_Quit();
  727. tlog0 << "Ending...\n";
  728. break;
  729. }
  730. else if(LOCPLINT && ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  731. {
  732. Settings full = settings.write["video"]["fullscreen"];
  733. full->Bool() = !full->Bool();
  734. continue;
  735. }
  736. else if(ev.type == SDL_USEREVENT)
  737. {
  738. auto endGame = []
  739. {
  740. client->endGame();
  741. vstd::clear_pointer(client);
  742. delete CGI->dobjinfo.get();
  743. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  744. VLC->dobjinfo = const_cast<CGameInfo*>(CGI)->dobjinfo; // update dobjinfo pointer in VLC (used by modHandler::reload())
  745. const_cast<CGameInfo*>(CGI)->dobjinfo->load();
  746. const_cast<CGameInfo*>(CGI)->modh->reload(); //add info about new creatures to dobjinfo
  747. };
  748. switch(ev.user.code)
  749. {
  750. /* case CHANGE_SCREEN_RESOLUTION:
  751. {
  752. tlog0 << "Changing resolution has been requested\n";
  753. const JsonNode& video = settings["video"];
  754. const JsonNode& res = video["gameRes"];
  755. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  756. break;
  757. }*/
  758. case RETURN_TO_MAIN_MENU:
  759. {
  760. // StartInfo si = *client->getStartInfo();
  761. // if(si.mode == StartInfo::CAMPAIGN)
  762. // GH.pushInt( new CBonusSelection(si.campState) );
  763. // else
  764. {
  765. endGame();
  766. GH.curInt = CGPreGame::create();;
  767. GH.defActionsDef = 63;
  768. }
  769. }
  770. break;
  771. case STOP_CLIENT:
  772. client->endGame(false);
  773. break;
  774. case RESTART_GAME:
  775. {
  776. StartInfo si = *client->getStartInfo(true);
  777. endGame();
  778. startGame(&si);
  779. }
  780. break;
  781. case RETURN_TO_MENU_LOAD:
  782. endGame();
  783. CGPreGame::create();
  784. GH.defActionsDef = 63;
  785. CGP->update();
  786. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  787. GH.curInt = CGP;
  788. break;
  789. case FULLSCREEN_TOGGLED:
  790. fullScreenChanged();
  791. break;
  792. default:
  793. tlog1 << "Error: unknown user event. Code " << ev.user.code << std::endl;
  794. assert(0);
  795. }
  796. continue;
  797. }
  798. //tlog0 << " pushing ";
  799. {
  800. boost::unique_lock<boost::mutex> lock(eventsM);
  801. events.push(ev);
  802. }
  803. //tlog0 << " done\n";
  804. }
  805. }
  806. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  807. {
  808. if(gOnlyAI)
  809. {
  810. for(auto it = options->playerInfos.begin(); it != options->playerInfos.end(); ++it)
  811. {
  812. it->second.playerID = PlayerSettings::PLAYER_AI;
  813. }
  814. }
  815. /* const JsonNode& res = settings["video"]["screenRes"];
  816. if(screen->w != res["width"].Float() || screen->h != res["height"].Float())
  817. {
  818. requestChangingResolution();
  819. //allow event handling thread change resolution
  820. auto unlock = vstd::makeUnlockGuard(eventsM);
  821. while(!setResolution) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  822. }
  823. else
  824. setResolution = true;*/
  825. client = new CClient;
  826. CPlayerInterface::howManyPeople = 0;
  827. switch(options->mode) //new game
  828. {
  829. case StartInfo::NEW_GAME:
  830. case StartInfo::CAMPAIGN:
  831. case StartInfo::DUEL:
  832. client->newGame(serv, options);
  833. break;
  834. case StartInfo::LOAD_GAME:
  835. std::string fname = options->mapname;
  836. boost::algorithm::erase_last(fname,".vlgm1");
  837. client->loadGame(fname);
  838. break;
  839. }
  840. client->connectionHandler = new boost::thread(&CClient::run, client);
  841. }
  842. /*
  843. void requestChangingResolution()
  844. {
  845. //mark that we are going to change resolution
  846. setResolution = false;
  847. //push special event to order event reading thread to change resolution
  848. SDL_Event ev;
  849. ev.type = SDL_USEREVENT;
  850. ev.user.code = CHANGE_SCREEN_RESOLUTION;
  851. SDL_PushEvent(&ev);
  852. }
  853. */