CMT.cpp 25 KB

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