Client.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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.h"
  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 CClient::endGame( bool closeConnection /*= true*/ )
  162. {
  163. // Game is ending
  164. // Tell the network thread to reach a stable state
  165. if(closeConnection)
  166. stopConnection();
  167. tlog0 << "Closed connection." << std::endl;
  168. GH.curInt = NULL;
  169. LOCPLINT->terminate_cond.setn(true);
  170. LOCPLINT->pim->lock();
  171. tlog0 << "\n\nEnding current game!" << std::endl;
  172. if(GH.topInt())
  173. GH.topInt()->deactivate();
  174. GH.listInt.clear();
  175. GH.objsToBlit.clear();
  176. GH.statusbar = NULL;
  177. tlog0 << "Removed GUI." << std::endl;
  178. delete CGI->mh;
  179. const_cast<CGameInfo*>(CGI)->mh = NULL;
  180. const_cast<CGameInfo*>(CGI)->state.dellNull();
  181. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  182. CPlayerInterface * oldInt = LOCPLINT;
  183. LOCPLINT = NULL;
  184. oldInt->pim->unlock();
  185. while (!playerint.empty())
  186. {
  187. CGameInterface *pint = playerint.begin()->second;
  188. playerint.erase(playerint.begin());
  189. delete pint;
  190. }
  191. BOOST_FOREACH(CCallback *cb, callbacks)
  192. {
  193. delete cb;
  194. }
  195. tlog0 << "Deleted playerInts." << std::endl;
  196. tlog0 << "Client stopped." << std::endl;
  197. }
  198. void CClient::loadGame( const std::string & fname )
  199. {
  200. tlog0 <<"\n\nLoading procedure started!\n\n";
  201. CServerHandler sh;
  202. sh.startServer();
  203. timeHandler tmh;
  204. {
  205. char sig[8];
  206. CMapHeader dum;
  207. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  208. StartInfo *si;
  209. CLoadFile lf(fname + ".vlgm1");
  210. lf >> sig >> dum >> si;
  211. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  212. lf >> *VLC;
  213. const_cast<CGameInfo*>(CGI)->setFromLib();
  214. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  215. lf >> gs;
  216. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  217. const_cast<CGameInfo*>(CGI)->state = gs;
  218. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  219. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  220. CGI->mh->init();
  221. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  222. }
  223. serv = sh.connectToServer();
  224. serv->addStdVecItems(gs);
  225. tmh.update();
  226. ui8 pom8;
  227. *serv << ui8(3) << ui8(1); //load game; one client
  228. *serv << fname;
  229. *serv >> pom8;
  230. if(pom8)
  231. throw "Server cannot open the savegame!";
  232. else
  233. tlog0 << "Server opened savegame properly.\n";
  234. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  235. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  236. it != gs->scenarioOps->playerInfos.end(); ++it)
  237. {
  238. *serv << ui8(it->first); //players
  239. }
  240. *serv << ui8(255); // neutrals
  241. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  242. {
  243. CLoadFile lf(fname + ".vcgm1");
  244. lf >> *this;
  245. }
  246. }
  247. void CClient::newGame( CConnection *con, StartInfo *si )
  248. {
  249. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  250. std::set<ui8> myPlayers;
  251. if (con == NULL)
  252. {
  253. CServerHandler sh;
  254. serv = sh.connectToServer();
  255. }
  256. else
  257. {
  258. serv = con;
  259. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  260. }
  261. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  262. it != si->playerInfos.end(); ++it)
  263. {
  264. if((networkMode == SINGLE) //single - one client has all player
  265. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  266. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  267. {
  268. myPlayers.insert(ui8(it->first)); //add player
  269. }
  270. }
  271. if(networkMode != GUEST)
  272. myPlayers.insert(255); //neutral
  273. timeHandler tmh;
  274. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  275. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  276. CConnection &c(*serv);
  277. ////////////////////////////////////////////////////
  278. if(networkMode == SINGLE)
  279. {
  280. ui8 pom8;
  281. c << ui8(2) << ui8(1); //new game; one client
  282. c << *si;
  283. c >> pom8;
  284. if(pom8)
  285. throw "Server cannot open the map!";
  286. else
  287. tlog0 << "Server opened map properly.\n";
  288. }
  289. c << myPlayers;
  290. ui32 seed, sum;
  291. c >> si >> sum >> seed;
  292. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  293. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  294. gs = const_cast<CGameInfo*>(CGI)->state;
  295. gs->scenarioOps = si;
  296. gs->init(si, sum, seed);
  297. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  298. if(gs->map)
  299. {
  300. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  301. CGI->mh->map = gs->map;
  302. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  303. CGI->mh->init();
  304. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  305. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  306. }
  307. int humanPlayers = 0;
  308. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  309. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  310. {
  311. ui8 color = it->first;
  312. gs->currentPlayer = color;
  313. if(!vstd::contains(myPlayers, color))
  314. continue;
  315. if(si->mode != StartInfo::DUEL)
  316. {
  317. CCallback *cb = new CCallback(gs,color,this);
  318. if(!it->second.human)
  319. {
  320. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(conf.cc.defaultPlayerAI));
  321. }
  322. else
  323. {
  324. playerint[color] = new CPlayerInterface(color);
  325. humanPlayers++;
  326. }
  327. battleints[color] = playerint[color];
  328. playerint[color]->init(cb);
  329. }
  330. else
  331. {
  332. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  333. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  334. battleints[color]->init(cbc);
  335. }
  336. }
  337. if(si->mode == StartInfo::DUEL)
  338. {
  339. CPlayerInterface *p = new CPlayerInterface(-1);
  340. p->observerInDuelMode = true;
  341. battleints[254] = playerint[254] = p;
  342. GH.curInt = p;
  343. p->init(new CCallback(gs, -1, this));
  344. battleStarted(gs->curB);
  345. }
  346. else
  347. {
  348. loadNeutralBattleAI();
  349. }
  350. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  351. hotSeat = (humanPlayers > 1);
  352. // std::vector<FileInfo> scriptModules;
  353. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  354. // BOOST_FOREACH(FileInfo &m, scriptModules)
  355. // {
  356. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  357. // privilagedGameEventReceivers.push_back(nm);
  358. // privilagedBattleEventReceivers.push_back(nm);
  359. // nm->giveActionCB(this);
  360. // nm->giveInfoCB(this);
  361. // nm->init();
  362. //
  363. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  364. // }
  365. }
  366. template <typename Handler>
  367. void CClient::serialize( Handler &h, const int version )
  368. {
  369. h & hotSeat;
  370. if(h.saving)
  371. {
  372. ui8 players = playerint.size();
  373. h & players;
  374. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  375. {
  376. h & i->first & i->second->dllName;
  377. i->second->serialize(h,version);
  378. }
  379. }
  380. else
  381. {
  382. ui8 players;
  383. h & players;
  384. for(int i=0; i < players; i++)
  385. {
  386. std::string dllname;
  387. ui8 pid;
  388. h & pid & dllname;
  389. CGameInterface *nInt = NULL;
  390. if(dllname.length())
  391. {
  392. if(pid == 255)
  393. {
  394. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  395. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  396. battleints[pid] = cbgi;
  397. cbgi->init(cb);
  398. //TODO? consider serialization
  399. continue;
  400. }
  401. else
  402. nInt = CDynLibHandler::getNewAI(dllname);
  403. }
  404. else
  405. nInt = new CPlayerInterface(pid);
  406. CCallback *callback = new CCallback(gs,pid,this);
  407. callbacks.insert(callback);
  408. battleints[pid] = playerint[pid] = nInt;
  409. nInt->init(callback);
  410. nInt->serialize(h, version);
  411. }
  412. if(!vstd::contains(battleints, NEUTRAL_PLAYER))
  413. loadNeutralBattleAI();
  414. }
  415. }
  416. void CClient::handlePack( CPack * pack )
  417. {
  418. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  419. if(apply)
  420. {
  421. apply->applyOnClBefore(this,pack);
  422. tlog5 << "\tMade first apply on cl\n";
  423. gs->apply(pack);
  424. tlog5 << "\tApplied on gs\n";
  425. apply->applyOnClAfter(this,pack);
  426. tlog5 << "\tMade second apply on cl\n";
  427. }
  428. else
  429. {
  430. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  431. }
  432. delete pack;
  433. }
  434. void CClient::updatePaths()
  435. {
  436. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  437. const CGHeroInstance *h = getSelectedHero();
  438. if (h)//if we have selected hero...
  439. calculatePaths(h);
  440. }
  441. void CClient::finishCampaign( CCampaignState * camp )
  442. {
  443. }
  444. void CClient::proposeNextMission( CCampaignState * camp )
  445. {
  446. GH.pushInt(new CBonusSelection(camp));
  447. GH.curInt = CGP;
  448. }
  449. void CClient::stopConnection()
  450. {
  451. terminate = true;
  452. if (serv) //request closing connection
  453. {
  454. tlog0 << "Connection has been requested to be closed.\n";
  455. boost::unique_lock<boost::mutex>(*serv->wmx);
  456. CloseServer close_server;
  457. *serv << &close_server;
  458. tlog0 << "Sent closing signal to the server\n";
  459. }
  460. if(connectionHandler)//end connection handler
  461. {
  462. if(connectionHandler->get_id() != boost::this_thread::get_id())
  463. connectionHandler->join();
  464. tlog0 << "Connection handler thread joined" << std::endl;
  465. delete connectionHandler;
  466. connectionHandler = NULL;
  467. }
  468. if (serv) //and delete connection
  469. {
  470. serv->close();
  471. delete serv;
  472. serv = NULL;
  473. tlog3 << "Our socket has been closed." << std::endl;
  474. }
  475. }
  476. void CClient::battleStarted(const BattleInfo * info)
  477. {
  478. CPlayerInterface * att, * def;
  479. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  480. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  481. else
  482. att = NULL;
  483. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  484. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  485. else
  486. def = NULL;
  487. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  488. 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);
  489. if(vstd::contains(battleints,info->sides[0]))
  490. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  491. if(vstd::contains(battleints,info->sides[1]))
  492. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  493. if(vstd::contains(battleints,254))
  494. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  495. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  496. {
  497. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  498. }
  499. }
  500. void CClient::loadNeutralBattleAI()
  501. {
  502. battleints[255] = CDynLibHandler::getNewBattleAI(conf.cc.defaultBattleAI);
  503. battleints[255]->init(new CBattleCallback(gs, 255, this));
  504. }
  505. void CClient::commitPackage( CPackForClient *pack )
  506. {
  507. CommitPackage cp;
  508. cp.freePack = false;
  509. cp.packToCommit = pack;
  510. *serv << &cp;
  511. }
  512. int CClient::getLocalPlayer() const
  513. {
  514. if(LOCPLINT)
  515. return LOCPLINT->playerID;
  516. return getCurrentPlayer();
  517. }
  518. void CClient::calculatePaths(const CGHeroInstance *h)
  519. {
  520. assert(h);
  521. boost::unique_lock<boost::mutex> pathLock(pathMx);
  522. gs->calculatePaths(h, *pathInfo);
  523. }
  524. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  525. {
  526. setThreadName(-1, "CClient::commenceTacticPhaseForInt");
  527. try
  528. {
  529. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  530. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  531. {
  532. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  533. serv->sendPack(ma);
  534. }
  535. } HANDLE_EXCEPTION
  536. }
  537. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  538. {
  539. if(!h || pathInfo->hero == h)
  540. pathInfo->isValid = false;
  541. }
  542. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  543. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  544. void CServerHandler::startServer()
  545. {
  546. th.update();
  547. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  548. if(verbose)
  549. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  550. }
  551. void CServerHandler::waitForServer()
  552. {
  553. if(!serverThread)
  554. startServer();
  555. th.update();
  556. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  557. while(!shared->sr->ready)
  558. {
  559. shared->sr->cond.wait(slock);
  560. }
  561. if(verbose)
  562. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  563. }
  564. CConnection * CServerHandler::connectToServer()
  565. {
  566. if(!shared->sr->ready)
  567. waitForServer();
  568. th.update();
  569. CConnection *ret = justConnectToServer(conf.cc.server, port);
  570. if(verbose)
  571. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  572. return ret;
  573. }
  574. CServerHandler::CServerHandler(bool runServer /*= false*/)
  575. {
  576. serverThread = NULL;
  577. shared = NULL;
  578. port = boost::lexical_cast<std::string>(conf.cc.port);
  579. verbose = false;
  580. 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
  581. try
  582. {
  583. shared = new SharedMem();
  584. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  585. }
  586. CServerHandler::~CServerHandler()
  587. {
  588. delete shared;
  589. delete serverThread; //detaches, not kills thread
  590. }
  591. void CServerHandler::callServer()
  592. {
  593. setThreadName(-1, "CServerHandler::callServer");
  594. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  595. std::system(comm.c_str());
  596. tlog0 << "Server finished\n";
  597. }
  598. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  599. {
  600. CConnection *ret = NULL;
  601. while(!ret)
  602. {
  603. try
  604. {
  605. tlog0 << "Establishing connection...\n";
  606. ret = new CConnection( host.size() ? host : conf.cc.server,
  607. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  608. NAME);
  609. }
  610. catch(...)
  611. {
  612. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  613. SDL_Delay(2000);
  614. }
  615. }
  616. return ret;
  617. }