Client.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. #include "StdInc.h"
  2. #include "CMusicHandler.h"
  3. #include "../lib/mapping/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/mapping/CMap.h"
  26. #include "../lib/JsonNode.h"
  27. #include "mapHandler.h"
  28. #include "../lib/CConfigHandler.h"
  29. #include "Client.h"
  30. #include "CPreGame.h"
  31. #include "battle/CBattleInterface.h"
  32. #include "../lib/CThreadHelper.h"
  33. #include "../lib/CScriptingModule.h"
  34. #include "../lib/RegisterTypes.h"
  35. #include "gui/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 = nullptr;
  74. void CClient::init()
  75. {
  76. hotSeat = false;
  77. connectionHandler = nullptr;
  78. pathInfo = nullptr;
  79. applier = new CApplier<CBaseForCLApply>;
  80. registerTypes2(*applier);
  81. IObjectInterface::cb = this;
  82. serv = nullptr;
  83. gs = nullptr;
  84. cb = nullptr;
  85. erm = nullptr;
  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 applier;
  100. }
  101. void CClient::waitForMoveAndSend(PlayerColor color)
  102. {
  103. try
  104. {
  105. setThreadName("CClient::waitForMoveAndSend");
  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. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  115. return;
  116. }
  117. HANDLE_EXCEPTION
  118. logNetwork->errorStream() << "We should not be here!";
  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. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  143. logNetwork->errorStream() << e.what();
  144. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  145. {
  146. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  147. throw;
  148. }
  149. }
  150. }
  151. void CClient::save(const std::string & fname)
  152. {
  153. if(gs->curB)
  154. {
  155. logNetwork->errorStream() << "Game cannot be saved during battle!";
  156. return;
  157. }
  158. SaveGame save_game(fname);
  159. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  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. logNetwork->infoStream() << "Closed connection.";
  171. GH.curInt = NULL;
  172. LOCPLINT->terminate_cond.setn(true);
  173. {
  174. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  175. logNetwork->infoStream() << "Ending current game!";
  176. if(GH.topInt())
  177. GH.topInt()->deactivate();
  178. GH.listInt.clear();
  179. GH.objsToBlit.clear();
  180. GH.statusbar = NULL;
  181. logNetwork->infoStream() << "Removed GUI.";
  182. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  183. vstd::clear_pointer(gs);
  184. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  185. LOCPLINT = NULL;
  186. }
  187. while (!playerint.empty())
  188. {
  189. CGameInterface *pint = playerint.begin()->second;
  190. playerint.erase(playerint.begin());
  191. delete pint;
  192. }
  193. callbacks.clear();
  194. logNetwork->infoStream() << "Deleted playerInts.";
  195. logNetwork->infoStream() << "Client stopped.";
  196. }
  197. void CClient::loadGame( const std::string & fname )
  198. {
  199. logNetwork->infoStream() <<"Loading procedure started!";
  200. CServerHandler sh;
  201. sh.startServer();
  202. CStopWatch tmh;
  203. {
  204. auto clientSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  205. auto controlServerSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  206. unique_ptr<CLoadFile> loader;
  207. {
  208. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName);
  209. loadCommonState(checkingLoader);
  210. loader = checkingLoader.decay();
  211. }
  212. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  213. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  214. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  215. pathInfo = make_unique<CPathsInfo>(getMapSize());
  216. CGI->mh->init();
  217. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  218. *loader >> *this;
  219. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  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 std::runtime_error("Server cannot open the savegame!");
  230. else
  231. logNetwork->infoStream() << "Server opened savegame properly.";
  232. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  233. for(auto it = gs->scenarioOps->playerInfos.begin();
  234. it != gs->scenarioOps->playerInfos.end(); ++it)
  235. {
  236. *serv << ui8(it->first.getNum()); //players
  237. }
  238. *serv << ui8(PlayerColor::NEUTRAL.getNum());
  239. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  240. serv->enableStackSendingByID();
  241. serv->disableSmartPointerSerialization();
  242. }
  243. void CClient::newGame( CConnection *con, StartInfo *si )
  244. {
  245. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  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. CConnection &c = *serv;
  257. ////////////////////////////////////////////////////
  258. logNetwork->infoStream() <<"\tWill send info to server...";
  259. CStopWatch tmh;
  260. if(networkMode == SINGLE)
  261. {
  262. ui8 pom8;
  263. c << ui8(2) << ui8(1); //new game; one client
  264. c << *si;
  265. c >> pom8;
  266. if(pom8)
  267. throw std::runtime_error("Server cannot open the map!");
  268. else
  269. logNetwork->infoStream() << "Server opened map properly.";
  270. }
  271. c >> si;
  272. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  273. c.enableStackSendingByID();
  274. c.disableSmartPointerSerialization();
  275. // Initialize game state
  276. gs = new CGameState();
  277. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  278. gs->scenarioOps = si;
  279. gs->init(si);
  280. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  281. // Now after possible random map gen, we know exact player count.
  282. // Inform server about how many players client handles
  283. std::set<PlayerColor> myPlayers;
  284. for(auto it = gs->scenarioOps->playerInfos.begin(); it != gs->scenarioOps->playerInfos.end(); ++it)
  285. {
  286. if((networkMode == SINGLE) //single - one client has all player
  287. || (networkMode != SINGLE && serv->connectionID == it->second.playerID) //multi - client has only "its players"
  288. || (networkMode == HOST && it->second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  289. {
  290. myPlayers.insert(it->first); //add player
  291. }
  292. }
  293. if(networkMode != GUEST)
  294. myPlayers.insert(PlayerColor::NEUTRAL);
  295. c << myPlayers;
  296. // Init map handler
  297. if(gs->map)
  298. {
  299. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  300. CGI->mh->map = gs->map;
  301. logNetwork->infoStream() <<"Creating mapHandler: "<<tmh.getDiff();
  302. CGI->mh->init();
  303. pathInfo = make_unique<CPathsInfo>(getMapSize());
  304. logNetwork->infoStream() <<"Initializing mapHandler (together): "<<tmh.getDiff();
  305. }
  306. int humanPlayers = 0;
  307. int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  308. for(auto it = gs->scenarioOps->playerInfos.begin();
  309. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  310. {
  311. PlayerColor color = it->first;
  312. gs->currentPlayer = color;
  313. if(!vstd::contains(myPlayers, color))
  314. continue;
  315. logNetwork->traceStream() << "Preparing interface for player " << color;
  316. if(si->mode != StartInfo::DUEL)
  317. {
  318. auto cb = make_shared<CCallback>(gs,color,this);
  319. if(it->second.playerID == PlayerSettings::PLAYER_AI)
  320. {
  321. std::string AItoGive = settings["server"]["playerAI"].String();
  322. if(!sensibleAILimit)
  323. AItoGive = "EmptyAI";
  324. else
  325. sensibleAILimit--;
  326. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(AItoGive));
  327. logNetwork->infoStream() << "Player " << static_cast<int>(color.getNum()) << " will be lead by " << AItoGive;
  328. }
  329. else
  330. {
  331. playerint[color] = new CPlayerInterface(color);
  332. humanPlayers++;
  333. }
  334. battleints[color] = playerint[color];
  335. logNetwork->traceStream() << "\tInitializing the interface";
  336. playerint[color]->init(cb.get());
  337. battleCallbacks[color] = callbacks[color] = cb;
  338. }
  339. else
  340. {
  341. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  342. battleCallbacks[color] = cbc;
  343. if(color == PlayerColor(0))
  344. battleints[color] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  345. else
  346. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  347. battleints[color]->init(cbc.get());
  348. }
  349. }
  350. if(si->mode == StartInfo::DUEL)
  351. {
  352. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  353. CPlayerInterface *p = new CPlayerInterface(PlayerColor::NEUTRAL); //TODO: check if neutral really works -- was -1, but CPlayerInterface seems to cooperate with this value not too well
  354. p->observerInDuelMode = true;
  355. battleints[PlayerColor::UNFLAGGABLE] = playerint[PlayerColor::UNFLAGGABLE] = p;
  356. privilagedBattleEventReceivers.push_back(p);
  357. GH.curInt = p;
  358. auto cb = make_shared<CCallback>(gs, boost::optional<PlayerColor>(), this);
  359. battleCallbacks[PlayerColor::NEUTRAL] = callbacks[PlayerColor::NEUTRAL] = cb;
  360. p->init(cb.get());
  361. battleStarted(gs->curB);
  362. }
  363. else
  364. {
  365. loadNeutralBattleAI();
  366. }
  367. serv->addStdVecItems(gs);
  368. hotSeat = (humanPlayers > 1);
  369. // std::vector<FileInfo> scriptModules;
  370. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  371. // BOOST_FOREACH(FileInfo &m, scriptModules)
  372. // {
  373. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  374. // privilagedGameEventReceivers.push_back(nm);
  375. // privilagedBattleEventReceivers.push_back(nm);
  376. // nm->giveActionCB(this);
  377. // nm->giveInfoCB(this);
  378. // nm->init();
  379. //
  380. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  381. // }
  382. }
  383. template <typename Handler>
  384. void CClient::serialize( Handler &h, const int version )
  385. {
  386. h & hotSeat;
  387. if(h.saving)
  388. {
  389. ui8 players = playerint.size();
  390. h & players;
  391. for(auto i = playerint.begin(); i != playerint.end(); i++)
  392. {
  393. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  394. assert(i->first == i->second->playerID);
  395. h & i->first & i->second->dllName & i->second->human;
  396. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  397. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  398. }
  399. }
  400. else
  401. {
  402. ui8 players = 0; //fix for uninitialized warning
  403. h & players;
  404. for(int i=0; i < players; i++)
  405. {
  406. std::string dllname;
  407. PlayerColor pid;
  408. bool isHuman = false;
  409. h & pid & dllname & isHuman;
  410. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  411. CGameInterface *nInt = nullptr;
  412. if(dllname.length())
  413. {
  414. if(pid == PlayerColor::NEUTRAL)
  415. {
  416. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  417. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  418. battleints[pid] = cbgi;
  419. cbgi->init(cb);
  420. //TODO? consider serialization
  421. continue;
  422. }
  423. else
  424. {
  425. assert(!isHuman);
  426. nInt = CDynLibHandler::getNewAI(dllname);
  427. }
  428. }
  429. else
  430. {
  431. assert(isHuman);
  432. nInt = new CPlayerInterface(pid);
  433. }
  434. nInt->dllName = dllname;
  435. nInt->human = isHuman;
  436. nInt->playerID = pid;
  437. battleCallbacks[pid] = callbacks[pid] = make_shared<CCallback>(gs,pid,this);
  438. battleints[pid] = playerint[pid] = nInt;
  439. nInt->init(callbacks[pid].get());
  440. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  441. }
  442. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  443. loadNeutralBattleAI();
  444. }
  445. }
  446. void CClient::handlePack( CPack * pack )
  447. {
  448. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  449. if(apply)
  450. {
  451. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  452. apply->applyOnClBefore(this,pack);
  453. logNetwork->traceStream() << "\tMade first apply on cl";
  454. gs->apply(pack);
  455. logNetwork->traceStream() << "\tApplied on gs";
  456. apply->applyOnClAfter(this,pack);
  457. logNetwork->traceStream() << "\tMade second apply on cl";
  458. }
  459. else
  460. {
  461. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  462. }
  463. delete pack;
  464. }
  465. void CClient::updatePaths()
  466. {
  467. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  468. const CGHeroInstance *h = getSelectedHero();
  469. if (h)//if we have selected hero...
  470. calculatePaths(h);
  471. }
  472. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  473. {
  474. }
  475. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  476. {
  477. GH.pushInt(new CBonusSelection(camp));
  478. }
  479. void CClient::stopConnection()
  480. {
  481. terminate = true;
  482. if (serv) //request closing connection
  483. {
  484. logNetwork->infoStream() << "Connection has been requested to be closed.";
  485. boost::unique_lock<boost::mutex>(*serv->wmx);
  486. CloseServer close_server;
  487. sendRequest(&close_server, PlayerColor::NEUTRAL);
  488. logNetwork->infoStream() << "Sent closing signal to the server";
  489. }
  490. if(connectionHandler)//end connection handler
  491. {
  492. if(connectionHandler->get_id() != boost::this_thread::get_id())
  493. connectionHandler->join();
  494. logNetwork->infoStream() << "Connection handler thread joined";
  495. delete connectionHandler;
  496. connectionHandler = NULL;
  497. }
  498. if (serv) //and delete connection
  499. {
  500. serv->close();
  501. delete serv;
  502. serv = NULL;
  503. logNetwork->warnStream() << "Our socket has been closed.";
  504. }
  505. }
  506. void CClient::battleStarted(const BattleInfo * info)
  507. {
  508. BOOST_FOREACH(auto &battleCb, battleCallbacks)
  509. {
  510. if(vstd::contains(info->sides, battleCb.first) || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  511. battleCb.second->setBattle(info);
  512. }
  513. // BOOST_FOREACH(ui8 side, info->sides)
  514. // if(battleCallbacks.count(side))
  515. // battleCallbacks[side]->setBattle(info);
  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. {
  527. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  528. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1],
  529. Rect((screen->w - 800)/2,
  530. (screen->h - 600)/2, 800, 600), att, def);
  531. }
  532. if(vstd::contains(battleints,info->sides[0]))
  533. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  534. if(vstd::contains(battleints,info->sides[1]))
  535. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  536. if(vstd::contains(battleints,PlayerColor::UNFLAGGABLE))
  537. battleints[PlayerColor::UNFLAGGABLE]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  538. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  539. {
  540. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  541. }
  542. }
  543. void CClient::battleFinished()
  544. {
  545. BOOST_FOREACH(PlayerColor side, gs->curB->sides)
  546. if(battleCallbacks.count(side))
  547. battleCallbacks[side]->setBattle(nullptr);
  548. }
  549. void CClient::loadNeutralBattleAI()
  550. {
  551. battleints[PlayerColor::NEUTRAL] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  552. auto cbc = make_shared<CBattleCallback>(gs, PlayerColor::NEUTRAL, this);
  553. battleCallbacks[PlayerColor::NEUTRAL] = cbc;
  554. battleints[PlayerColor::NEUTRAL]->init(cbc.get());
  555. }
  556. void CClient::commitPackage( CPackForClient *pack )
  557. {
  558. CommitPackage cp;
  559. cp.freePack = false;
  560. cp.packToCommit = pack;
  561. sendRequest(&cp, PlayerColor::NEUTRAL);
  562. }
  563. PlayerColor CClient::getLocalPlayer() const
  564. {
  565. if(LOCPLINT)
  566. return LOCPLINT->playerID;
  567. return getCurrentPlayer();
  568. }
  569. void CClient::calculatePaths(const CGHeroInstance *h)
  570. {
  571. assert(h);
  572. boost::unique_lock<boost::mutex> pathLock(pathMx);
  573. gs->calculatePaths(h, *pathInfo);
  574. }
  575. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  576. {
  577. setThreadName("CClient::commenceTacticPhaseForInt");
  578. try
  579. {
  580. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  581. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  582. {
  583. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  584. sendRequest(&ma, battleInt->playerID);
  585. }
  586. } HANDLE_EXCEPTION
  587. }
  588. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  589. {
  590. if(!h || pathInfo->hero == h)
  591. pathInfo->isValid = false;
  592. }
  593. int CClient::sendRequest(const CPack *request, PlayerColor player)
  594. {
  595. static ui32 requestCounter = 0;
  596. ui32 requestID = requestCounter++;
  597. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  598. % typeid(*request).name() % requestID;
  599. waitingRequest.pushBack(requestID);
  600. serv->sendPackToServer(*request, player, requestID);
  601. if(vstd::contains(playerint, player))
  602. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  603. return requestID;
  604. }
  605. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  606. {
  607. endGame(false);
  608. LOCPLINT = nullptr; //TODO free res
  609. GH.curInt = CGPreGame::create();
  610. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  611. auto finisher = [&]()
  612. {
  613. if(camp->mapsRemaining.size())
  614. proposeNextMission(camp);
  615. else
  616. finishCampaign(camp);
  617. };
  618. if(epilogue.hasPrologEpilog)
  619. {
  620. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  621. }
  622. else
  623. {
  624. finisher();
  625. }
  626. }
  627. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  628. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  629. void CServerHandler::startServer()
  630. {
  631. th.update();
  632. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  633. if(verbose)
  634. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  635. }
  636. void CServerHandler::waitForServer()
  637. {
  638. if(!serverThread)
  639. startServer();
  640. th.update();
  641. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  642. while(!shared->sr->ready)
  643. {
  644. shared->sr->cond.wait(slock);
  645. }
  646. if(verbose)
  647. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  648. }
  649. CConnection * CServerHandler::connectToServer()
  650. {
  651. if(!shared->sr->ready)
  652. waitForServer();
  653. th.update(); //put breakpoint here to attach to server before it does something stupid
  654. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  655. if(verbose)
  656. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  657. return ret;
  658. }
  659. CServerHandler::CServerHandler(bool runServer /*= false*/)
  660. {
  661. serverThread = NULL;
  662. shared = NULL;
  663. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  664. verbose = true;
  665. 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
  666. try
  667. {
  668. shared = new SharedMem();
  669. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  670. }
  671. CServerHandler::~CServerHandler()
  672. {
  673. delete shared;
  674. delete serverThread; //detaches, not kills thread
  675. }
  676. void CServerHandler::callServer()
  677. {
  678. setThreadName("CServerHandler::callServer");
  679. std::string logName = VCMIDirs::get().localPath() + "/server_log.txt";
  680. std::string comm = VCMIDirs::get().serverPath() + " " + port + " > " + logName;
  681. int result = std::system(comm.c_str());
  682. if (result == 0)
  683. logNetwork->infoStream() << "Server closed correctly";
  684. else
  685. {
  686. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  687. logNetwork->errorStream() << "Check " << logName << " for more info";
  688. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  689. }
  690. }
  691. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  692. {
  693. CConnection *ret = NULL;
  694. while(!ret)
  695. {
  696. try
  697. {
  698. logNetwork->infoStream() << "Establishing connection...";
  699. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  700. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  701. NAME);
  702. }
  703. catch(...)
  704. {
  705. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  706. SDL_Delay(2000);
  707. }
  708. }
  709. return ret;
  710. }