CMT.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 "CPreGame.h"
  10. #include "CCastleInterface.h"
  11. #include "../lib/CConsoleHandler.h"
  12. #include "UIFramework/CCursorHandler.h"
  13. #include "../lib/CGameState.h"
  14. #include "../CCallback.h"
  15. #include "CPlayerInterface.h"
  16. #include "CAdvmapInterface.h"
  17. #include "../lib/CBuildingHandler.h"
  18. #include "CVideoHandler.h"
  19. #include "../lib/CHeroHandler.h"
  20. #include "../lib/CCreatureHandler.h"
  21. #include "../lib/CSpellHandler.h"
  22. #include "CMusicHandler.h"
  23. #include "CVideoHandler.h"
  24. #include "../lib/CLodHandler.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. settings.init();
  209. conf.init();
  210. tlog0 <<"Loading settings: "<<pomtime.getDiff() << std::endl;
  211. tlog0 << NAME << std::endl;
  212. srand ( time(NULL) );
  213. CCS = new CClientState;
  214. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  215. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  216. {
  217. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  218. exit(-1);
  219. }
  220. atexit(SDL_Quit);
  221. const JsonNode& video = settings["video"];
  222. const JsonNode& res = video["screenRes"];
  223. //something is really wrong...
  224. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  225. {
  226. tlog0 << "Fatal error: failed to load settings!\n";
  227. tlog0 << "Possible reasons:\n";
  228. tlog0 << "\tCorrupted local configuration file at " << GVCMIDirs.UserPath << "/config/settings.json\n";
  229. tlog0 << "\tMissing or corrupted global configuration file at " << GameConstants::DATA_DIR << "/config/defaultSettings.json\n";
  230. tlog0 << "VCMI will now exit...\n";
  231. exit(EXIT_FAILURE);
  232. }
  233. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  234. tlog0 <<"\tInitializing screen: "<<pomtime.getDiff() << std::endl;
  235. // Initialize video
  236. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  237. CCS->videoh = new CEmptyVideoPlayer;
  238. #else
  239. if (!vm.count("disable-video"))
  240. CCS->videoh = new CVideoPlayer;
  241. else
  242. CCS->videoh = new CEmptyVideoPlayer;
  243. #endif
  244. tlog0<<"\tInitializing video: "<<pomtime.getDiff()<<std::endl;
  245. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  246. boost::thread loading(init);
  247. if(!vm.count("battle") && !vm.count("nointro"))
  248. playIntro();
  249. SDL_FillRect(screen,NULL,0);
  250. CSDL_Ext::update(screen);
  251. loading.join();
  252. tlog0<<"Initialization of VCMI (together): "<<total.getDiff()<<std::endl;
  253. if(!vm.count("battle"))
  254. {
  255. gOnlyAI = vm.count("onlyAI");
  256. Settings session = settings.write["session"];
  257. session["autoSkip"].Bool() = vm.count("autoSkip");
  258. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  259. std::string fileToStartFrom; //none by default
  260. if(vm.count("start"))
  261. fileToStartFrom = vm["start"].as<std::string>();
  262. if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
  263. startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
  264. else
  265. {
  266. if(fileToStartFrom.size())
  267. {
  268. tlog3 << "Warning: cannot find given file to start from (" << fileToStartFrom
  269. << "). Falling back to main menu.\n";
  270. }
  271. GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
  272. }
  273. }
  274. else
  275. {
  276. StartInfo *si = new StartInfo();
  277. si->mode = StartInfo::DUEL;
  278. si->mapname = vm["battle"].as<std::string>();
  279. si->playerInfos[0].color = 0;
  280. si->playerInfos[1].color = 1;
  281. startGame(si);
  282. }
  283. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  284. listenForEvents();
  285. return 0;
  286. }
  287. void printInfoAboutIntObject(const CIntObject *obj, int level)
  288. {
  289. tlog4 << std::string(level, '\t');
  290. tlog4 << typeid(*obj).name() << " *** ";
  291. if (obj->active)
  292. {
  293. #define PRINT(check, text) if (obj->active & CIntObject::check) tlog4 << text
  294. PRINT(LCLICK, 'L');
  295. PRINT(RCLICK, 'R');
  296. PRINT(HOVER, 'H');
  297. PRINT(MOVE, 'M');
  298. PRINT(KEYBOARD, 'K');
  299. PRINT(TIME, 'T');
  300. PRINT(GENERAL, 'A');
  301. PRINT(WHEEL, 'W');
  302. PRINT(DOUBLECLICK, 'D');
  303. #undef PRINT
  304. }
  305. else
  306. tlog4 << "inactive";
  307. tlog4 << " at " << obj->pos.x <<"x"<< obj->pos.y;
  308. tlog4 << " (" << obj->pos.w <<"x"<< obj->pos.h << ")\n";
  309. BOOST_FOREACH(const CIntObject *child, obj->children)
  310. printInfoAboutIntObject(child, level+1);
  311. }
  312. void processCommand(const std::string &message)
  313. {
  314. std::istringstream readed;
  315. readed.str(message);
  316. std::string cn; //command name
  317. readed >> cn;
  318. if(LOCPLINT && LOCPLINT->cingconsole)
  319. LOCPLINT->cingconsole->print(message);
  320. if(ermInteractiveMode)
  321. {
  322. if(cn == "exit")
  323. {
  324. ermInteractiveMode = false;
  325. return;
  326. }
  327. else
  328. {
  329. if(client && client->erm)
  330. client->erm->executeUserCommand(message);
  331. tlog0 << "erm>";
  332. }
  333. }
  334. else if(message==std::string("die, fool"))
  335. {
  336. exit(EXIT_SUCCESS);
  337. }
  338. else if(cn == "erm")
  339. {
  340. ermInteractiveMode = true;
  341. tlog0 << "erm>";
  342. }
  343. else if(cn==std::string("activate"))
  344. {
  345. int what;
  346. readed >> what;
  347. switch (what)
  348. {
  349. case 0:
  350. GH.topInt()->activate();
  351. break;
  352. case 1:
  353. adventureInt->activate();
  354. break;
  355. case 2:
  356. LOCPLINT->castleInt->activate();
  357. break;
  358. }
  359. }
  360. else if(cn=="redraw")
  361. {
  362. GH.totalRedraw();
  363. }
  364. else if(cn=="screen")
  365. {
  366. tlog0 << "Screenbuf points to ";
  367. if(screenBuf == screen)
  368. tlog1 << "screen";
  369. else if(screenBuf == screen2)
  370. tlog1 << "screen2";
  371. else
  372. tlog1 << "?!?";
  373. tlog1 << std::endl;
  374. SDL_SaveBMP(screen, "Screen_c.bmp");
  375. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  376. }
  377. else if(cn=="save")
  378. {
  379. std::string fname;
  380. readed >> fname;
  381. client->save(fname);
  382. }
  383. else if(cn=="load")
  384. {
  385. // TODO: this code should end the running game and manage to call startGame instead
  386. std::string fname;
  387. readed >> fname;
  388. client->loadGame(fname);
  389. }/*
  390. else if(cn=="resolution" || cn == "r")
  391. {
  392. if(LOCPLINT)
  393. {
  394. tlog1 << "Resolution can be set only before starting the game.\n";
  395. return;
  396. }
  397. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  398. int i=1;
  399. tlog4 << "Available screen resolutions:\n";
  400. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  401. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  402. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  403. std::cin >> i;
  404. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  405. {
  406. std::cin.clear();
  407. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  408. }
  409. else if(!i)
  410. {
  411. return;
  412. }
  413. else
  414. {
  415. auto j = conf.guiOptions.begin();
  416. std::advance(j, i - 1); //move j to the i-th resolution info
  417. const int w = j->first.first, h = j->first.second;
  418. Settings screen = settings.write["video"]["screenRes"];
  419. screen["width"].Float() = w;
  420. screen["height"].Float() = h;
  421. conf.SetResolution(screen["width"].Float(), screen["height"].Float());
  422. tlog0 << "Screen resolution set to " << (int)screen["width"].Float() << " x "
  423. << (int)screen["height"].Float() <<". It will be applied afters game restart.\n";
  424. }
  425. }*/
  426. else if(message=="get txt")
  427. {
  428. boost::filesystem::create_directory("Extracted_txts");
  429. tlog0<<"Command accepted. Opening .lod file...\t";
  430. CLodHandler * txth = new CLodHandler;
  431. txth->init(GameConstants::DATA_DIR + "/Data/H3bitmap.lod","");
  432. tlog0<<"done.\nScanning .lod file\n";
  433. BOOST_FOREACH(Entry e, txth->entries)
  434. if( e.type == FILE_TEXT )
  435. txth->extractFile(std::string(GVCMIDirs.UserPath + "/Extracted_txts/")+e.name, e.name, FILE_TEXT);
  436. tlog0<<"\rExtracting done :)\n";
  437. }
  438. else if(cn=="crash")
  439. {
  440. int *ptr = NULL;
  441. *ptr = 666;
  442. //disaster!
  443. }
  444. else if(cn == "onlyai")
  445. {
  446. gOnlyAI = true;
  447. }
  448. else if (cn == "ai")
  449. {
  450. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  451. tlog4 << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  452. }
  453. else if(cn == "mp" && adventureInt)
  454. {
  455. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  456. tlog0 << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  457. }
  458. else if(cn == "bonuses")
  459. {
  460. tlog0 << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  461. << adventureInt->selection->getBonusList() << std::endl;
  462. tlog0 << "\nInherited bonuses:\n";
  463. TCNodes parents;
  464. adventureInt->selection->getParents(parents);
  465. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  466. {
  467. tlog0 << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  468. }
  469. }
  470. else if(cn == "not dialog")
  471. {
  472. LOCPLINT->showingDialog->setn(false);
  473. }
  474. else if(cn == "gui")
  475. {
  476. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  477. {
  478. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  479. printInfoAboutIntObject(obj, 0);
  480. else
  481. tlog4 << typeid(*obj).name() << std::endl;
  482. }
  483. }
  484. else if(cn=="tell")
  485. {
  486. std::string what;
  487. int id1, id2;
  488. readed >> what >> id1 >> id2;
  489. if(what == "hs")
  490. {
  491. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  492. if(h->type->ID == id1)
  493. if(const CArtifactInstance *a = h->getArt(id2))
  494. tlog4 << a->nodeName();
  495. }
  496. }
  497. else if (cn == "set")
  498. {
  499. std::string what, value;
  500. readed >> what;
  501. Settings conf = settings.write["session"][what];
  502. readed >> value;
  503. if (value == "on")
  504. conf->Bool() = true;
  505. else if (value == "off")
  506. conf->Bool() = false;
  507. }
  508. else if(cn == "sinfo")
  509. {
  510. std::string fname;
  511. readed >> fname;
  512. if(fname.size() && SEL)
  513. {
  514. CSaveFile out(fname);
  515. out << SEL->sInfo;
  516. }
  517. }
  518. else if(cn == "start")
  519. {
  520. std::string fname;
  521. readed >> fname;
  522. startGameFromFile(fname);
  523. }
  524. else if(cn == "unlock")
  525. {
  526. std::string mxname;
  527. readed >> mxname;
  528. if(mxname == "pim" && LOCPLINT)
  529. LOCPLINT->pim->unlock();
  530. }
  531. else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  532. {
  533. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  534. LOCPLINT->cb->sendMessage(message);
  535. }
  536. }
  537. //plays intro, ends when intro is over or button has been pressed (handles events)
  538. void playIntro()
  539. {
  540. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  541. {
  542. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  543. }
  544. }
  545. void dispose()
  546. {
  547. if (console)
  548. delete console;
  549. delete logfile;
  550. }
  551. //used only once during initialization
  552. static void setScreenRes(int w, int h, int bpp, bool fullscreen, bool resetVideo)
  553. {
  554. // VCMI will only work with 2, 3 or 4 bytes per pixel
  555. vstd::amax(bpp, 16);
  556. vstd::amin(bpp, 32);
  557. // Try to use the best screen depth for the display
  558. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  559. if(suggestedBpp == 0)
  560. {
  561. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  562. return;
  563. }
  564. bool bufOnScreen = (screenBuf == screen);
  565. if(suggestedBpp != bpp)
  566. {
  567. tlog2 << "Note: SDL suggests to use " << suggestedBpp << " bpp instead of" << bpp << " bpp " << std::endl;
  568. }
  569. //For some reason changing fullscreen via config window checkbox result in SDL_Quit event
  570. if (resetVideo)
  571. {
  572. if(screen) //screen has been already initialized
  573. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  574. SDL_InitSubSystem(SDL_INIT_VIDEO);
  575. }
  576. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  577. {
  578. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  579. throw std::runtime_error("Requested screen resolution is not available\n");
  580. }
  581. tlog0 << "New screen flags: " << screen->flags << std::endl;
  582. if(screen2)
  583. SDL_FreeSurface(screen2);
  584. screen2 = CSDL_Ext::copySurface(screen);
  585. SDL_EnableUNICODE(1);
  586. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  587. SDL_ShowCursor(SDL_DISABLE);
  588. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  589. #ifdef _WIN32
  590. SDL_SysWMinfo wm;
  591. SDL_VERSION(&wm.version);
  592. int getwm = SDL_GetWMInfo(&wm);
  593. if(getwm == 1)
  594. {
  595. int sw = GetSystemMetrics(SM_CXSCREEN),
  596. sh = GetSystemMetrics(SM_CYSCREEN);
  597. RECT curpos;
  598. GetWindowRect(wm.window,&curpos);
  599. int ourw = curpos.right - curpos.left,
  600. ourh = curpos.bottom - curpos.top;
  601. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  602. }
  603. else
  604. {
  605. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  606. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  607. tlog3 << "Window won't be centered.\n";
  608. }
  609. #endif
  610. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  611. screenBuf = bufOnScreen ? screen : screen2;
  612. //setResolution = true;
  613. }
  614. static void fullScreenChanged(const JsonNode &newState)
  615. {
  616. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  617. bool fullscreen = newState.Bool();
  618. int bitsPerPixel = screen->format->BitsPerPixel;
  619. bitsPerPixel = SDL_VideoModeOK(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  620. if(bitsPerPixel == 0)
  621. {
  622. tlog1 << "Error: SDL says that " << screen->w << "x" << screen->h << " resolution is not available!\n";
  623. return;
  624. }
  625. screen = SDL_SetVideoMode(screen->w, screen->h, bitsPerPixel, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  626. GH.totalRedraw();
  627. }
  628. static void listenForEvents()
  629. {
  630. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  631. resChanged(fullScreenChanged);
  632. while(1) //main SDL events loop
  633. {
  634. SDL_Event *ev = new SDL_Event();
  635. //tlog0 << "Waiting... ";
  636. int ret = SDL_WaitEvent(ev);
  637. //tlog0 << "got " << (int)ev->type;
  638. if (ret == 0 || (ev->type==SDL_QUIT) ||
  639. (ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4 && (ev->key.keysym.mod & KMOD_ALT)))
  640. {
  641. if (client)
  642. client->endGame();
  643. if (mainGUIThread)
  644. {
  645. GH.terminate = true;
  646. mainGUIThread->join();
  647. delete mainGUIThread;
  648. mainGUIThread = NULL;
  649. }
  650. delete console;
  651. console = NULL;
  652. SDL_Delay(750);
  653. SDL_Quit();
  654. tlog0 << "Ending...\n";
  655. break;
  656. }
  657. else if(LOCPLINT && ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4)
  658. {
  659. Settings full = settings.write["video"]["fullscreen"];
  660. full->Bool() = !full->Bool();
  661. delete ev;
  662. continue;
  663. }
  664. else if(ev->type == SDL_USEREVENT)
  665. {
  666. auto endGame = []
  667. {
  668. client->endGame();
  669. vstd::clear_pointer(client);
  670. delete CGI->dobjinfo.get();
  671. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  672. const_cast<CGameInfo*>(CGI)->dobjinfo->load();
  673. };
  674. switch(ev->user.code)
  675. {
  676. /* case CHANGE_SCREEN_RESOLUTION:
  677. {
  678. tlog0 << "Changing resolution has been requested\n";
  679. const JsonNode& video = settings["video"];
  680. const JsonNode& res = video["gameRes"];
  681. setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
  682. break;
  683. }*/
  684. case RETURN_TO_MAIN_MENU:
  685. endGame();
  686. CGPreGame::create();
  687. GH.curInt = CGP;
  688. GH.defActionsDef = 63;
  689. break;
  690. case STOP_CLIENT:
  691. client->endGame(false);
  692. break;
  693. case RESTART_GAME:
  694. {
  695. StartInfo si = *client->getStartInfo(true);
  696. endGame();
  697. startGame(&si);
  698. }
  699. break;
  700. case RETURN_TO_MENU_LOAD:
  701. endGame();
  702. CGPreGame::create();
  703. GH.defActionsDef = 63;
  704. CGP->update();
  705. CGP->menu->switchToTab(vstd::find_pos(CGP->menu->menuNameToEntry, "load"));
  706. GH.curInt = CGP;
  707. break;
  708. default:
  709. tlog1 << "Error: unknown user event. Code " << ev->user.code << std::endl;
  710. assert(0);
  711. }
  712. delete ev;
  713. continue;
  714. }
  715. //tlog0 << " pushing ";
  716. {
  717. boost::unique_lock<boost::mutex> lock(eventsM);
  718. events.push(ev);
  719. }
  720. //tlog0 << " done\n";
  721. }
  722. }
  723. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  724. {
  725. GH.curInt =NULL;
  726. SDL_FillRect(screen, 0, 0);
  727. if(gOnlyAI)
  728. {
  729. for(std::map<int, PlayerSettings>::iterator it = options->playerInfos.begin();
  730. it != options->playerInfos.end(); ++it)
  731. {
  732. it->second.human = false;
  733. }
  734. }
  735. /* const JsonNode& res = settings["video"]["screenRes"];
  736. if(screen->w != res["width"].Float() || screen->h != res["height"].Float())
  737. {
  738. requestChangingResolution();
  739. //allow event handling thread change resolution
  740. auto unlock = vstd::makeUnlockGuard(eventsM);
  741. while(!setResolution) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  742. }
  743. else
  744. setResolution = true;*/
  745. client = new CClient;
  746. CPlayerInterface::howManyPeople = 0;
  747. switch(options->mode) //new game
  748. {
  749. case StartInfo::NEW_GAME:
  750. case StartInfo::CAMPAIGN:
  751. case StartInfo::DUEL:
  752. client->newGame(serv, options);
  753. break;
  754. case StartInfo::LOAD_GAME:
  755. std::string fname = options->mapname;
  756. boost::algorithm::erase_last(fname,".vlgm1");
  757. client->loadGame(fname);
  758. break;
  759. }
  760. client->connectionHandler = new boost::thread(&CClient::run, client);
  761. }
  762. /*
  763. void requestChangingResolution()
  764. {
  765. //mark that we are going to change resolution
  766. setResolution = false;
  767. //push special event to order event reading thread to change resolution
  768. SDL_Event ev;
  769. ev.type = SDL_USEREVENT;
  770. ev.user.code = CHANGE_SCREEN_RESOLUTION;
  771. SDL_PushEvent(&ev);
  772. }
  773. */