Client.cpp 26 KB

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