Client.cpp 19 KB

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