Client.cpp 19 KB

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