Client.cpp 21 KB

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