Client.cpp 19 KB

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