Client.cpp 19 KB

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