CMT.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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 "gui/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 "gui/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/CTownHandler.h"
  37. #include "../lib/CObjectHandler.h"
  38. #include "../lib/CArtHandler.h"
  39. #include "../lib/CScriptingModule.h"
  40. #include "../lib/GameConstants.h"
  41. #include "gui/CGuiHandler.h"
  42. #include "../lib/logging/CBasicLogConfigurator.h"
  43. #ifdef _WIN32
  44. #include "SDL_syswm.h"
  45. #endif
  46. #include "../lib/CDefObjInfoHandler.h"
  47. #include "../lib/UnlockGuard.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=NULL;
  65. SDL_Surface *screen = NULL, //main screen surface
  66. *screen2 = NULL,//and hlp surface (used to store not-active interfaces layer)
  67. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  68. static boost::thread *mainGUIThread;
  69. std::queue<SDL_Event> events;
  70. boost::mutex eventsM;
  71. static bool gOnlyAI = false;
  72. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  73. static bool ermInteractiveMode = false; //structurize when time is right
  74. void processCommand(const std::string &message);
  75. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo=true);
  76. void dispose();
  77. void playIntro();
  78. static void listenForEvents();
  79. //void requestChangingResolution();
  80. void startGame(StartInfo * options, CConnection *serv = NULL);
  81. #ifndef _WIN32
  82. #ifndef _GNU_SOURCE
  83. #define _GNU_SOURCE
  84. #endif
  85. #include <getopt.h>
  86. #endif
  87. void startGameFromFile(const std::string &fname)
  88. {
  89. if(fname.size() && boost::filesystem::exists(fname))
  90. {
  91. StartInfo si;
  92. CLoadFile out(fname);
  93. if(!out.sfile || !*out.sfile)
  94. {
  95. logGlobal->errorStream() << "Failed to open startfile, falling back to the main menu!";
  96. GH.curInt = CGPreGame::create();
  97. return;
  98. }
  99. out >> si;
  100. while(GH.topInt())
  101. GH.popIntTotally(GH.topInt());
  102. startGame(&si);
  103. }
  104. }
  105. void init()
  106. {
  107. CStopWatch tmh, pomtime;
  108. logGlobal->infoStream() << "\tInitializing minors: " << pomtime.getDiff();
  109. //initializing audio
  110. // Note: because of interface button range, volume can only be a
  111. // multiple of 11, from 0 to 99.
  112. CCS->soundh = new CSoundHandler;
  113. CCS->soundh->init();
  114. CCS->soundh->setVolume(settings["general"]["sound"].Float());
  115. CCS->musich = new CMusicHandler;
  116. CCS->musich->init();
  117. CCS->musich->setVolume(settings["general"]["music"].Float());
  118. logGlobal->infoStream()<<"\tInitializing sound: "<<pomtime.getDiff();
  119. logGlobal->infoStream()<<"Initializing screen and sound handling: "<<tmh.getDiff();
  120. loadDLLClasses();
  121. const_cast<CGameInfo*>(CGI)->setFromLib();
  122. CCS->soundh->initSpellsSounds(CGI->spellh->spells);
  123. logGlobal->infoStream()<<"Initializing VCMI_Lib: "<<tmh.getDiff();
  124. pomtime.getDiff();
  125. CCS->curh = new CCursorHandler;
  126. CCS->curh->initCursor();
  127. CCS->curh->show();
  128. logGlobal->infoStream()<<"Screen handler: "<<pomtime.getDiff();
  129. pomtime.getDiff();
  130. graphics = new Graphics();
  131. graphics->loadHeroAnims();
  132. logGlobal->infoStream()<<"\tMain graphics: "<<tmh.getDiff();
  133. logGlobal->infoStream()<<"Initializing game graphics: "<<tmh.getDiff();
  134. CMessage::init();
  135. logGlobal->infoStream()<<"Message handler: "<<tmh.getDiff();
  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 wmain(int argc, wchar_t* 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. std::cout << "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. std::cerr << "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. // Init old logging system and new (temporary) logging system
  226. CStopWatch total, pomtime;
  227. std::cout.flags(std::ios::unitbuf);
  228. console = new CConsoleHandler;
  229. *console->cb = boost::bind(&processCommand, _1);
  230. console->start();
  231. atexit(dispose);
  232. CBasicLogConfigurator logConfig(VCMIDirs::get().localPath() + "/VCMI_Client_log.txt", console);
  233. logConfig.configureDefault();
  234. logGlobal->infoStream() <<"Creating console "<<pomtime.getDiff();
  235. // Init filesystem and settings
  236. preinitDLL(::console);
  237. settings.init();
  238. // Initialize logging based on settings
  239. logConfig.configure();
  240. // Some basic data validation to produce better error messages in cases of incorrect install
  241. auto testFile = [](std::string filename, std::string message) -> bool
  242. {
  243. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  244. return true;
  245. logGlobal->errorStream() << "Error: " << message << " was not found!";
  246. return false;
  247. };
  248. if (!testFile("DATA/HELP.TXT", "Heroes III data") &&
  249. !testFile("DATA/ZELP.TXT", "In the Wake of Gods data") &&
  250. !testFile("MODS/VCMI/MOD.JSON", "VCMI mod") &&
  251. !testFile("DATA/StackQueueBgBig.PCX", "VCMI data"))
  252. exit(1); // These are unrecoverable errors
  253. // these two are optional + some installs have them on CD and not in data directory
  254. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  255. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  256. conf.init();
  257. logGlobal->infoStream() <<"Loading settings: "<<pomtime.getDiff();
  258. logGlobal->infoStream() << NAME;
  259. srand ( time(NULL) );
  260. CCS = new CClientState;
  261. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  262. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  263. {
  264. logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
  265. exit(-1);
  266. }
  267. atexit(SDL_Quit);
  268. const JsonNode& video = settings["video"];
  269. const JsonNode& res = video["screenRes"];
  270. //something is really wrong...
  271. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  272. {
  273. logGlobal->errorStream() << "Fatal error: failed to load settings!";
  274. logGlobal->errorStream() << "Possible reasons:";
  275. logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().localPath() << "/config/settings.json";
  276. logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().dataPath() << "/config/schemas/settings.json";
  277. logGlobal->errorStream() << "VCMI will now exit...";
  278. exit(EXIT_FAILURE);
  279. }
  280. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  281. logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
  282. // Initialize video
  283. #if DISABLE_VIDEO
  284. CCS->videoh = new CEmptyVideoPlayer;
  285. #else
  286. if (!vm.count("disable-video"))
  287. CCS->videoh = new CVideoPlayer;
  288. else
  289. CCS->videoh = new CEmptyVideoPlayer;
  290. #endif
  291. logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();
  292. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  293. boost::thread loading(init);
  294. if(!vm.count("battle") && !vm.count("nointro"))
  295. playIntro();
  296. SDL_FillRect(screen,NULL,0);
  297. CSDL_Ext::update(screen);
  298. loading.join();
  299. logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();
  300. if(!vm.count("battle"))
  301. {
  302. gOnlyAI = vm.count("onlyAI");
  303. Settings session = settings.write["session"];
  304. session["autoSkip"].Bool() = vm.count("autoSkip");
  305. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  306. std::string fileToStartFrom; //none by default
  307. if(vm.count("start"))
  308. fileToStartFrom = vm["start"].as<std::string>();
  309. if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
  310. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
  311. else
  312. {
  313. if(fileToStartFrom.size())
  314. {
  315. logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
  316. << "). Falling back to main menu.";
  317. }
  318. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  319. }
  320. }
  321. else
  322. {
  323. StartInfo *si = new StartInfo();
  324. si->mode = StartInfo::DUEL;
  325. si->mapname = vm["battle"].as<std::string>();
  326. si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
  327. si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
  328. startGame(si);
  329. }
  330. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  331. listenForEvents();
  332. return 0;
  333. }
  334. void printInfoAboutIntObject(const CIntObject *obj, int level)
  335. {
  336. std::stringstream sbuffer;
  337. sbuffer << std::string(level, '\t');
  338. sbuffer << typeid(*obj).name() << " *** ";
  339. if (obj->active)
  340. {
  341. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  342. PRINT(LCLICK, 'L');
  343. PRINT(RCLICK, 'R');
  344. PRINT(HOVER, 'H');
  345. PRINT(MOVE, 'M');
  346. PRINT(KEYBOARD, 'K');
  347. PRINT(TIME, 'T');
  348. PRINT(GENERAL, 'A');
  349. PRINT(WHEEL, 'W');
  350. PRINT(DOUBLECLICK, 'D');
  351. #undef PRINT
  352. }
  353. else
  354. sbuffer << "inactive";
  355. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  356. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  357. logGlobal->debugStream() << sbuffer.str();
  358. BOOST_FOREACH(const CIntObject *child, obj->children)
  359. printInfoAboutIntObject(child, level+1);
  360. }
  361. void processCommand(const std::string &message)
  362. {
  363. std::istringstream readed;
  364. readed.str(message);
  365. std::string cn; //command name
  366. readed >> cn;
  367. if(LOCPLINT && LOCPLINT->cingconsole)
  368. LOCPLINT->cingconsole->print(message);
  369. if(ermInteractiveMode)
  370. {
  371. if(cn == "exit")
  372. {
  373. ermInteractiveMode = false;
  374. return;
  375. }
  376. else
  377. {
  378. if(client && client->erm)
  379. client->erm->executeUserCommand(message);
  380. std::cout << "erm>";
  381. }
  382. }
  383. else if(message==std::string("die, fool"))
  384. {
  385. exit(EXIT_SUCCESS);
  386. }
  387. else if(cn == "erm")
  388. {
  389. ermInteractiveMode = true;
  390. std::cout << "erm>";
  391. }
  392. else if(cn==std::string("activate"))
  393. {
  394. int what;
  395. readed >> what;
  396. switch (what)
  397. {
  398. case 0:
  399. GH.topInt()->activate();
  400. break;
  401. case 1:
  402. adventureInt->activate();
  403. break;
  404. case 2:
  405. LOCPLINT->castleInt->activate();
  406. break;
  407. }
  408. }
  409. else if(cn=="redraw")
  410. {
  411. GH.totalRedraw();
  412. }
  413. else if(cn=="screen")
  414. {
  415. std::cout << "Screenbuf points to ";
  416. if(screenBuf == screen)
  417. logGlobal->errorStream() << "screen";
  418. else if(screenBuf == screen2)
  419. logGlobal->errorStream() << "screen2";
  420. else
  421. logGlobal->errorStream() << "?!?";
  422. SDL_SaveBMP(screen, "Screen_c.bmp");
  423. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  424. }
  425. else if(cn=="save")
  426. {
  427. std::string fname;
  428. readed >> fname;
  429. client->save(fname);
  430. }
  431. else if(cn=="load")
  432. {
  433. // TODO: this code should end the running game and manage to call startGame instead
  434. std::string fname;
  435. readed >> fname;
  436. client->loadGame(fname);
  437. }
  438. else if(message=="get txt")
  439. {
  440. std::cout<<"Command accepted.\t";
  441. boost::filesystem::create_directory("Extracted_txts");
  442. auto iterator = CResourceHandler::get()->getIterator([](const ResourceID & ident)
  443. {
  444. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  445. });
  446. std::string basePath = CResourceHandler::get()->getResourceName(ResourceID("DATA")) + "/Extracted_txts/";
  447. while (iterator.hasNext())
  448. {
  449. std::ofstream file(basePath + iterator->getName() + ".TXT");
  450. auto text = CResourceHandler::get()->loadData(*iterator);
  451. file.write((char*)text.first.get(), text.second);
  452. ++iterator;
  453. }
  454. std::cout << "\rExtracting done :)\n";
  455. std::cout << " Extracted files can be found in " << basePath << " directory\n";
  456. }
  457. else if(cn=="crash")
  458. {
  459. int *ptr = NULL;
  460. *ptr = 666;
  461. //disaster!
  462. }
  463. else if(cn == "onlyai")
  464. {
  465. gOnlyAI = true;
  466. }
  467. else if (cn == "ai")
  468. {
  469. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  470. std::cout << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  471. }
  472. else if(cn == "mp" && adventureInt)
  473. {
  474. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  475. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  476. }
  477. else if(cn == "bonuses")
  478. {
  479. std::cout << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  480. << adventureInt->selection->getBonusList() << std::endl;
  481. std::cout << "\nInherited bonuses:\n";
  482. TCNodes parents;
  483. adventureInt->selection->getParents(parents);
  484. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  485. {
  486. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  487. }
  488. }
  489. else if(cn == "not dialog")
  490. {
  491. LOCPLINT->showingDialog->setn(false);
  492. }
  493. else if(cn == "gui")
  494. {
  495. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  496. {
  497. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  498. printInfoAboutIntObject(obj, 0);
  499. else
  500. std::cout << typeid(*obj).name() << std::endl;
  501. }
  502. }
  503. else if(cn=="tell")
  504. {
  505. std::string what;
  506. int id1, id2;
  507. readed >> what >> id1 >> id2;
  508. if(what == "hs")
  509. {
  510. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  511. if(h->type->ID == id1)
  512. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  513. std::cout << a->nodeName();
  514. }
  515. }
  516. else if (cn == "set")
  517. {
  518. std::string what, value;
  519. readed >> what;
  520. Settings conf = settings.write["session"][what];
  521. readed >> value;
  522. if (value == "on")
  523. conf->Bool() = true;
  524. else if (value == "off")
  525. conf->Bool() = false;
  526. }
  527. else if(cn == "sinfo")
  528. {
  529. std::string fname;
  530. readed >> fname;
  531. if(fname.size() && SEL)
  532. {
  533. CSaveFile out(fname);
  534. out << SEL->sInfo;
  535. }
  536. }
  537. else if(cn == "start")
  538. {
  539. std::string fname;
  540. readed >> fname;
  541. startGameFromFile(fname);
  542. }
  543. else if(cn == "unlock")
  544. {
  545. std::string mxname;
  546. readed >> mxname;
  547. if(mxname == "pim" && LOCPLINT)
  548. LOCPLINT->pim->unlock();
  549. }
  550. else if(cn == "setBattleAI")
  551. {
  552. std::string fname;
  553. readed >> fname;
  554. std::cout << "Will try loading that AI to see if it is correct name...\n";
  555. try
  556. {
  557. 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
  558. {
  559. delete ai;
  560. Settings neutralAI = settings.write["server"]["neutralAI"];
  561. neutralAI->String() = fname;
  562. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  563. }
  564. }
  565. catch(std::exception &e)
  566. {
  567. logGlobal->warnStream() << "Failed opening " << fname << ": " << e.what();
  568. logGlobal->warnStream() << "Setting not changes, AI not found or invalid!";
  569. }
  570. }
  571. else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  572. {
  573. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  574. LOCPLINT->cb->sendMessage(message);
  575. }
  576. }
  577. //plays intro, ends when intro is over or button has been pressed (handles events)
  578. void playIntro()
  579. {
  580. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  581. {
  582. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  583. }
  584. }
  585. void dispose()
  586. {
  587. if (console)
  588. delete console;
  589. }
  590. //used only once during initialization
  591. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo)
  592. {
  593. // VCMI will only work with 2, 3 or 4 bytes per pixel
  594. vstd::amax(bpp, 16);
  595. vstd::amin(bpp, 32);
  596. // Try to use the best screen depth for the display
  597. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  598. if(suggestedBpp == 0)
  599. {
  600. logGlobal->errorStream() << "Error: SDL says that " << w << "x" << h << " resolution is not available!";
  601. return;
  602. }
  603. bool bufOnScreen = (screenBuf == screen);
  604. if(suggestedBpp != bpp)
  605. {
  606. logGlobal->warnStream() << "Note: SDL suggests to use " << suggestedBpp << " bpp instead of" << bpp << " bpp ";
  607. }
  608. //For some reason changing fullscreen via config window checkbox result in SDL_Quit event
  609. if (resetVideo)
  610. {
  611. if(screen) //screen has been already initialized
  612. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  613. SDL_InitSubSystem(SDL_INIT_VIDEO);
  614. }
  615. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  616. {
  617. logGlobal->errorStream() << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)";
  618. throw std::runtime_error("Requested screen resolution is not available\n");
  619. }
  620. logGlobal->infoStream() << "New screen flags: " << screen->flags;
  621. if(screen2)
  622. SDL_FreeSurface(screen2);
  623. screen2 = CSDL_Ext::copySurface(screen);
  624. SDL_EnableUNICODE(1);
  625. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  626. SDL_ShowCursor(SDL_DISABLE);
  627. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  628. #ifdef _WIN32
  629. SDL_SysWMinfo wm;
  630. SDL_VERSION(&wm.version);
  631. int getwm = SDL_GetWMInfo(&wm);
  632. if(getwm == 1)
  633. {
  634. int sw = GetSystemMetrics(SM_CXSCREEN),
  635. sh = GetSystemMetrics(SM_CYSCREEN);
  636. RECT curpos;
  637. GetWindowRect(wm.window,&curpos);
  638. int ourw = curpos.right - curpos.left,
  639. ourh = curpos.bottom - curpos.top;
  640. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  641. }
  642. else
  643. {
  644. logGlobal->warnStream() << "Something went wrong, getwm=" << getwm;
  645. logGlobal->warnStream() << "SDL says: " << SDL_GetError();
  646. logGlobal->warnStream() << "Window won't be centered.";
  647. }
  648. #endif
  649. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  650. screenBuf = bufOnScreen ? screen : screen2;
  651. //setResolution = true;
  652. }
  653. static void fullScreenChanged()
  654. {
  655. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  656. Settings full = settings.write["video"]["fullscreen"];
  657. const bool toFullscreen = full->Bool();
  658. int bitsPerPixel = screen->format->BitsPerPixel;
  659. bitsPerPixel = SDL_VideoModeOK(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  660. if(bitsPerPixel == 0)
  661. {
  662. logGlobal->errorStream() << "Error: SDL says that " << screen->w << "x" << screen->h << " resolution is not available!";
  663. return;
  664. }
  665. bool bufOnScreen = (screenBuf == screen);
  666. screen = SDL_SetVideoMode(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(toFullscreen?SDL_FULLSCREEN:0));
  667. screenBuf = bufOnScreen ? screen : screen2;
  668. GH.totalRedraw();
  669. }
  670. static void listenForEvents()
  671. {
  672. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  673. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, FULLSCREEN_TOGGLED); });
  674. while(1) //main SDL events loop
  675. {
  676. SDL_Event ev;
  677. int ret = SDL_WaitEvent(&ev);
  678. if (ret == 0 || (ev.type==SDL_QUIT) ||
  679. (ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  680. {
  681. if (client)
  682. client->endGame();
  683. if (mainGUIThread)
  684. {
  685. GH.terminate = true;
  686. mainGUIThread->join();
  687. delete mainGUIThread;
  688. mainGUIThread = NULL;
  689. }
  690. delete console;
  691. console = NULL;
  692. SDL_Delay(750);
  693. SDL_Quit();
  694. std::cout << "Ending...";
  695. break;
  696. }
  697. else if(LOCPLINT && ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  698. {
  699. Settings full = settings.write["video"]["fullscreen"];
  700. full->Bool() = !full->Bool();
  701. continue;
  702. }
  703. else if(ev.type == SDL_USEREVENT)
  704. {
  705. auto endGame = []
  706. {
  707. client->endGame();
  708. vstd::clear_pointer(client);
  709. delete CGI->dobjinfo.get();
  710. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  711. const_cast<CGameInfo*>(CGI)->modh->reload(); //add info about new creatures to dobjinfo
  712. };
  713. switch(ev.user.code)
  714. {
  715. case RETURN_TO_MAIN_MENU:
  716. {
  717. endGame();
  718. GH.curInt = CGPreGame::create();;
  719. GH.defActionsDef = 63;
  720. }
  721. break;
  722. case STOP_CLIENT:
  723. client->endGame(false);
  724. break;
  725. case RESTART_GAME:
  726. {
  727. StartInfo si = *client->getStartInfo(true);
  728. endGame();
  729. startGame(&si);
  730. }
  731. break;
  732. case RETURN_TO_MENU_LOAD:
  733. endGame();
  734. CGPreGame::create();
  735. GH.defActionsDef = 63;
  736. CGP->update();
  737. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  738. GH.curInt = CGP;
  739. break;
  740. case FULLSCREEN_TOGGLED:
  741. fullScreenChanged();
  742. break;
  743. default:
  744. logGlobal->errorStream() << "Error: unknown user event. Code " << ev.user.code;
  745. assert(0);
  746. }
  747. continue;
  748. }
  749. {
  750. boost::unique_lock<boost::mutex> lock(eventsM);
  751. events.push(ev);
  752. }
  753. }
  754. }
  755. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  756. {
  757. if(gOnlyAI)
  758. {
  759. for(auto it = options->playerInfos.begin(); it != options->playerInfos.end(); ++it)
  760. {
  761. it->second.playerID = PlayerSettings::PLAYER_AI;
  762. }
  763. }
  764. client = new CClient;
  765. CPlayerInterface::howManyPeople = 0;
  766. switch(options->mode) //new game
  767. {
  768. case StartInfo::NEW_GAME:
  769. case StartInfo::CAMPAIGN:
  770. case StartInfo::DUEL:
  771. client->newGame(serv, options);
  772. break;
  773. case StartInfo::LOAD_GAME:
  774. std::string fname = options->mapname;
  775. boost::algorithm::erase_last(fname,".vlgm1");
  776. client->loadGame(fname);
  777. break;
  778. }
  779. client->connectionHandler = new boost::thread(&CClient::run, client);
  780. }