Client.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. #include "CMT.h"
  37. extern std::string NAME;
  38. namespace intpr = boost::interprocess;
  39. /*
  40. * Client.cpp, part of VCMI engine
  41. *
  42. * Authors: listed in file AUTHORS in main folder
  43. *
  44. * License: GNU General Public License v2.0 or later
  45. * Full text of license available in license.txt file, in main folder
  46. *
  47. */
  48. template <typename T> class CApplyOnCL;
  49. class CBaseForCLApply
  50. {
  51. public:
  52. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  53. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  54. virtual ~CBaseForCLApply(){}
  55. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  56. {
  57. return new CApplyOnCL<U>;
  58. }
  59. };
  60. template <typename T> class CApplyOnCL : public CBaseForCLApply
  61. {
  62. public:
  63. void applyOnClAfter(CClient *cl, void *pack) const
  64. {
  65. T *ptr = static_cast<T*>(pack);
  66. ptr->applyCl(cl);
  67. }
  68. void applyOnClBefore(CClient *cl, void *pack) const
  69. {
  70. T *ptr = static_cast<T*>(pack);
  71. ptr->applyFirstCl(cl);
  72. }
  73. };
  74. static CApplier<CBaseForCLApply> *applier = nullptr;
  75. void CClient::init()
  76. {
  77. hotSeat = false;
  78. connectionHandler = nullptr;
  79. pathInfo = nullptr;
  80. applier = new CApplier<CBaseForCLApply>;
  81. registerTypes2(*applier);
  82. IObjectInterface::cb = this;
  83. serv = nullptr;
  84. gs = 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 = nullptr;
  126. while(!terminate)
  127. {
  128. pack = serv->retreivePack(); //get the package from the server
  129. if (terminate)
  130. {
  131. delete pack;
  132. pack = nullptr;
  133. break;
  134. }
  135. handlePack(pack);
  136. pack = nullptr;
  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 = nullptr;
  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 = nullptr;
  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 = nullptr;
  186. }
  187. playerint.clear();
  188. callbacks.clear();
  189. battleCallbacks.clear();
  190. logNetwork->infoStream() << "Deleted playerInts.";
  191. logNetwork->infoStream() << "Client stopped.";
  192. }
  193. void CClient::loadGame( const std::string & fname )
  194. {
  195. logNetwork->infoStream() <<"Loading procedure started!";
  196. CServerHandler sh;
  197. sh.startServer();
  198. CStopWatch tmh;
  199. try
  200. {
  201. std::string clientSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  202. std::string controlServerSaveName;
  203. if (CResourceHandler::get()->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  204. {
  205. controlServerSaveName = CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  206. }
  207. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  208. {
  209. controlServerSaveName = clientSaveName.substr(0, clientSaveName.find_last_of(".")) + ".vsgm1";
  210. CResourceHandler::get()->createResource(controlServerSaveName, true);
  211. }
  212. if(clientSaveName.empty())
  213. throw std::runtime_error("Cannot open client part of " + fname);
  214. if(controlServerSaveName.empty())
  215. throw std::runtime_error("Cannot open server part of " + fname);
  216. unique_ptr<CLoadFile> loader;
  217. {
  218. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName);
  219. loadCommonState(checkingLoader);
  220. loader = checkingLoader.decay();
  221. }
  222. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  223. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  224. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  225. pathInfo = make_unique<CPathsInfo>(getMapSize());
  226. CGI->mh->init();
  227. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  228. *loader >> *this;
  229. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  230. }
  231. catch(std::exception &e)
  232. {
  233. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  234. throw; //obviously we cannot continue here
  235. }
  236. serv = sh.connectToServer();
  237. serv->addStdVecItems(gs);
  238. tmh.update();
  239. ui8 pom8;
  240. *serv << ui8(3) << ui8(1); //load game; one client
  241. *serv << fname;
  242. *serv >> pom8;
  243. if(pom8)
  244. throw std::runtime_error("Server cannot open the savegame!");
  245. else
  246. logNetwork->infoStream() << "Server opened savegame properly.";
  247. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  248. for(auto it = gs->scenarioOps->playerInfos.begin();
  249. it != gs->scenarioOps->playerInfos.end(); ++it)
  250. {
  251. *serv << ui8(it->first.getNum()); //players
  252. }
  253. *serv << ui8(PlayerColor::NEUTRAL.getNum());
  254. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  255. serv->enableStackSendingByID();
  256. serv->disableSmartPointerSerialization();
  257. }
  258. void CClient::newGame( CConnection *con, StartInfo *si )
  259. {
  260. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  261. if (con == nullptr)
  262. {
  263. CServerHandler sh;
  264. serv = sh.connectToServer();
  265. }
  266. else
  267. {
  268. serv = con;
  269. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  270. }
  271. CConnection &c = *serv;
  272. ////////////////////////////////////////////////////
  273. logNetwork->infoStream() <<"\tWill send info to server...";
  274. CStopWatch tmh;
  275. if(networkMode == SINGLE)
  276. {
  277. ui8 pom8;
  278. c << ui8(2) << ui8(1); //new game; one client
  279. c << *si;
  280. c >> pom8;
  281. if(pom8)
  282. throw std::runtime_error("Server cannot open the map!");
  283. else
  284. logNetwork->infoStream() << "Server opened map properly.";
  285. }
  286. c >> si;
  287. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  288. c.enableStackSendingByID();
  289. c.disableSmartPointerSerialization();
  290. // Initialize game state
  291. gs = new CGameState();
  292. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  293. gs->scenarioOps = si;
  294. gs->init(si);
  295. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  296. // Now after possible random map gen, we know exact player count.
  297. // Inform server about how many players client handles
  298. std::set<PlayerColor> myPlayers;
  299. for(auto it = gs->scenarioOps->playerInfos.begin(); it != gs->scenarioOps->playerInfos.end(); ++it)
  300. {
  301. if((networkMode == SINGLE) //single - one client has all player
  302. || (networkMode != SINGLE && serv->connectionID == it->second.playerID) //multi - client has only "its players"
  303. || (networkMode == HOST && it->second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  304. {
  305. myPlayers.insert(it->first); //add player
  306. }
  307. }
  308. if(networkMode != GUEST)
  309. myPlayers.insert(PlayerColor::NEUTRAL);
  310. c << myPlayers;
  311. // Init map handler
  312. if(gs->map)
  313. {
  314. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  315. CGI->mh->map = gs->map;
  316. logNetwork->infoStream() <<"Creating mapHandler: "<<tmh.getDiff();
  317. CGI->mh->init();
  318. pathInfo = make_unique<CPathsInfo>(getMapSize());
  319. logNetwork->infoStream() <<"Initializing mapHandler (together): "<<tmh.getDiff();
  320. }
  321. int humanPlayers = 0;
  322. for(auto it = gs->scenarioOps->playerInfos.begin();
  323. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  324. {
  325. PlayerColor color = it->first;
  326. gs->currentPlayer = color;
  327. if(!vstd::contains(myPlayers, color))
  328. continue;
  329. logNetwork->traceStream() << "Preparing interface for player " << color;
  330. if(si->mode != StartInfo::DUEL)
  331. {
  332. if(it->second.playerID == PlayerSettings::PLAYER_AI)
  333. {
  334. auto AiToGive = aiNameForPlayer(it->second, false);
  335. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  336. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  337. }
  338. else
  339. {
  340. installNewPlayerInterface(make_shared<CPlayerInterface>(color), color);
  341. humanPlayers++;
  342. }
  343. }
  344. else
  345. {
  346. std::string AItoGive = aiNameForPlayer(it->second, true);
  347. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  348. }
  349. }
  350. if(si->mode == StartInfo::DUEL)
  351. {
  352. if(!gNoGUI)
  353. {
  354. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  355. auto p = make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  356. p->observerInDuelMode = true;
  357. installNewPlayerInterface(p, boost::none);
  358. GH.curInt = p.get();
  359. }
  360. battleStarted(gs->curB);
  361. }
  362. else
  363. {
  364. loadNeutralBattleAI();
  365. }
  366. serv->addStdVecItems(gs);
  367. hotSeat = (humanPlayers > 1);
  368. // std::vector<FileInfo> scriptModules;
  369. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  370. // BOOST_FOREACH(FileInfo &m, scriptModules)
  371. // {
  372. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  373. // privilagedGameEventReceivers.push_back(nm);
  374. // privilagedBattleEventReceivers.push_back(nm);
  375. // nm->giveActionCB(this);
  376. // nm->giveInfoCB(this);
  377. // nm->init();
  378. //
  379. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  380. // }
  381. }
  382. template <typename Handler>
  383. void CClient::serialize( Handler &h, const int version )
  384. {
  385. h & hotSeat;
  386. if(h.saving)
  387. {
  388. ui8 players = playerint.size();
  389. h & players;
  390. for(auto i = playerint.begin(); i != playerint.end(); i++)
  391. {
  392. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  393. assert(i->first == i->second->playerID);
  394. h & i->first & i->second->dllName & i->second->human;
  395. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  396. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  397. }
  398. }
  399. else
  400. {
  401. ui8 players = 0; //fix for uninitialized warning
  402. h & players;
  403. for(int i=0; i < players; i++)
  404. {
  405. std::string dllname;
  406. PlayerColor pid;
  407. bool isHuman = false;
  408. h & pid & dllname & isHuman;
  409. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  410. shared_ptr<CGameInterface> nInt;
  411. if(dllname.length())
  412. {
  413. if(pid == PlayerColor::NEUTRAL)
  414. {
  415. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  416. //TODO? consider serialization
  417. continue;
  418. }
  419. else
  420. {
  421. assert(!isHuman);
  422. nInt = CDynLibHandler::getNewAI(dllname);
  423. }
  424. }
  425. else
  426. {
  427. assert(isHuman);
  428. nInt = make_shared<CPlayerInterface>(pid);
  429. }
  430. nInt->dllName = dllname;
  431. nInt->human = isHuman;
  432. nInt->playerID = pid;
  433. installNewPlayerInterface(nInt, pid);
  434. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  435. }
  436. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  437. loadNeutralBattleAI();
  438. }
  439. }
  440. void CClient::handlePack( CPack * pack )
  441. {
  442. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  443. if(apply)
  444. {
  445. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  446. apply->applyOnClBefore(this,pack);
  447. logNetwork->traceStream() << "\tMade first apply on cl";
  448. gs->apply(pack);
  449. logNetwork->traceStream() << "\tApplied on gs";
  450. apply->applyOnClAfter(this,pack);
  451. logNetwork->traceStream() << "\tMade second apply on cl";
  452. }
  453. else
  454. {
  455. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  456. }
  457. delete pack;
  458. }
  459. void CClient::updatePaths()
  460. {
  461. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  462. const CGHeroInstance *h = getSelectedHero();
  463. if (h)//if we have selected hero...
  464. calculatePaths(h);
  465. }
  466. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  467. {
  468. }
  469. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  470. {
  471. GH.pushInt(new CBonusSelection(camp));
  472. }
  473. void CClient::stopConnection()
  474. {
  475. terminate = true;
  476. if (serv) //request closing connection
  477. {
  478. logNetwork->infoStream() << "Connection has been requested to be closed.";
  479. boost::unique_lock<boost::mutex>(*serv->wmx);
  480. CloseServer close_server;
  481. sendRequest(&close_server, PlayerColor::NEUTRAL);
  482. logNetwork->infoStream() << "Sent closing signal to the server";
  483. }
  484. if(connectionHandler)//end connection handler
  485. {
  486. if(connectionHandler->get_id() != boost::this_thread::get_id())
  487. connectionHandler->join();
  488. logNetwork->infoStream() << "Connection handler thread joined";
  489. delete connectionHandler;
  490. connectionHandler = nullptr;
  491. }
  492. if (serv) //and delete connection
  493. {
  494. serv->close();
  495. delete serv;
  496. serv = nullptr;
  497. logNetwork->warnStream() << "Our socket has been closed.";
  498. }
  499. }
  500. void CClient::battleStarted(const BattleInfo * info)
  501. {
  502. BOOST_FOREACH(auto &battleCb, battleCallbacks)
  503. {
  504. if(vstd::contains(info->sides, battleCb.first) || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  505. battleCb.second->setBattle(info);
  506. }
  507. // BOOST_FOREACH(ui8 side, info->sides)
  508. // if(battleCallbacks.count(side))
  509. // battleCallbacks[side]->setBattle(info);
  510. shared_ptr<CPlayerInterface> att, def;
  511. //If quick combat is not, do not prepare interfaces for battleint
  512. if(!settings["adventure"]["quickCombat"].Bool())
  513. {
  514. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  515. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[info->sides[0]] );
  516. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  517. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[info->sides[1]] );
  518. }
  519. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  520. {
  521. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  522. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1],
  523. Rect((screen->w - 800)/2,
  524. (screen->h - 600)/2, 800, 600), att, def);
  525. }
  526. if(vstd::contains(battleints,info->sides[0]))
  527. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  528. if(vstd::contains(battleints,info->sides[1]))
  529. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  530. if(vstd::contains(battleints,PlayerColor::UNFLAGGABLE))
  531. battleints[PlayerColor::UNFLAGGABLE]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  532. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  533. {
  534. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  535. }
  536. }
  537. void CClient::battleFinished()
  538. {
  539. BOOST_FOREACH(PlayerColor side, gs->curB->sides)
  540. if(battleCallbacks.count(side))
  541. battleCallbacks[side]->setBattle(nullptr);
  542. }
  543. void CClient::loadNeutralBattleAI()
  544. {
  545. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  546. }
  547. void CClient::commitPackage( CPackForClient *pack )
  548. {
  549. CommitPackage cp;
  550. cp.freePack = false;
  551. cp.packToCommit = pack;
  552. sendRequest(&cp, PlayerColor::NEUTRAL);
  553. }
  554. PlayerColor CClient::getLocalPlayer() const
  555. {
  556. if(LOCPLINT)
  557. return LOCPLINT->playerID;
  558. return getCurrentPlayer();
  559. }
  560. void CClient::calculatePaths(const CGHeroInstance *h)
  561. {
  562. assert(h);
  563. boost::unique_lock<boost::mutex> pathLock(pathMx);
  564. gs->calculatePaths(h, *pathInfo);
  565. }
  566. void CClient::commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt)
  567. {
  568. setThreadName("CClient::commenceTacticPhaseForInt");
  569. try
  570. {
  571. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  572. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  573. {
  574. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  575. sendRequest(&ma, battleInt->playerID);
  576. }
  577. } HANDLE_EXCEPTION
  578. }
  579. void CClient::invalidatePaths(const CGHeroInstance *h /*= nullptr*/)
  580. {
  581. if(!h || pathInfo->hero == h)
  582. pathInfo->isValid = false;
  583. }
  584. int CClient::sendRequest(const CPack *request, PlayerColor player)
  585. {
  586. static ui32 requestCounter = 0;
  587. ui32 requestID = requestCounter++;
  588. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  589. % typeid(*request).name() % requestID;
  590. waitingRequest.pushBack(requestID);
  591. serv->sendPackToServer(*request, player, requestID);
  592. if(vstd::contains(playerint, player))
  593. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  594. return requestID;
  595. }
  596. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  597. {
  598. endGame(false);
  599. LOCPLINT = nullptr; //TODO free res
  600. GH.curInt = CGPreGame::create();
  601. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  602. auto finisher = [&]()
  603. {
  604. if(camp->mapsRemaining.size())
  605. proposeNextMission(camp);
  606. else
  607. finishCampaign(camp);
  608. };
  609. if(epilogue.hasPrologEpilog)
  610. {
  611. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  612. }
  613. else
  614. {
  615. finisher();
  616. }
  617. }
  618. void CClient::installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  619. {
  620. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  621. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  622. if(!color)
  623. privilagedGameEventReceivers.push_back(gameInterface);
  624. playerint[colorUsed] = gameInterface;
  625. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  626. auto cb = make_shared<CCallback>(gs, color, this);
  627. callbacks[colorUsed] = cb;
  628. battleCallbacks[colorUsed] = cb;
  629. gameInterface->init(cb);
  630. installNewBattleInterface(gameInterface, color, false);
  631. }
  632. void CClient::installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  633. {
  634. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  635. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  636. if(!color)
  637. privilagedBattleEventReceivers.push_back(battleInterface);
  638. battleints[colorUsed] = battleInterface;
  639. if(needCallback)
  640. {
  641. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  642. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  643. battleCallbacks[colorUsed] = cbc;
  644. battleInterface->init(cbc);
  645. }
  646. }
  647. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  648. {
  649. if(ps.name.size())
  650. {
  651. std::string filename = VCMIDirs::get().libraryPath() + "/AI/" + VCMIDirs::get().libraryName(ps.name);
  652. if(boost::filesystem::exists(filename))
  653. return ps.name;
  654. }
  655. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  656. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  657. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  658. //TODO what about human players
  659. if(battleints.size() >= sensibleAILimit)
  660. return badAI;
  661. return goodAI;
  662. }
  663. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  664. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  665. void CServerHandler::startServer()
  666. {
  667. th.update();
  668. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  669. if(verbose)
  670. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  671. }
  672. void CServerHandler::waitForServer()
  673. {
  674. if(!serverThread)
  675. startServer();
  676. th.update();
  677. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  678. while(!shared->sr->ready)
  679. {
  680. shared->sr->cond.wait(slock);
  681. }
  682. if(verbose)
  683. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  684. }
  685. CConnection * CServerHandler::connectToServer()
  686. {
  687. if(!shared->sr->ready)
  688. waitForServer();
  689. th.update(); //put breakpoint here to attach to server before it does something stupid
  690. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  691. if(verbose)
  692. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  693. return ret;
  694. }
  695. CServerHandler::CServerHandler(bool runServer /*= false*/)
  696. {
  697. serverThread = nullptr;
  698. shared = nullptr;
  699. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  700. verbose = true;
  701. 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
  702. try
  703. {
  704. shared = new SharedMem();
  705. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  706. }
  707. CServerHandler::~CServerHandler()
  708. {
  709. delete shared;
  710. delete serverThread; //detaches, not kills thread
  711. }
  712. void CServerHandler::callServer()
  713. {
  714. setThreadName("CServerHandler::callServer");
  715. std::string logName = VCMIDirs::get().localPath() + "/server_log.txt";
  716. std::string comm = VCMIDirs::get().serverPath() + " --port=" + port + " > " + logName;
  717. int result = std::system(comm.c_str());
  718. if (result == 0)
  719. logNetwork->infoStream() << "Server closed correctly";
  720. else
  721. {
  722. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  723. logNetwork->errorStream() << "Check " << logName << " for more info";
  724. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  725. }
  726. }
  727. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  728. {
  729. CConnection *ret = nullptr;
  730. while(!ret)
  731. {
  732. try
  733. {
  734. logNetwork->infoStream() << "Establishing connection...";
  735. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  736. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  737. NAME);
  738. }
  739. catch(...)
  740. {
  741. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  742. SDL_Delay(2000);
  743. }
  744. }
  745. return ret;
  746. }