Client.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #include "CMusicHandler.h"
  2. #include "../lib/CCampaignHandler.h"
  3. #include "../CCallback.h"
  4. #include "../CConsoleHandler.h"
  5. #include "CGameInfo.h"
  6. #include "../lib/CGameState.h"
  7. #include "CPlayerInterface.h"
  8. #include "../StartInfo.h"
  9. #include "../lib/BattleState.h"
  10. #include "../lib/CArtHandler.h"
  11. #include "../lib/CDefObjInfoHandler.h"
  12. #include "../lib/CGeneralTextHandler.h"
  13. #include "../lib/CHeroHandler.h"
  14. #include "../lib/CTownHandler.h"
  15. #include "../lib/CObjectHandler.h"
  16. #include "../lib/CBuildingHandler.h"
  17. #include "../lib/CSpellHandler.h"
  18. #include "../lib/Connection.h"
  19. #include "../lib/Interprocess.h"
  20. #include "../lib/NetPacks.h"
  21. #include "../lib/VCMI_Lib.h"
  22. #include "../lib/map.h"
  23. #include "mapHandler.h"
  24. #include "CConfigHandler.h"
  25. #include "Client.h"
  26. #include "GUIBase.h"
  27. #include <boost/bind.hpp>
  28. #include <boost/foreach.hpp>
  29. #include <boost/thread.hpp>
  30. #include <boost/thread/shared_mutex.hpp>
  31. #include <boost/lexical_cast.hpp>
  32. #include <sstream>
  33. #include "CPreGame.h"
  34. #include "CBattleInterface.h"
  35. #include "../CThreadHelper.h"
  36. #include "../lib/CScriptingModule.h"
  37. #include "../lib/CFileUtility.h"
  38. #define NOT_LIB
  39. #include "../lib/RegisterTypes.cpp"
  40. extern std::string NAME;
  41. namespace intpr = boost::interprocess;
  42. /*
  43. * Client.cpp, part of VCMI engine
  44. *
  45. * Authors: listed in file AUTHORS in main folder
  46. *
  47. * License: GNU General Public License v2.0 or later
  48. * Full text of license available in license.txt file, in main folder
  49. *
  50. */
  51. template <typename T> class CApplyOnCL;
  52. class CBaseForCLApply
  53. {
  54. public:
  55. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  56. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  57. virtual ~CBaseForCLApply(){}
  58. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  59. {
  60. return new CApplyOnCL<U>;
  61. }
  62. };
  63. template <typename T> class CApplyOnCL : public CBaseForCLApply
  64. {
  65. public:
  66. void applyOnClAfter(CClient *cl, void *pack) const
  67. {
  68. T *ptr = static_cast<T*>(pack);
  69. ptr->applyCl(cl);
  70. }
  71. void applyOnClBefore(CClient *cl, void *pack) const
  72. {
  73. T *ptr = static_cast<T*>(pack);
  74. ptr->applyFirstCl(cl);
  75. }
  76. };
  77. static CApplier<CBaseForCLApply> *applier = NULL;
  78. void CClient::init()
  79. {
  80. hotSeat = false;
  81. connectionHandler = NULL;
  82. pathInfo = NULL;
  83. applier = new CApplier<CBaseForCLApply>;
  84. registerTypes2(*applier);
  85. IObjectInterface::cb = this;
  86. serv = NULL;
  87. gs = NULL;
  88. cb = NULL;
  89. erm = NULL;
  90. terminate = false;
  91. }
  92. CClient::CClient(void)
  93. :waitingRequest(0)
  94. {
  95. init();
  96. }
  97. CClient::CClient(CConnection *con, StartInfo *si)
  98. :waitingRequest(0)
  99. {
  100. init();
  101. newGame(con,si);
  102. }
  103. CClient::~CClient(void)
  104. {
  105. delete pathInfo;
  106. delete applier;
  107. }
  108. void CClient::waitForMoveAndSend(int color)
  109. {
  110. try
  111. {
  112. assert(vstd::contains(battleints, color));
  113. BattleAction ba = battleints[color]->activeStack(gs->curB->getStack(gs->curB->activeStack, false));
  114. MakeAction temp_action(ba);
  115. *serv << &temp_action;
  116. return;
  117. }HANDLE_EXCEPTION
  118. tlog1 << "We should not be here!" << std::endl;
  119. }
  120. void CClient::run()
  121. {
  122. setThreadName(-1, "CClient::run");
  123. try
  124. {
  125. CPack *pack = NULL;
  126. while(!terminate)
  127. {
  128. pack = serv->retreivePack(); //get the package from the server
  129. if (terminate)
  130. {
  131. delete pack;
  132. pack = NULL;
  133. break;
  134. }
  135. handlePack(pack);
  136. pack = NULL;
  137. }
  138. }
  139. catch (const std::exception& e)
  140. {
  141. tlog3 << "Lost connection to server, ending listening thread!\n";
  142. tlog1 << e.what() << std::endl;
  143. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  144. {
  145. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  146. throw;
  147. }
  148. }
  149. }
  150. void CClient::save(const std::string & fname)
  151. {
  152. if(gs->curB)
  153. {
  154. tlog1 << "Game cannot be saved during battle!\n";
  155. return;
  156. }
  157. SaveGame save_game(fname);
  158. *serv << &save_game;
  159. }
  160. #include <fstream>
  161. void initVillagesCapitols(Mapa * map)
  162. {
  163. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  164. int ccc;
  165. ifs>>ccc;
  166. for(int i=0;i<ccc*2;i++)
  167. {
  168. const CGDefInfo *n;
  169. if(i<ccc)
  170. {
  171. n = CGI->state->villages[i];
  172. map->defy.push_back(CGI->state->forts[i]);
  173. }
  174. else
  175. n = CGI->state->capitols[i%ccc];
  176. ifs >> const_cast<CGDefInfo*>(n)->name;
  177. if(!n)
  178. tlog1 << "*HUGE* Warning - missing town def for " << i << std::endl;
  179. else
  180. map->defy.push_back(const_cast<CGDefInfo*>(n));
  181. }
  182. }
  183. void CClient::endGame( bool closeConnection /*= true*/ )
  184. {
  185. // Game is ending
  186. // Tell the network thread to reach a stable state
  187. if(closeConnection)
  188. stopConnection();
  189. tlog0 << "Closed connection." << std::endl;
  190. GH.curInt = NULL;
  191. LOCPLINT->terminate_cond.setn(true);
  192. LOCPLINT->pim->lock();
  193. tlog0 << "\n\nEnding current game!" << std::endl;
  194. if(GH.topInt())
  195. GH.topInt()->deactivate();
  196. GH.listInt.clear();
  197. GH.objsToBlit.clear();
  198. GH.statusbar = NULL;
  199. tlog0 << "Removed GUI." << std::endl;
  200. delete CGI->mh;
  201. const_cast<CGameInfo*>(CGI)->mh = NULL;
  202. const_cast<CGameInfo*>(CGI)->state.dellNull();
  203. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  204. CPlayerInterface * oldInt = LOCPLINT;
  205. LOCPLINT = NULL;
  206. oldInt->pim->unlock();
  207. while (!playerint.empty())
  208. {
  209. CGameInterface *pint = playerint.begin()->second;
  210. playerint.erase(playerint.begin());
  211. delete pint;
  212. }
  213. BOOST_FOREACH(CCallback *cb, callbacks)
  214. {
  215. delete cb;
  216. }
  217. tlog0 << "Deleted playerInts." << std::endl;
  218. tlog0 << "Client stopped." << std::endl;
  219. }
  220. void CClient::loadGame( const std::string & fname )
  221. {
  222. tlog0 <<"\n\nLoading procedure started!\n\n";
  223. CServerHandler sh;
  224. sh.startServer();
  225. timeHandler tmh;
  226. {
  227. char sig[8];
  228. CMapHeader dum;
  229. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  230. StartInfo *si;
  231. CLoadFile lf(fname + ".vlgm1");
  232. lf >> sig >> dum >> si;
  233. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  234. lf >> *VLC;
  235. const_cast<CGameInfo*>(CGI)->setFromLib();
  236. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  237. lf >> gs;
  238. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  239. const_cast<CGameInfo*>(CGI)->state = gs;
  240. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  241. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  242. CGI->mh->init();
  243. initVillagesCapitols(gs->map);
  244. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  245. }
  246. serv = sh.connectToServer();
  247. serv->addStdVecItems(gs);
  248. tmh.update();
  249. ui8 pom8;
  250. *serv << ui8(3) << ui8(1); //load game; one client
  251. *serv << fname;
  252. *serv >> pom8;
  253. if(pom8)
  254. throw "Server cannot open the savegame!";
  255. else
  256. tlog0 << "Server opened savegame properly.\n";
  257. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  258. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  259. it != gs->scenarioOps->playerInfos.end(); ++it)
  260. {
  261. *serv << ui8(it->first); //players
  262. }
  263. *serv << ui8(255); // neutrals
  264. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  265. {
  266. CLoadFile lf(fname + ".vcgm1");
  267. lf >> *this;
  268. }
  269. }
  270. void CClient::newGame( CConnection *con, StartInfo *si )
  271. {
  272. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  273. std::set<ui8> myPlayers;
  274. if (con == NULL)
  275. {
  276. CServerHandler sh;
  277. serv = sh.connectToServer();
  278. }
  279. else
  280. {
  281. serv = con;
  282. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  283. }
  284. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  285. it != si->playerInfos.end(); ++it)
  286. {
  287. if((networkMode == SINGLE) //single - one client has all player
  288. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  289. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  290. {
  291. myPlayers.insert(ui8(it->first)); //add player
  292. }
  293. }
  294. if(networkMode != GUEST)
  295. myPlayers.insert(255); //neutral
  296. timeHandler tmh;
  297. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  298. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  299. CConnection &c(*serv);
  300. ////////////////////////////////////////////////////
  301. if(networkMode == SINGLE)
  302. {
  303. ui8 pom8;
  304. c << ui8(2) << ui8(1); //new game; one client
  305. c << *si;
  306. c >> pom8;
  307. if(pom8)
  308. throw "Server cannot open the map!";
  309. else
  310. tlog0 << "Server opened map properly.\n";
  311. }
  312. c << myPlayers;
  313. ui32 seed, sum;
  314. c >> si >> sum >> seed;
  315. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  316. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  317. gs = const_cast<CGameInfo*>(CGI)->state;
  318. gs->scenarioOps = si;
  319. gs->init(si, sum, seed);
  320. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  321. if(gs->map)
  322. {
  323. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  324. CGI->mh->map = gs->map;
  325. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  326. CGI->mh->init();
  327. initVillagesCapitols(gs->map);
  328. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  329. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  330. }
  331. int humanPlayers = 0;
  332. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  333. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  334. {
  335. ui8 color = it->first;
  336. gs->currentPlayer = color;
  337. if(!vstd::contains(myPlayers, color))
  338. continue;
  339. if(si->mode != StartInfo::DUEL)
  340. {
  341. CCallback *cb = new CCallback(gs,color,this);
  342. if(!it->second.human)
  343. {
  344. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(conf.cc.defaultPlayerAI));
  345. }
  346. else
  347. {
  348. playerint[color] = new CPlayerInterface(color);
  349. humanPlayers++;
  350. }
  351. battleints[color] = playerint[color];
  352. playerint[color]->init(cb);
  353. }
  354. else
  355. {
  356. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  357. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  358. battleints[color]->init(cbc);
  359. }
  360. }
  361. if(si->mode == StartInfo::DUEL)
  362. {
  363. CPlayerInterface *p = new CPlayerInterface(-1);
  364. p->observerInDuelMode = true;
  365. battleints[254] = playerint[254] = p;
  366. GH.curInt = p;
  367. p->init(new CCallback(gs, -1, this));
  368. battleStarted(gs->curB);
  369. }
  370. else
  371. {
  372. loadNeutralBattleAI();
  373. }
  374. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  375. hotSeat = (humanPlayers > 1);
  376. // std::vector<FileInfo> scriptModules;
  377. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  378. // BOOST_FOREACH(FileInfo &m, scriptModules)
  379. // {
  380. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  381. // privilagedGameEventReceivers.push_back(nm);
  382. // privilagedBattleEventReceivers.push_back(nm);
  383. // nm->giveActionCB(this);
  384. // nm->giveInfoCB(this);
  385. // nm->init();
  386. //
  387. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  388. // }
  389. }
  390. template <typename Handler>
  391. void CClient::serialize( Handler &h, const int version )
  392. {
  393. h & hotSeat;
  394. if(h.saving)
  395. {
  396. ui8 players = playerint.size();
  397. h & players;
  398. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  399. {
  400. h & i->first & i->second->dllName;
  401. i->second->serialize(h,version);
  402. }
  403. }
  404. else
  405. {
  406. ui8 players;
  407. h & players;
  408. for(int i=0; i < players; i++)
  409. {
  410. std::string dllname;
  411. ui8 pid;
  412. h & pid & dllname;
  413. CGameInterface *nInt = NULL;
  414. if(dllname.length())
  415. {
  416. if(pid == 255)
  417. {
  418. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  419. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  420. battleints[pid] = cbgi;
  421. cbgi->init(cb);
  422. //TODO? consider serialization
  423. continue;
  424. }
  425. else
  426. nInt = CDynLibHandler::getNewAI(dllname);
  427. }
  428. else
  429. nInt = new CPlayerInterface(pid);
  430. CCallback *callback = new CCallback(gs,pid,this);
  431. callbacks.insert(callback);
  432. battleints[pid] = playerint[pid] = nInt;
  433. nInt->init(callback);
  434. nInt->serialize(h, version);
  435. }
  436. if(!vstd::contains(battleints, NEUTRAL_PLAYER))
  437. loadNeutralBattleAI();
  438. }
  439. }
  440. void CClient::handlePack( CPack * pack )
  441. {
  442. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  443. if(apply)
  444. {
  445. apply->applyOnClBefore(this,pack);
  446. tlog5 << "\tMade first apply on cl\n";
  447. gs->apply(pack);
  448. tlog5 << "\tApplied on gs\n";
  449. apply->applyOnClAfter(this,pack);
  450. tlog5 << "\tMade second apply on cl\n";
  451. }
  452. else
  453. {
  454. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  455. }
  456. delete pack;
  457. }
  458. void CClient::updatePaths()
  459. {
  460. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  461. const CGHeroInstance *h = getSelectedHero();
  462. if (h)//if we have selected hero...
  463. calculatePaths(h);
  464. }
  465. void CClient::finishCampaign( CCampaignState * camp )
  466. {
  467. }
  468. void CClient::proposeNextMission( CCampaignState * camp )
  469. {
  470. GH.pushInt(new CBonusSelection(camp));
  471. GH.curInt = CGP;
  472. }
  473. void CClient::stopConnection()
  474. {
  475. terminate = true;
  476. if (serv) //request closing connection
  477. {
  478. tlog0 << "Connection has been requested to be closed.\n";
  479. boost::unique_lock<boost::mutex>(*serv->wmx);
  480. CloseServer close_server;
  481. *serv << &close_server;
  482. tlog0 << "Sent closing signal to the server\n";
  483. }
  484. if(connectionHandler)//end connection handler
  485. {
  486. if(connectionHandler->get_id() != boost::this_thread::get_id())
  487. connectionHandler->join();
  488. tlog0 << "Connection handler thread joined" << std::endl;
  489. delete connectionHandler;
  490. connectionHandler = NULL;
  491. }
  492. if (serv) //and delete connection
  493. {
  494. serv->close();
  495. delete serv;
  496. serv = NULL;
  497. tlog3 << "Our socket has been closed." << std::endl;
  498. }
  499. }
  500. void CClient::battleStarted(const BattleInfo * info)
  501. {
  502. CPlayerInterface * att, * def;
  503. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  504. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  505. else
  506. att = NULL;
  507. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  508. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  509. else
  510. def = NULL;
  511. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  512. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1], Rect((conf.cc.resx - 800)/2, (conf.cc.resy - 600)/2, 800, 600), att, def);
  513. if(vstd::contains(battleints,info->sides[0]))
  514. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  515. if(vstd::contains(battleints,info->sides[1]))
  516. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  517. if(vstd::contains(battleints,254))
  518. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  519. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  520. {
  521. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  522. }
  523. }
  524. void CClient::loadNeutralBattleAI()
  525. {
  526. battleints[255] = CDynLibHandler::getNewBattleAI(conf.cc.defaultBattleAI);
  527. battleints[255]->init(new CBattleCallback(gs, 255, this));
  528. }
  529. void CClient::commitPackage( CPackForClient *pack )
  530. {
  531. CommitPackage cp;
  532. cp.freePack = false;
  533. cp.packToCommit = pack;
  534. *serv << &cp;
  535. }
  536. int CClient::getLocalPlayer() const
  537. {
  538. if(LOCPLINT)
  539. return LOCPLINT->playerID;
  540. return getCurrentPlayer();
  541. }
  542. void CClient::calculatePaths(const CGHeroInstance *h)
  543. {
  544. assert(h);
  545. boost::unique_lock<boost::mutex> pathLock(pathMx);
  546. gs->calculatePaths(h, *pathInfo);
  547. }
  548. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  549. {
  550. setThreadName(-1, "CClient::commenceTacticPhaseForInt");
  551. try
  552. {
  553. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  554. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  555. {
  556. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  557. serv->sendPack(ma);
  558. }
  559. } HANDLE_EXCEPTION
  560. }
  561. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  562. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  563. void CServerHandler::startServer()
  564. {
  565. th.update();
  566. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  567. if(verbose)
  568. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  569. }
  570. void CServerHandler::waitForServer()
  571. {
  572. if(!serverThread)
  573. startServer();
  574. th.update();
  575. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  576. while(!shared->sr->ready)
  577. {
  578. shared->sr->cond.wait(slock);
  579. }
  580. if(verbose)
  581. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  582. }
  583. CConnection * CServerHandler::connectToServer()
  584. {
  585. if(!shared->sr->ready)
  586. waitForServer();
  587. th.update();
  588. CConnection *ret = justConnectToServer(conf.cc.server, port);
  589. if(verbose)
  590. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  591. return ret;
  592. }
  593. CServerHandler::CServerHandler(bool runServer /*= false*/)
  594. {
  595. serverThread = NULL;
  596. shared = NULL;
  597. port = boost::lexical_cast<std::string>(conf.cc.port);
  598. verbose = false;
  599. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  600. try
  601. {
  602. shared = new SharedMem();
  603. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  604. }
  605. CServerHandler::~CServerHandler()
  606. {
  607. delete shared;
  608. delete serverThread; //detaches, not kills thread
  609. }
  610. void CServerHandler::callServer()
  611. {
  612. setThreadName(-1, "CServerHandler::callServer");
  613. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  614. std::system(comm.c_str());
  615. tlog0 << "Server finished\n";
  616. }
  617. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  618. {
  619. CConnection *ret = NULL;
  620. while(!ret)
  621. {
  622. try
  623. {
  624. tlog0 << "Establishing connection...\n";
  625. ret = new CConnection( host.size() ? host : conf.cc.server,
  626. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  627. NAME);
  628. }
  629. catch(...)
  630. {
  631. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  632. SDL_Delay(2000);
  633. }
  634. }
  635. return ret;
  636. }