CMT.cpp 24 KB

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