CMT.cpp 21 KB

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