CMT.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 "SDL_Extensions.h"
  7. #include "SDL_framerate.h"
  8. #include "CGameInfo.h"
  9. #include "mapHandler.h"
  10. #include "CPreGame.h"
  11. #include "CCastleInterface.h"
  12. #include "../lib/CConsoleHandler.h"
  13. #include "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 "../lib/CLodHandler.h"
  26. #include "CDefHandler.h"
  27. #include "../lib/CGeneralTextHandler.h"
  28. #include "Graphics.h"
  29. #include "Client.h"
  30. #include "CConfigHandler.h"
  31. #include "../lib/Connection.h"
  32. #include "../lib/VCMI_Lib.h"
  33. #include "../lib/VCMIDirs.h"
  34. #include "../lib/NetPacks.h"
  35. #include "CMessage.h"
  36. #include "../lib/CObjectHandler.h"
  37. #include "../lib/CArtHandler.h"
  38. #include "../lib/CScriptingModule.h"
  39. #include "../lib/GameConstants.h"
  40. #include "UIFramework/CGuiHandler.h"
  41. #ifdef _WIN32
  42. #include "SDL_syswm.h"
  43. #endif
  44. #include "../lib/CDefObjInfoHandler.h"
  45. #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;
  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. SystemOptions GDefaultOptions;
  67. VCMIDirs GVCMIDirs;
  68. std::queue<SDL_Event*> events;
  69. boost::mutex eventsM;
  70. static bool gOnlyAI = false;
  71. static bool setResolution = false; //set by event handling thread after resolution is adjusted
  72. static bool ermInteractiveMode = false; //structurize when time is right
  73. void processCommand(const std::string &message);
  74. static void setScreenRes(int w, int h, int bpp, bool fullscreen);
  75. void dispose();
  76. void playIntro();
  77. static void listenForEvents();
  78. void requestChangingResolution();
  79. void startGame(StartInfo * options, CConnection *serv = NULL);
  80. #ifndef _WIN32
  81. #ifndef _GNU_SOURCE
  82. #define _GNU_SOURCE
  83. #endif
  84. #include <getopt.h>
  85. #endif
  86. void init()
  87. {
  88. CStopWatch tmh, pomtime;
  89. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  90. int rmask = 0xff000000;int gmask = 0x00ff0000;int bmask = 0x0000ff00;int amask = 0x000000ff;
  91. #else
  92. int rmask = 0x000000ff; int gmask = 0x0000ff00; int bmask = 0x00ff0000; int amask = 0xff000000;
  93. #endif
  94. CSDL_Ext::std32bppSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 1, 32, rmask, gmask, bmask, amask);
  95. tlog0 << "\tInitializing minors: " << pomtime.getDiff() << std::endl;
  96. {
  97. //read system options
  98. CLoadFile settings(GVCMIDirs.UserPath + "/config/sysopts.bin", 727);
  99. if(settings.sfile)
  100. {
  101. settings >> GDefaultOptions;
  102. }
  103. else //file not found (probably, may be also some kind of access problem
  104. {
  105. tlog2 << "Warning: Cannot read system options, default settings will be used.\n";
  106. //Try to create file
  107. tlog2 << "VCMI will try to save default system options...\n";
  108. GDefaultOptions.settingsChanged();
  109. }
  110. }
  111. tlog0 << "\tLoading default system settings: " << pomtime.getDiff() << std::endl;
  112. //initializing audio
  113. // Note: because of interface button range, volume can only be a
  114. // multiple of 11, from 0 to 99.
  115. CCS->soundh = new CSoundHandler;
  116. CCS->soundh->init();
  117. CCS->soundh->setVolume(GDefaultOptions.soundVolume);
  118. CCS->musich = new CMusicHandler;
  119. CCS->musich->init();
  120. CCS->musich->setVolume(GDefaultOptions.musicVolume);
  121. tlog0<<"\tInitializing sound: "<<pomtime.getDiff()<<std::endl;
  122. tlog0<<"Initializing screen and sound handling: "<<tmh.getDiff()<<std::endl;
  123. initDLL(::console,logfile);
  124. const_cast<CGameInfo*>(CGI)->setFromLib();
  125. CCS->soundh->initCreaturesSounds(CGI->creh->creatures);
  126. CCS->soundh->initSpellsSounds(CGI->spellh->spells);
  127. tlog0<<"Initializing VCMI_Lib: "<<tmh.getDiff()<<std::endl;
  128. pomtime.getDiff();
  129. CCS->curh = new CCursorHandler;
  130. CCS->curh->initCursor();
  131. CCS->curh->show();
  132. tlog0<<"Screen handler: "<<pomtime.getDiff()<<std::endl;
  133. pomtime.getDiff();
  134. graphics = new Graphics();
  135. graphics->loadHeroAnims();
  136. tlog0<<"\tMain graphics: "<<tmh.getDiff()<<std::endl;
  137. tlog0<<"Initializing game graphics: "<<tmh.getDiff()<<std::endl;
  138. CMessage::init();
  139. tlog0<<"Message handler: "<<tmh.getDiff()<<std::endl;
  140. //CPG = new CPreGame(); //main menu and submenus
  141. //tlog0<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
  142. }
  143. static void prog_version(void)
  144. {
  145. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  146. printf(" data directory: %s\n", GameConstants::DATA_DIR.c_str());
  147. printf(" library directory: %s\n", GameConstants::LIB_DIR.c_str());
  148. printf(" binary directory: %s\n", GameConstants::BIN_DIR.c_str());
  149. }
  150. static void prog_help(const char *progname)
  151. {
  152. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  153. printf("Copyright (C) 2007-2010 VCMI dev team - see AUTHORS file\n");
  154. printf("This is free software; see the source for copying conditions. There is NO\n");
  155. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  156. printf("\n");
  157. printf("Usage:\n");
  158. printf(" -h, --help display this help and exit\n");
  159. printf(" -v, --version display version information and exit\n");
  160. }
  161. #ifdef _WIN32
  162. int _tmain(int argc, _TCHAR* argv[])
  163. #else
  164. int main(int argc, char** argv)
  165. #endif
  166. {
  167. tlog0 << "Starting... " << std::endl;
  168. po::options_description opts("Allowed options");
  169. opts.add_options()
  170. ("help,h", "display help and exit")
  171. ("version,v", "display version information and exit")
  172. ("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
  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(0);
  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. conf.init();
  209. tlog0 <<"Loading settings: "<<pomtime.getDiff() << std::endl;
  210. tlog0 << NAME << std::endl;
  211. srand ( time(NULL) );
  212. CCS = new CClientState;
  213. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
  214. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  215. {
  216. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  217. exit(-1);
  218. }
  219. atexit(SDL_Quit);
  220. setScreenRes(conf.cc.pregameResx, conf.cc.pregameResy, conf.cc.bpp, conf.cc.fullscreen);
  221. tlog0 <<"\tInitializing screen: "<<pomtime.getDiff() << std::endl;
  222. // Initialize video
  223. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  224. CCS->videoh = new CEmptyVideoPlayer;
  225. #else
  226. CCS->videoh = new CVideoPlayer;
  227. #endif
  228. tlog0<<"\tInitializing video: "<<pomtime.getDiff()<<std::endl;
  229. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  230. boost::thread loading(init);
  231. if(!vm.count("battle") && !vm.count("nointro"))
  232. playIntro();
  233. SDL_FillRect(screen,NULL,0);
  234. CSDL_Ext::update(screen);
  235. loading.join();
  236. tlog0<<"Initialization of VCMI (together): "<<total.getDiff()<<std::endl;
  237. if(!vm.count("battle"))
  238. {
  239. //CCS->musich->playMusic(musicBase::mainMenu, -1);
  240. GH.curInt = new CGPreGame; //will set CGP pointer to itself
  241. }
  242. else
  243. {
  244. StartInfo *si = new StartInfo();
  245. si->mode = StartInfo::DUEL;
  246. si->mapname = vm["battle"].as<std::string>();
  247. si->playerInfos[0].color = 0;
  248. si->playerInfos[1].color = 1;
  249. startGame(si);
  250. }
  251. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  252. listenForEvents();
  253. return 0;
  254. }
  255. void printInfoAboutIntObject(const CIntObject *obj, int level)
  256. {
  257. int tabs = level;
  258. while(tabs--) tlog4 << '\t';
  259. tlog4 << typeid(*obj).name() << " *** " << (obj->active ? "" : "not ") << "active\n";
  260. BOOST_FOREACH(const CIntObject *child, obj->children)
  261. printInfoAboutIntObject(child, level+1);
  262. }
  263. void processCommand(const std::string &message)
  264. {
  265. std::istringstream readed;
  266. readed.str(message);
  267. std::string cn; //command name
  268. readed >> cn;
  269. if(LOCPLINT && LOCPLINT->cingconsole)
  270. LOCPLINT->cingconsole->print(message);
  271. if(ermInteractiveMode)
  272. {
  273. if(cn == "exit")
  274. {
  275. ermInteractiveMode = false;
  276. return;
  277. }
  278. else
  279. {
  280. if(client && client->erm)
  281. client->erm->executeUserCommand(message);
  282. tlog0 << "erm>";
  283. }
  284. }
  285. else if(message==std::string("die, fool"))
  286. {
  287. exit(EXIT_SUCCESS);
  288. }
  289. else if(cn == "erm")
  290. {
  291. ermInteractiveMode = true;
  292. tlog0 << "erm>";
  293. }
  294. else if(cn==std::string("activate"))
  295. {
  296. int what;
  297. readed >> what;
  298. switch (what)
  299. {
  300. case 0:
  301. GH.topInt()->activate();
  302. break;
  303. case 1:
  304. adventureInt->activate();
  305. break;
  306. case 2:
  307. LOCPLINT->castleInt->activate();
  308. break;
  309. }
  310. }
  311. else if(cn=="redraw")
  312. {
  313. GH.totalRedraw();
  314. }
  315. else if(cn=="screen")
  316. {
  317. tlog0 << "Screenbuf points to ";
  318. if(screenBuf == screen)
  319. tlog1 << "screen";
  320. else if(screenBuf == screen2)
  321. tlog1 << "screen2";
  322. else
  323. tlog1 << "?!?";
  324. tlog1 << std::endl;
  325. SDL_SaveBMP(screen, "Screen_c.bmp");
  326. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  327. }
  328. else if(cn=="save")
  329. {
  330. std::string fname;
  331. readed >> fname;
  332. client->save(fname);
  333. }
  334. //else if(cn=="list")
  335. //{
  336. // if(CPG)
  337. // for(int i = 0; i < CPG->ourScenSel->mapsel.ourGames.size(); i++)
  338. // tlog0 << i << ".\t" << CPG->ourScenSel->mapsel.ourGames[i]->filename << std::endl;
  339. //}
  340. else if(cn=="load")
  341. {
  342. // TODO: this code should end the running game and manage to call startGame instead
  343. std::string fname;
  344. readed >> fname;
  345. client->loadGame(fname);
  346. }
  347. //else if(cn=="ln")
  348. //{
  349. // int num;
  350. // readed >> num;
  351. // std::string &name = CPG->ourScenSel->mapsel.ourGames[num]->filename;
  352. // client->load(name.substr(0, name.size()-6));
  353. //}
  354. else if(cn=="resolution" || cn == "r")
  355. {
  356. if(LOCPLINT)
  357. {
  358. tlog1 << "Resolution can be set only before starting the game.\n";
  359. return;
  360. }
  361. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  362. int i=1, hlp=1;
  363. tlog4 << "Available screen resolutions:\n";
  364. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  365. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  366. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  367. std::cin >> i;
  368. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  369. {
  370. std::cin.clear();
  371. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  372. }
  373. else if(!i)
  374. {
  375. return;
  376. }
  377. else
  378. {
  379. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end() && hlp++<i; j++); //move j to the i-th resolution info
  380. conf.cc.resx = conf.cc.screenx = j->first.first;
  381. conf.cc.resy = conf.cc.screeny = j->first.second;
  382. conf.SetResolution(conf.cc.screenx, conf.cc.screeny);
  383. tlog0 << "Screen resolution set to " << conf.cc.screenx << " x " << conf.cc.screeny <<". It will be applied when the game starts.\n";
  384. }
  385. }
  386. else if(message=="get txt")
  387. {
  388. boost::filesystem::create_directory("Extracted_txts");
  389. tlog0<<"Command accepted. Opening .lod file...\t";
  390. CLodHandler * txth = new CLodHandler;
  391. txth->init(GameConstants::DATA_DIR + "/Data/H3bitmap.lod","");
  392. tlog0<<"done.\nScanning .lod file\n";
  393. BOOST_FOREACH(Entry e, txth->entries)
  394. if( e.type == FILE_TEXT )
  395. txth->extractFile(std::string(GVCMIDirs.UserPath + "/Extracted_txts/")+e.name, e.name, FILE_TEXT);
  396. tlog0<<"\rExtracting done :)\n";
  397. }
  398. else if(cn=="crash")
  399. {
  400. int *ptr = NULL;
  401. *ptr = 666;
  402. //disaster!
  403. }
  404. else if(cn == "onlyai")
  405. {
  406. gOnlyAI = true;
  407. }
  408. else if (cn == "ai")
  409. {
  410. VLC->IS_AI_ENABLED = !VLC->IS_AI_ENABLED;
  411. tlog4 << "Current AI status: " << (VLC->IS_AI_ENABLED ? "enabled" : "disabled") << std::endl;
  412. }
  413. else if(cn == "mp" && adventureInt)
  414. {
  415. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  416. tlog0 << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  417. }
  418. else if(cn == "bonuses")
  419. {
  420. tlog0 << "Bonuses of " << adventureInt->selection->getHoverText() << std::endl
  421. << adventureInt->selection->getBonusList() << std::endl;
  422. tlog0 << "\nInherited bonuses:\n";
  423. TCNodes parents;
  424. adventureInt->selection->getParents(parents);
  425. BOOST_FOREACH(const CBonusSystemNode *parent, parents)
  426. {
  427. tlog0 << "\nBonuses from " << typeid(*parent).name() << std::endl << parent->getBonusList() << std::endl;
  428. }
  429. }
  430. else if(cn == "not dialog")
  431. {
  432. LOCPLINT->showingDialog->setn(false);
  433. }
  434. else if(cn == "gui")
  435. {
  436. BOOST_FOREACH(const IShowActivatable *child, GH.listInt)
  437. {
  438. if(const CIntObject *obj = dynamic_cast<const CIntObject *>(child))
  439. printInfoAboutIntObject(obj, 0);
  440. else
  441. tlog4 << typeid(*obj).name() << std::endl;
  442. }
  443. }
  444. else if(cn=="tell")
  445. {
  446. std::string what;
  447. int id1, id2;
  448. readed >> what >> id1 >> id2;
  449. if(what == "hs")
  450. {
  451. BOOST_FOREACH(const CGHeroInstance *h, LOCPLINT->cb->getHeroesInfo())
  452. if(h->type->ID == id1)
  453. if(const CArtifactInstance *a = h->getArt(id2))
  454. tlog4 << a->nodeName();
  455. }
  456. else if (what == "anim" )
  457. {
  458. CAnimation::getAnimInfo();
  459. }
  460. }
  461. else if (cn == "switchCreWin" )
  462. {
  463. conf.cc.classicCreatureWindow = !conf.cc.classicCreatureWindow;
  464. }
  465. else if(client && client->serv && client->serv->connected) //send to server
  466. {
  467. PlayerMessage pm(LOCPLINT->playerID,message);
  468. *client->serv << &pm;
  469. }
  470. }
  471. //plays intro, ends when intro is over or button has been pressed (handles events)
  472. void playIntro()
  473. {
  474. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  475. {
  476. CCS->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  477. }
  478. }
  479. void dispose()
  480. {
  481. if (console)
  482. delete console;
  483. delete logfile;
  484. }
  485. static void setScreenRes(int w, int h, int bpp, bool fullscreen)
  486. {
  487. // VCMI will only work with 2, 3 or 4 bytes per pixel
  488. vstd::amax(bpp, 16);
  489. vstd::amin(bpp, 32);
  490. // Try to use the best screen depth for the display
  491. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  492. if(suggestedBpp == 0)
  493. {
  494. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  495. return;
  496. }
  497. bool bufOnScreen = (screenBuf == screen);
  498. if(suggestedBpp != bpp)
  499. {
  500. tlog2 << "Warning: SDL says that " << bpp << "bpp is wrong and suggests " << suggestedBpp << std::endl;
  501. }
  502. if(screen) //screen has been already initialized
  503. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  504. SDL_InitSubSystem(SDL_INIT_VIDEO);
  505. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  506. {
  507. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  508. throw "Requested screen resolution is not available\n";
  509. }
  510. tlog0 << "New screen flags: " << screen->flags << std::endl;
  511. if(screen2)
  512. SDL_FreeSurface(screen2);
  513. screen2 = CSDL_Ext::copySurface(screen);
  514. SDL_EnableUNICODE(1);
  515. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  516. SDL_ShowCursor(SDL_DISABLE);
  517. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  518. #ifdef _WIN32
  519. SDL_SysWMinfo wm;
  520. SDL_VERSION(&wm.version);
  521. int getwm = SDL_GetWMInfo(&wm);
  522. if(getwm == 1)
  523. {
  524. int sw = GetSystemMetrics(SM_CXSCREEN),
  525. sh = GetSystemMetrics(SM_CYSCREEN);
  526. RECT curpos;
  527. GetWindowRect(wm.window,&curpos);
  528. int ourw = curpos.right - curpos.left,
  529. ourh = curpos.bottom - curpos.top;
  530. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  531. }
  532. else
  533. {
  534. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  535. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  536. tlog3 << "Window won't be centered.\n";
  537. }
  538. #endif
  539. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  540. screenBuf = bufOnScreen ? screen : screen2;
  541. setResolution = true;
  542. }
  543. static void listenForEvents()
  544. {
  545. while(1) //main SDL events loop
  546. {
  547. SDL_Event *ev = new SDL_Event();
  548. //tlog0 << "Waiting... ";
  549. int ret = SDL_WaitEvent(ev);
  550. //tlog0 << "got " << (int)ev->type;
  551. if (ret == 0 || (ev->type==SDL_QUIT) ||
  552. (ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4 && (ev->key.keysym.mod & KMOD_ALT)))
  553. {
  554. if (client)
  555. client->endGame();
  556. if (mainGUIThread)
  557. {
  558. GH.terminate = true;
  559. mainGUIThread->join();
  560. delete mainGUIThread;
  561. mainGUIThread = NULL;
  562. }
  563. delete console;
  564. console = NULL;
  565. SDL_Delay(750);
  566. SDL_Quit();
  567. tlog0 << "Ending...\n";
  568. break;
  569. }
  570. else if(LOCPLINT && ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4)
  571. {
  572. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  573. bool full = !(screen->flags&SDL_FULLSCREEN);
  574. setScreenRes(conf.cc.screenx, conf.cc.screeny, conf.cc.bpp, full);
  575. GH.totalRedraw();
  576. delete ev;
  577. continue;
  578. }
  579. else if(ev->type == SDL_USEREVENT)
  580. {
  581. switch(ev->user.code)
  582. {
  583. case 1:
  584. tlog0 << "Changing resolution has been requested\n";
  585. setScreenRes(conf.cc.screenx, conf.cc.screeny, conf.cc.bpp, conf.cc.fullscreen);
  586. break;
  587. case 2:
  588. client->endGame();
  589. delete client;
  590. client = NULL;
  591. delete CGI->dobjinfo.get();
  592. const_cast<CGameInfo*>(CGI)->dobjinfo = new CDefObjInfoHandler;
  593. const_cast<CGameInfo*>(CGI)->dobjinfo->load();
  594. GH.curInt = CGP;
  595. GH.defActionsDef = 63;
  596. break;
  597. case 3:
  598. client->endGame(false);
  599. break;
  600. }
  601. delete ev;
  602. continue;
  603. }
  604. //tlog0 << " pushing ";
  605. eventsM.lock();
  606. events.push(ev);
  607. eventsM.unlock();
  608. //tlog0 << " done\n";
  609. }
  610. }
  611. void startGame(StartInfo * options, CConnection *serv/* = NULL*/)
  612. {
  613. GH.curInt =NULL;
  614. SDL_FillRect(screen, 0, 0);
  615. if(gOnlyAI)
  616. {
  617. for(std::map<int, PlayerSettings>::iterator it = options->playerInfos.begin();
  618. it != options->playerInfos.end(); ++it)
  619. {
  620. it->second.human = false;
  621. }
  622. }
  623. if(screen->w != conf.cc.screenx || screen->h != conf.cc.screeny)
  624. {
  625. requestChangingResolution();
  626. //allow event handling thread change resolution
  627. eventsM.unlock();
  628. while(!setResolution) boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  629. eventsM.lock();
  630. }
  631. else
  632. setResolution = true;
  633. client = new CClient;
  634. CPlayerInterface::howManyPeople = 0;
  635. switch(options->mode) //new game
  636. {
  637. case StartInfo::NEW_GAME:
  638. case StartInfo::CAMPAIGN:
  639. case StartInfo::DUEL:
  640. client->newGame(serv, options);
  641. break;
  642. case StartInfo::LOAD_GAME:
  643. std::string fname = options->mapname;
  644. boost::algorithm::erase_last(fname,".vlgm1");
  645. client->loadGame(fname);
  646. break;
  647. }
  648. client->connectionHandler = new boost::thread(&CClient::run, client);
  649. }
  650. void requestChangingResolution()
  651. {
  652. //mark that we are going to change resolution
  653. setResolution = false;
  654. //push special event to order event reading thread to change resolution
  655. SDL_Event ev;
  656. ev.type = SDL_USEREVENT;
  657. ev.user.code = 1;
  658. SDL_PushEvent(&ev);
  659. }