Client.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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/CModHandler.h"
  12. #include "../lib/CArtHandler.h"
  13. #include "../lib/CDefObjInfoHandler.h"
  14. #include "../lib/CGeneralTextHandler.h"
  15. #include "../lib/CHeroHandler.h"
  16. #include "../lib/CTownHandler.h"
  17. #include "../lib/CObjectHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/CSpellHandler.h"
  20. #include "../lib/Connection.h"
  21. #include "../lib/Interprocess.h"
  22. #include "../lib/NetPacks.h"
  23. #include "../lib/VCMI_Lib.h"
  24. #include "../lib/VCMIDirs.h"
  25. #include "../lib/map.h"
  26. #include "../lib/JsonNode.h"
  27. #include "mapHandler.h"
  28. #include "CConfigHandler.h"
  29. #include "Client.h"
  30. #include "CPreGame.h"
  31. #include "BattleInterface/CBattleInterface.h"
  32. #include "../lib/CThreadHelper.h"
  33. #include "../lib/CScriptingModule.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. {
  90. init();
  91. }
  92. CClient::CClient(CConnection *con, StartInfo *si)
  93. {
  94. init();
  95. newGame(con,si);
  96. }
  97. CClient::~CClient(void)
  98. {
  99. delete pathInfo;
  100. delete applier;
  101. }
  102. void CClient::waitForMoveAndSend(int color)
  103. {
  104. try
  105. {
  106. assert(vstd::contains(battleints, color));
  107. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  108. MakeAction temp_action(ba);
  109. sendRequest(&temp_action, color);
  110. return;
  111. }
  112. catch(boost::thread_interrupted&)
  113. {
  114. tlog5 << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?\n";
  115. return;
  116. }
  117. HANDLE_EXCEPTION
  118. tlog1 << "We should not be here!" << std::endl;
  119. }
  120. void CClient::run()
  121. {
  122. setThreadName("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 only asio exceptions
  140. catch (const boost::system::system_error& e)
  141. {
  142. tlog3 << "Lost connection to server, ending listening thread!\n";
  143. tlog1 << e.what() << std::endl;
  144. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  145. {
  146. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  147. throw;
  148. }
  149. }
  150. }
  151. void CClient::save(const std::string & fname)
  152. {
  153. if(gs->curB)
  154. {
  155. tlog1 << "Game cannot be saved during battle!\n";
  156. return;
  157. }
  158. SaveGame save_game(fname);
  159. sendRequest((CPackForClient*)&save_game, 255);
  160. }
  161. void CClient::endGame( bool closeConnection /*= true*/ )
  162. {
  163. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  164. BOOST_FOREACH(auto i, playerint)
  165. i.second->finish();
  166. // Game is ending
  167. // Tell the network thread to reach a stable state
  168. if(closeConnection)
  169. stopConnection();
  170. tlog0 << "Closed connection." << std::endl;
  171. GH.curInt = NULL;
  172. LOCPLINT->terminate_cond.setn(true);
  173. {
  174. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  175. tlog0 << "\n\nEnding current game!" << std::endl;
  176. if(GH.topInt())
  177. GH.topInt()->deactivate();
  178. GH.listInt.clear();
  179. GH.objsToBlit.clear();
  180. GH.statusbar = NULL;
  181. tlog0 << "Removed GUI." << std::endl;
  182. delete CGI->mh;
  183. const_cast<CGameInfo*>(CGI)->mh = NULL;
  184. const_cast<CGameInfo*>(CGI)->state.dellNull();
  185. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  186. LOCPLINT = NULL;
  187. }
  188. while (!playerint.empty())
  189. {
  190. CGameInterface *pint = playerint.begin()->second;
  191. playerint.erase(playerint.begin());
  192. delete pint;
  193. }
  194. callbacks.clear();
  195. tlog0 << "Deleted playerInts." << std::endl;
  196. tlog0 << "Client stopped." << std::endl;
  197. }
  198. void CClient::loadGame( const std::string & fname )
  199. {
  200. tlog0 <<"\n\nLoading procedure started!\n\n";
  201. CServerHandler sh;
  202. sh.startServer();
  203. CStopWatch tmh;
  204. {
  205. char sig[8];
  206. CMapHeader dum;
  207. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  208. StartInfo *si;
  209. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME)));
  210. lf >> sig >> dum >> si;
  211. tlog0 <<"Reading save signature: "<<tmh.getDiff()<<std::endl;
  212. lf >> *VLC;
  213. const_cast<CGameInfo*>(CGI)->setFromLib();
  214. tlog0 <<"Reading handlers: "<<tmh.getDiff()<<std::endl;
  215. lf >> gs;
  216. tlog0 <<"Reading gamestate: "<<tmh.getDiff()<<std::endl;
  217. const_cast<CGameInfo*>(CGI)->state = gs;
  218. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  219. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  220. CGI->mh->init();
  221. tlog0 <<"Initing maphandler: "<<tmh.getDiff()<<std::endl;
  222. }
  223. serv = sh.connectToServer();
  224. serv->addStdVecItems(gs);
  225. tmh.update();
  226. ui8 pom8;
  227. *serv << ui8(3) << ui8(1); //load game; one client
  228. *serv << fname;
  229. *serv >> pom8;
  230. if(pom8)
  231. throw std::runtime_error("Server cannot open the savegame!");
  232. else
  233. tlog0 << "Server opened savegame properly.\n";
  234. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  235. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  236. it != gs->scenarioOps->playerInfos.end(); ++it)
  237. {
  238. *serv << ui8(it->first); //players
  239. }
  240. *serv << ui8(255); // neutrals
  241. tlog0 <<"Sent info to server: "<<tmh.getDiff()<<std::endl;
  242. {
  243. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME)));
  244. lf >> *this;
  245. }
  246. }
  247. void CClient::newGame( CConnection *con, StartInfo *si )
  248. {
  249. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  250. std::set<ui8> myPlayers;
  251. if (con == NULL)
  252. {
  253. CServerHandler sh;
  254. serv = sh.connectToServer();
  255. }
  256. else
  257. {
  258. serv = con;
  259. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  260. }
  261. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  262. it != si->playerInfos.end(); ++it)
  263. {
  264. if((networkMode == SINGLE) //single - one client has all player
  265. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  266. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  267. {
  268. myPlayers.insert(ui8(it->first)); //add player
  269. }
  270. }
  271. if(networkMode != GUEST)
  272. myPlayers.insert(255); //neutral
  273. CStopWatch tmh;
  274. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  275. tlog0 <<"\tGamestate: "<<tmh.getDiff()<<std::endl;
  276. CConnection &c(*serv);
  277. ////////////////////////////////////////////////////
  278. if(networkMode == SINGLE)
  279. {
  280. ui8 pom8;
  281. c << ui8(2) << ui8(1); //new game; one client
  282. c << *si;
  283. c >> pom8;
  284. if(pom8)
  285. throw std::runtime_error("Server cannot open the map!");
  286. else
  287. tlog0 << "Server opened map properly.\n";
  288. }
  289. c << myPlayers;
  290. c >> si;
  291. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDiff()<<std::endl;
  292. gs = const_cast<CGameInfo*>(CGI)->state;
  293. gs->scenarioOps = si;
  294. gs->init(si);
  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. auto cb = make_shared<CCallback>(gs,color,this);
  317. if(!it->second.human)
  318. {
  319. std::string AItoGive = settings["server"]["playerAI"].String();
  320. if(!sensibleAILimit)
  321. AItoGive = "EmptyAI";
  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.get());
  334. battleCallbacks[color] = callbacks[color] = cb;
  335. }
  336. else
  337. {
  338. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  339. battleCallbacks[color] = cbc;
  340. if(!color)
  341. battleints[color] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  342. else
  343. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  344. battleints[color]->init(cbc.get());
  345. }
  346. }
  347. if(si->mode == StartInfo::DUEL)
  348. {
  349. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  350. CPlayerInterface *p = new CPlayerInterface(-1);
  351. p->observerInDuelMode = true;
  352. battleints[254] = playerint[254] = p;
  353. privilagedBattleEventReceivers.push_back(p);
  354. GH.curInt = p;
  355. auto cb = make_shared<CCallback>(gs, -1, this);
  356. battleCallbacks[-1] = callbacks[-1] = cb;
  357. p->init(cb.get());
  358. battleStarted(gs->curB);
  359. }
  360. else
  361. {
  362. loadNeutralBattleAI();
  363. }
  364. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  365. hotSeat = (humanPlayers > 1);
  366. // std::vector<FileInfo> scriptModules;
  367. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  368. // BOOST_FOREACH(FileInfo &m, scriptModules)
  369. // {
  370. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  371. // privilagedGameEventReceivers.push_back(nm);
  372. // privilagedBattleEventReceivers.push_back(nm);
  373. // nm->giveActionCB(this);
  374. // nm->giveInfoCB(this);
  375. // nm->init();
  376. //
  377. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  378. // }
  379. }
  380. template <typename Handler>
  381. void CClient::serialize( Handler &h, const int version )
  382. {
  383. h & hotSeat;
  384. if(h.saving)
  385. {
  386. ui8 players = playerint.size();
  387. h & players;
  388. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  389. {
  390. h & i->first & i->second->dllName;
  391. i->second->serialize(h,version);
  392. }
  393. }
  394. else
  395. {
  396. ui8 players;
  397. h & players;
  398. for(int i=0; i < players; i++)
  399. {
  400. std::string dllname;
  401. ui8 pid;
  402. h & pid & dllname;
  403. CGameInterface *nInt = NULL;
  404. if(dllname.length())
  405. {
  406. if(pid == 255)
  407. {
  408. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  409. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  410. battleints[pid] = cbgi;
  411. cbgi->init(cb);
  412. //TODO? consider serialization
  413. continue;
  414. }
  415. else
  416. nInt = CDynLibHandler::getNewAI(dllname);
  417. }
  418. else
  419. nInt = new CPlayerInterface(pid);
  420. battleCallbacks[pid] = callbacks[pid] = make_shared<CCallback>(gs,pid,this);
  421. battleints[pid] = playerint[pid] = nInt;
  422. nInt->init(callbacks[pid].get());
  423. nInt->serialize(h, version);
  424. }
  425. if(!vstd::contains(battleints, GameConstants::NEUTRAL_PLAYER))
  426. loadNeutralBattleAI();
  427. }
  428. }
  429. void CClient::handlePack( CPack * pack )
  430. {
  431. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  432. if(apply)
  433. {
  434. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  435. apply->applyOnClBefore(this,pack);
  436. tlog5 << "\tMade first apply on cl\n";
  437. gs->apply(pack);
  438. tlog5 << "\tApplied on gs\n";
  439. apply->applyOnClAfter(this,pack);
  440. tlog5 << "\tMade second apply on cl\n";
  441. }
  442. else
  443. {
  444. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  445. }
  446. delete pack;
  447. }
  448. void CClient::updatePaths()
  449. {
  450. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  451. const CGHeroInstance *h = getSelectedHero();
  452. if (h)//if we have selected hero...
  453. calculatePaths(h);
  454. }
  455. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  456. {
  457. }
  458. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  459. {
  460. endGame(false);
  461. LOCPLINT = nullptr; //TODO free res
  462. GH.pushInt(new CBonusSelection(camp));
  463. GH.curInt = CGP;
  464. }
  465. void CClient::stopConnection()
  466. {
  467. terminate = true;
  468. if (serv) //request closing connection
  469. {
  470. tlog0 << "Connection has been requested to be closed.\n";
  471. boost::unique_lock<boost::mutex>(*serv->wmx);
  472. CloseServer close_server;
  473. sendRequest(&close_server, 255);
  474. tlog0 << "Sent closing signal to the server\n";
  475. }
  476. if(connectionHandler)//end connection handler
  477. {
  478. if(connectionHandler->get_id() != boost::this_thread::get_id())
  479. connectionHandler->join();
  480. tlog0 << "Connection handler thread joined" << std::endl;
  481. delete connectionHandler;
  482. connectionHandler = NULL;
  483. }
  484. if (serv) //and delete connection
  485. {
  486. serv->close();
  487. delete serv;
  488. serv = NULL;
  489. tlog3 << "Our socket has been closed." << std::endl;
  490. }
  491. }
  492. void CClient::battleStarted(const BattleInfo * info)
  493. {
  494. BOOST_FOREACH(auto &battleCb, battleCallbacks)
  495. {
  496. if(vstd::contains(info->sides, battleCb.first) || battleCb.first >= GameConstants::PLAYER_LIMIT)
  497. battleCb.second->setBattle(info);
  498. }
  499. // BOOST_FOREACH(ui8 side, info->sides)
  500. // if(battleCallbacks.count(side))
  501. // battleCallbacks[side]->setBattle(info);
  502. CPlayerInterface * att, * def;
  503. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  504. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  505. else
  506. att = NULL;
  507. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  508. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  509. else
  510. def = NULL;
  511. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  512. {
  513. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  514. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1],
  515. Rect((screen->w - 800)/2,
  516. (screen->h - 600)/2, 800, 600), att, def);
  517. }
  518. if(vstd::contains(battleints,info->sides[0]))
  519. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  520. if(vstd::contains(battleints,info->sides[1]))
  521. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  522. if(vstd::contains(battleints,254))
  523. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  524. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  525. {
  526. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  527. }
  528. }
  529. void CClient::battleFinished()
  530. {
  531. BOOST_FOREACH(ui8 side, gs->curB->sides)
  532. if(battleCallbacks.count(side))
  533. battleCallbacks[side]->setBattle(nullptr);
  534. }
  535. void CClient::loadNeutralBattleAI()
  536. {
  537. battleints[255] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  538. auto cbc = make_shared<CBattleCallback>(gs, 255, this);
  539. battleCallbacks[255] = cbc;
  540. battleints[255]->init(cbc.get());
  541. }
  542. void CClient::commitPackage( CPackForClient *pack )
  543. {
  544. CommitPackage cp;
  545. cp.freePack = false;
  546. cp.packToCommit = pack;
  547. sendRequest(&cp, 255);
  548. }
  549. int CClient::getLocalPlayer() const
  550. {
  551. if(LOCPLINT)
  552. return LOCPLINT->playerID;
  553. return getCurrentPlayer();
  554. }
  555. void CClient::calculatePaths(const CGHeroInstance *h)
  556. {
  557. assert(h);
  558. boost::unique_lock<boost::mutex> pathLock(pathMx);
  559. gs->calculatePaths(h, *pathInfo);
  560. }
  561. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  562. {
  563. setThreadName("CClient::commenceTacticPhaseForInt");
  564. try
  565. {
  566. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  567. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  568. {
  569. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  570. sendRequest(&ma, battleInt->playerID);
  571. }
  572. } HANDLE_EXCEPTION
  573. }
  574. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  575. {
  576. if(!h || pathInfo->hero == h)
  577. pathInfo->isValid = false;
  578. }
  579. int CClient::sendRequest(const CPack *request, int player)
  580. {
  581. static ui32 requestCounter = 0;
  582. ui32 requestID = requestCounter++;
  583. tlog5 << boost::format("Sending a request \"%s\". It'll have an ID=%d.\n")
  584. % typeid(*request).name() % requestID;
  585. waitingRequest.pushBack(requestID);
  586. serv->sendPackToServer(*request, player, requestID);
  587. if(vstd::contains(playerint, player))
  588. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  589. return requestID;
  590. }
  591. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  592. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  593. void CServerHandler::startServer()
  594. {
  595. th.update();
  596. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  597. if(verbose)
  598. tlog0 << "Setting up thread calling server: " << th.getDiff() << std::endl;
  599. }
  600. void CServerHandler::waitForServer()
  601. {
  602. if(!serverThread)
  603. startServer();
  604. th.update();
  605. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  606. while(!shared->sr->ready)
  607. {
  608. shared->sr->cond.wait(slock);
  609. }
  610. if(verbose)
  611. tlog0 << "Waiting for server: " << th.getDiff() << std::endl;
  612. }
  613. CConnection * CServerHandler::connectToServer()
  614. {
  615. if(!shared->sr->ready)
  616. waitForServer();
  617. th.update(); //put breakpoint here to attach to server before it does something stupid
  618. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  619. if(verbose)
  620. tlog0<<"\tConnecting to the server: "<<th.getDiff()<<std::endl;
  621. return ret;
  622. }
  623. CServerHandler::CServerHandler(bool runServer /*= false*/)
  624. {
  625. serverThread = NULL;
  626. shared = NULL;
  627. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  628. verbose = false;
  629. 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
  630. try
  631. {
  632. shared = new SharedMem();
  633. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  634. }
  635. CServerHandler::~CServerHandler()
  636. {
  637. delete shared;
  638. delete serverThread; //detaches, not kills thread
  639. }
  640. void CServerHandler::callServer()
  641. {
  642. setThreadName("CServerHandler::callServer");
  643. std::string logName = GVCMIDirs.UserPath + "/server_log.txt";
  644. std::string comm = GameConstants::BIN_DIR + GameConstants::PATH_SEPARATOR + GameConstants::SERVER_NAME + " " + port + " > " + logName;
  645. int result = std::system(comm.c_str());
  646. if (result == 0)
  647. tlog1 << "Server closed correctly\n";
  648. else
  649. tlog0 << "Error: server failed to close correctly or crashed!\n";
  650. }
  651. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  652. {
  653. CConnection *ret = NULL;
  654. while(!ret)
  655. {
  656. try
  657. {
  658. tlog0 << "Establishing connection...\n";
  659. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  660. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  661. NAME);
  662. }
  663. catch(...)
  664. {
  665. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  666. SDL_Delay(2000);
  667. }
  668. }
  669. return ret;
  670. }