NetPacksClient.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. /*
  2. * NetPacksClient.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ClientNetPackVisitors.h"
  12. #include "Client.h"
  13. #include "CPlayerInterface.h"
  14. #include "CGameInfo.h"
  15. #include "windows/GUIClasses.h"
  16. #include "adventureMap/mapHandler.h"
  17. #include "adventureMap/CInGameConsole.h"
  18. #include "battle/BattleInterface.h"
  19. #include "gui/CGuiHandler.h"
  20. #include "widgets/MiscWidgets.h"
  21. #include "CMT.h"
  22. #include "CServerHandler.h"
  23. #include "../CCallback.h"
  24. #include "../lib/filesystem/Filesystem.h"
  25. #include "../lib/filesystem/FileInfo.h"
  26. #include "../lib/serializer/Connection.h"
  27. #include "../lib/serializer/BinarySerializer.h"
  28. #include "../lib/CGeneralTextHandler.h"
  29. #include "../lib/CHeroHandler.h"
  30. #include "../lib/VCMI_Lib.h"
  31. #include "../lib/mapping/CMap.h"
  32. #include "../lib/VCMIDirs.h"
  33. #include "../lib/spells/CSpellHandler.h"
  34. #include "../lib/CSoundBase.h"
  35. #include "../lib/StartInfo.h"
  36. #include "../lib/CConfigHandler.h"
  37. #include "../lib/mapping/CCampaignHandler.h"
  38. #include "../lib/CGameState.h"
  39. #include "../lib/CStack.h"
  40. #include "../lib/battle/BattleInfo.h"
  41. #include "../lib/GameConstants.h"
  42. #include "../lib/CPlayerState.h"
  43. // TODO: as Tow suggested these template should all be part of CClient
  44. // This will require rework spectator interface properly though
  45. template<typename T, typename ... Args, typename ... Args2>
  46. bool callOnlyThatInterface(CClient & cl, PlayerColor player, void (T::*ptr)(Args...), Args2 && ...args)
  47. {
  48. if(vstd::contains(cl.playerint, player))
  49. {
  50. ((*cl.playerint[player]).*ptr)(std::forward<Args2>(args)...);
  51. return true;
  52. }
  53. return false;
  54. }
  55. template<typename T, typename ... Args, typename ... Args2>
  56. bool callInterfaceIfPresent(CClient & cl, PlayerColor player, void (T::*ptr)(Args...), Args2 && ...args)
  57. {
  58. bool called = callOnlyThatInterface(cl, player, ptr, std::forward<Args2>(args)...);
  59. return called;
  60. }
  61. template<typename T, typename ... Args, typename ... Args2>
  62. void callOnlyThatBattleInterface(CClient & cl, PlayerColor player, void (T::*ptr)(Args...), Args2 && ...args)
  63. {
  64. if(vstd::contains(cl.battleints,player))
  65. ((*cl.battleints[player]).*ptr)(std::forward<Args2>(args)...);
  66. if(cl.additionalBattleInts.count(player))
  67. {
  68. for(auto bInt : cl.additionalBattleInts[player])
  69. ((*bInt).*ptr)(std::forward<Args2>(args)...);
  70. }
  71. }
  72. template<typename T, typename ... Args, typename ... Args2>
  73. void callBattleInterfaceIfPresent(CClient & cl, PlayerColor player, void (T::*ptr)(Args...), Args2 && ...args)
  74. {
  75. callOnlyThatInterface(cl, player, ptr, std::forward<Args2>(args)...);
  76. }
  77. //calls all normal interfaces and privileged ones, playerints may be updated when iterating over it, so we need a copy
  78. template<typename T, typename ... Args, typename ... Args2>
  79. void callAllInterfaces(CClient & cl, void (T::*ptr)(Args...), Args2 && ...args)
  80. {
  81. for(auto pInt : cl.playerint)
  82. ((*pInt.second).*ptr)(std::forward<Args2>(args)...);
  83. }
  84. //calls all normal interfaces and privileged ones, playerints may be updated when iterating over it, so we need a copy
  85. template<typename T, typename ... Args, typename ... Args2>
  86. void callBattleInterfaceIfPresentForBothSides(CClient & cl, void (T::*ptr)(Args...), Args2 && ...args)
  87. {
  88. callOnlyThatBattleInterface(cl, cl.gameState()->curB->sides[0].color, ptr, std::forward<Args2>(args)...);
  89. callOnlyThatBattleInterface(cl, cl.gameState()->curB->sides[1].color, ptr, std::forward<Args2>(args)...);
  90. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool() && LOCPLINT->battleInt)
  91. {
  92. callOnlyThatBattleInterface(cl, PlayerColor::SPECTATOR, ptr, std::forward<Args2>(args)...);
  93. }
  94. }
  95. void ApplyClientNetPackVisitor::visitSetResources(SetResources & pack)
  96. {
  97. //todo: inform on actual resource set transfered
  98. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::receivedResource);
  99. }
  100. void ApplyClientNetPackVisitor::visitSetPrimSkill(SetPrimSkill & pack)
  101. {
  102. const CGHeroInstance * h = cl.getHero(pack.id);
  103. if(!h)
  104. {
  105. logNetwork->error("Cannot find hero with pack.id %d", pack.id.getNum());
  106. return;
  107. }
  108. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroPrimarySkillChanged, h, pack.which, pack.val);
  109. }
  110. void ApplyClientNetPackVisitor::visitSetSecSkill(SetSecSkill & pack)
  111. {
  112. const CGHeroInstance *h = cl.getHero(pack.id);
  113. if(!h)
  114. {
  115. logNetwork->error("Cannot find hero with pack.id %d", pack.id.getNum());
  116. return;
  117. }
  118. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroSecondarySkillChanged, h, pack.which, pack.val);
  119. }
  120. void ApplyClientNetPackVisitor::visitHeroVisitCastle(HeroVisitCastle & pack)
  121. {
  122. const CGHeroInstance *h = cl.getHero(pack.hid);
  123. if(pack.start())
  124. {
  125. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroVisitsTown, h, gs.getTown(pack.tid));
  126. }
  127. }
  128. void ApplyClientNetPackVisitor::visitSetMana(SetMana & pack)
  129. {
  130. const CGHeroInstance *h = cl.getHero(pack.hid);
  131. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroManaPointsChanged, h);
  132. }
  133. void ApplyClientNetPackVisitor::visitSetMovePoints(SetMovePoints & pack)
  134. {
  135. const CGHeroInstance *h = cl.getHero(pack.hid);
  136. cl.invalidatePaths();
  137. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroMovePointsChanged, h);
  138. }
  139. void ApplyClientNetPackVisitor::visitFoWChange(FoWChange & pack)
  140. {
  141. for(auto &i : cl.playerint)
  142. {
  143. if(cl.getPlayerRelations(i.first, pack.player) == PlayerRelations::SAME_PLAYER && pack.waitForDialogs && LOCPLINT == i.second.get())
  144. {
  145. LOCPLINT->waitWhileDialog();
  146. }
  147. if(cl.getPlayerRelations(i.first, pack.player) != PlayerRelations::ENEMIES)
  148. {
  149. if(pack.mode)
  150. i.second->tileRevealed(pack.tiles);
  151. else
  152. i.second->tileHidden(pack.tiles);
  153. }
  154. }
  155. cl.invalidatePaths();
  156. }
  157. static void dispatchGarrisonChange(CClient & cl, ObjectInstanceID army1, ObjectInstanceID army2)
  158. {
  159. auto obj1 = cl.getObj(army1);
  160. if(!obj1)
  161. {
  162. logNetwork->error("Cannot find army with pack.id %d", army1.getNum());
  163. return;
  164. }
  165. callInterfaceIfPresent(cl, obj1->tempOwner, &IGameEventsReceiver::garrisonsChanged, army1, army2);
  166. if(army2 != ObjectInstanceID() && army2 != army1)
  167. {
  168. auto obj2 = cl.getObj(army2);
  169. if(!obj2)
  170. {
  171. logNetwork->error("Cannot find army with pack.id %d", army2.getNum());
  172. return;
  173. }
  174. if(obj1->tempOwner != obj2->tempOwner)
  175. callInterfaceIfPresent(cl, obj2->tempOwner, &IGameEventsReceiver::garrisonsChanged, army1, army2);
  176. }
  177. }
  178. void ApplyClientNetPackVisitor::visitChangeStackCount(ChangeStackCount & pack)
  179. {
  180. dispatchGarrisonChange(cl, pack.army, ObjectInstanceID());
  181. }
  182. void ApplyClientNetPackVisitor::visitSetStackType(SetStackType & pack)
  183. {
  184. dispatchGarrisonChange(cl, pack.army, ObjectInstanceID());
  185. }
  186. void ApplyClientNetPackVisitor::visitEraseStack(EraseStack & pack)
  187. {
  188. dispatchGarrisonChange(cl, pack.army, ObjectInstanceID());
  189. }
  190. void ApplyClientNetPackVisitor::visitSwapStacks(SwapStacks & pack)
  191. {
  192. dispatchGarrisonChange(cl, pack.srcArmy, pack.dstArmy);
  193. }
  194. void ApplyClientNetPackVisitor::visitInsertNewStack(InsertNewStack & pack)
  195. {
  196. dispatchGarrisonChange(cl, pack.army, ObjectInstanceID());
  197. }
  198. void ApplyClientNetPackVisitor::visitRebalanceStacks(RebalanceStacks & pack)
  199. {
  200. dispatchGarrisonChange(cl, pack.srcArmy, pack.dstArmy);
  201. }
  202. void ApplyClientNetPackVisitor::visitBulkRebalanceStacks(BulkRebalanceStacks & pack)
  203. {
  204. if(!pack.moves.empty())
  205. {
  206. auto destArmy = pack.moves[0].srcArmy == pack.moves[0].dstArmy
  207. ? ObjectInstanceID()
  208. : pack.moves[0].dstArmy;
  209. dispatchGarrisonChange(cl, pack.moves[0].srcArmy, destArmy);
  210. }
  211. }
  212. void ApplyClientNetPackVisitor::visitBulkSmartRebalanceStacks(BulkSmartRebalanceStacks & pack)
  213. {
  214. if(!pack.moves.empty())
  215. {
  216. assert(pack.moves[0].srcArmy == pack.moves[0].dstArmy);
  217. dispatchGarrisonChange(cl, pack.moves[0].srcArmy, ObjectInstanceID());
  218. }
  219. else if(!pack.changes.empty())
  220. {
  221. dispatchGarrisonChange(cl, pack.changes[0].army, ObjectInstanceID());
  222. }
  223. }
  224. void ApplyClientNetPackVisitor::visitPutArtifact(PutArtifact & pack)
  225. {
  226. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactPut, pack.al);
  227. }
  228. void ApplyClientNetPackVisitor::visitEraseArtifact(EraseArtifact & pack)
  229. {
  230. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactRemoved, pack.al);
  231. }
  232. void ApplyClientNetPackVisitor::visitMoveArtifact(MoveArtifact & pack)
  233. {
  234. auto moveArtifact = [this, &pack](PlayerColor player) -> void
  235. {
  236. callInterfaceIfPresent(cl, player, &IGameEventsReceiver::artifactMoved, pack.src, pack.dst);
  237. if(pack.askAssemble)
  238. callInterfaceIfPresent(cl, player, &IGameEventsReceiver::artifactPossibleAssembling, pack.dst);
  239. };
  240. moveArtifact(pack.src.owningPlayer());
  241. if(pack.src.owningPlayer() != pack.dst.owningPlayer())
  242. moveArtifact(pack.dst.owningPlayer());
  243. }
  244. void ApplyClientNetPackVisitor::visitBulkMoveArtifacts(BulkMoveArtifacts & pack)
  245. {
  246. auto applyMove = [this, &pack](std::vector<BulkMoveArtifacts::LinkedSlots> & artsPack) -> void
  247. {
  248. for(auto & slotToMove : artsPack)
  249. {
  250. auto srcLoc = ArtifactLocation(pack.srcArtHolder, slotToMove.srcPos);
  251. auto dstLoc = ArtifactLocation(pack.dstArtHolder, slotToMove.dstPos);
  252. callInterfaceIfPresent(cl, srcLoc.owningPlayer(), &IGameEventsReceiver::artifactMoved, srcLoc, dstLoc);
  253. if(srcLoc.owningPlayer() != dstLoc.owningPlayer())
  254. callInterfaceIfPresent(cl, dstLoc.owningPlayer(), &IGameEventsReceiver::artifactMoved, srcLoc, dstLoc);
  255. }
  256. };
  257. applyMove(pack.artsPack0);
  258. if(pack.swap)
  259. applyMove(pack.artsPack1);
  260. }
  261. void ApplyClientNetPackVisitor::visitAssembledArtifact(AssembledArtifact & pack)
  262. {
  263. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactAssembled, pack.al);
  264. }
  265. void ApplyClientNetPackVisitor::visitDisassembledArtifact(DisassembledArtifact & pack)
  266. {
  267. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactDisassembled, pack.al);
  268. }
  269. void ApplyClientNetPackVisitor::visitHeroVisit(HeroVisit & pack)
  270. {
  271. auto hero = cl.getHero(pack.heroId);
  272. auto obj = cl.getObj(pack.objId, false);
  273. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::heroVisit, hero, obj, pack.starting);
  274. }
  275. void ApplyClientNetPackVisitor::visitNewTurn(NewTurn & pack)
  276. {
  277. cl.invalidatePaths();
  278. }
  279. void ApplyClientNetPackVisitor::visitGiveBonus(GiveBonus & pack)
  280. {
  281. cl.invalidatePaths();
  282. switch(pack.who)
  283. {
  284. case GiveBonus::HERO:
  285. {
  286. const CGHeroInstance *h = gs.getHero(ObjectInstanceID(pack.id));
  287. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroBonusChanged, h, *h->getBonusList().back(), true);
  288. }
  289. break;
  290. case GiveBonus::PLAYER:
  291. {
  292. const PlayerState *p = gs.getPlayerState(PlayerColor(pack.id));
  293. callInterfaceIfPresent(cl, PlayerColor(pack.id), &IGameEventsReceiver::playerBonusChanged, *p->getBonusList().back(), true);
  294. }
  295. break;
  296. }
  297. }
  298. void ApplyFirstClientNetPackVisitor::visitChangeObjPos(ChangeObjPos & pack)
  299. {
  300. CGObjectInstance *obj = gs.getObjInstance(pack.objid);
  301. if(pack.flags & 1 && CGI->mh)
  302. CGI->mh->hideObject(obj);
  303. }
  304. void ApplyClientNetPackVisitor::visitChangeObjPos(ChangeObjPos & pack)
  305. {
  306. CGObjectInstance *obj = gs.getObjInstance(pack.objid);
  307. if(pack.flags & 1 && CGI->mh)
  308. CGI->mh->printObject(obj);
  309. cl.invalidatePaths();
  310. }
  311. void ApplyClientNetPackVisitor::visitPlayerEndsGame(PlayerEndsGame & pack)
  312. {
  313. callAllInterfaces(cl, &IGameEventsReceiver::gameOver, pack.player, pack.victoryLossCheckResult);
  314. // In auto testing pack.mode we always close client if red pack.player won or lose
  315. if(!settings["session"]["testmap"].isNull() && pack.player == PlayerColor(0))
  316. handleQuit(settings["session"]["spectate"].Bool()); // if spectator is active ask to close client or not
  317. }
  318. void ApplyClientNetPackVisitor::visitPlayerReinitInterface(PlayerReinitInterface & pack)
  319. {
  320. auto initInterfaces = [this]()
  321. {
  322. cl.initPlayerInterfaces();
  323. auto currentPlayer = cl.gameState()->currentPlayer;
  324. callAllInterfaces(cl, &IGameEventsReceiver::playerStartsTurn, currentPlayer);
  325. callOnlyThatInterface(cl, currentPlayer, &CGameInterface::yourTurn);
  326. };
  327. for(auto player : pack.players)
  328. {
  329. auto & plSettings = CSH->si->getIthPlayersSettings(player);
  330. if(pack.playerConnectionId == PlayerSettings::PLAYER_AI)
  331. {
  332. plSettings.connectedPlayerIDs.clear();
  333. cl.initPlayerEnvironments();
  334. initInterfaces();
  335. }
  336. else if(pack.playerConnectionId == CSH->c->connectionID)
  337. {
  338. plSettings.connectedPlayerIDs.insert(pack.playerConnectionId);
  339. cl.playerint.clear();
  340. initInterfaces();
  341. }
  342. }
  343. }
  344. void ApplyClientNetPackVisitor::visitRemoveBonus(RemoveBonus & pack)
  345. {
  346. cl.invalidatePaths();
  347. switch(pack.who)
  348. {
  349. case RemoveBonus::HERO:
  350. {
  351. const CGHeroInstance *h = gs.getHero(ObjectInstanceID(pack.id));
  352. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroBonusChanged, h, pack.bonus, false);
  353. }
  354. break;
  355. case RemoveBonus::PLAYER:
  356. {
  357. //const PlayerState *p = gs.getPlayerState(pack.id);
  358. callInterfaceIfPresent(cl, PlayerColor(pack.id), &IGameEventsReceiver::playerBonusChanged, pack.bonus, false);
  359. }
  360. break;
  361. }
  362. }
  363. void ApplyFirstClientNetPackVisitor::visitRemoveObject(RemoveObject & pack)
  364. {
  365. const CGObjectInstance *o = cl.getObj(pack.id);
  366. if(CGI->mh)
  367. CGI->mh->hideObject(o, true);
  368. //notify interfaces about removal
  369. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  370. {
  371. //below line contains little cheat for AI so it will be aware of deletion of enemy heroes that moved or got re-covered by FoW
  372. //TODO: loose requirements as next AI related crashes appear, for example another pack.player collects object that got re-covered by FoW, unsure if AI code workarounds this
  373. if(gs.isVisible(o, i->first) || (!cl.getPlayerState(i->first)->human && o->ID == Obj::HERO && o->tempOwner != i->first))
  374. i->second->objectRemoved(o);
  375. }
  376. }
  377. void ApplyClientNetPackVisitor::visitRemoveObject(RemoveObject & pack)
  378. {
  379. cl.invalidatePaths();
  380. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  381. i->second->objectRemovedAfter();
  382. }
  383. void ApplyFirstClientNetPackVisitor::visitTryMoveHero(TryMoveHero & pack)
  384. {
  385. CGHeroInstance *h = gs.getHero(pack.id);
  386. //check if playerint will have the knowledge about movement - if not, directly update maphandler
  387. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  388. {
  389. auto ps = gs.getPlayerState(i->first);
  390. if(ps && (gs.isVisible(pack.start - int3(1, 0, 0), i->first) || gs.isVisible(pack.end - int3(1, 0, 0), i->first)))
  391. {
  392. if(ps->human)
  393. pack.humanKnows = true;
  394. }
  395. }
  396. if(!CGI->mh)
  397. return;
  398. if(pack.result == TryMoveHero::TELEPORTATION || pack.result == TryMoveHero::EMBARK || pack.result == TryMoveHero::DISEMBARK || !pack.humanKnows)
  399. CGI->mh->hideObject(h, pack.result == TryMoveHero::EMBARK && pack.humanKnows);
  400. if(pack.result == TryMoveHero::DISEMBARK)
  401. CGI->mh->printObject(h->boat);
  402. }
  403. void ApplyClientNetPackVisitor::visitTryMoveHero(TryMoveHero & pack)
  404. {
  405. const CGHeroInstance *h = cl.getHero(pack.id);
  406. cl.invalidatePaths();
  407. if(CGI->mh)
  408. {
  409. if(pack.result == TryMoveHero::TELEPORTATION || pack.result == TryMoveHero::EMBARK || pack.result == TryMoveHero::DISEMBARK)
  410. CGI->mh->printObject(h, pack.result == TryMoveHero::DISEMBARK);
  411. if(pack.result == TryMoveHero::EMBARK)
  412. CGI->mh->hideObject(h->boat);
  413. }
  414. PlayerColor player = h->tempOwner;
  415. for(auto &i : cl.playerint)
  416. if(cl.getPlayerRelations(i.first, player) != PlayerRelations::ENEMIES)
  417. i.second->tileRevealed(pack.fowRevealed);
  418. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  419. {
  420. if(i->first != PlayerColor::SPECTATOR && gs.checkForStandardLoss(i->first)) // Do not notify vanquished pack.player's interface
  421. continue;
  422. if(gs.isVisible(pack.start - int3(1, 0, 0), i->first)
  423. || gs.isVisible(pack.end - int3(1, 0, 0), i->first))
  424. {
  425. // pack.src and pack.dst of enemy hero move may be not visible => 'verbose' should be false
  426. const bool verbose = cl.getPlayerRelations(i->first, player) != PlayerRelations::ENEMIES;
  427. i->second->heroMoved(pack, verbose);
  428. }
  429. }
  430. //maphandler didn't get update from playerint, do it now
  431. //TODO: restructure nicely
  432. if(!pack.humanKnows && CGI->mh)
  433. CGI->mh->printObject(h);
  434. }
  435. void ApplyClientNetPackVisitor::visitNewStructures(NewStructures & pack)
  436. {
  437. CGTownInstance *town = gs.getTown(pack.tid);
  438. for(const auto & id : pack.bid)
  439. {
  440. callInterfaceIfPresent(cl, town->tempOwner, &IGameEventsReceiver::buildChanged, town, id, 1);
  441. }
  442. }
  443. void ApplyClientNetPackVisitor::visitRazeStructures(RazeStructures & pack)
  444. {
  445. CGTownInstance * town = gs.getTown(pack.tid);
  446. for(const auto & id : pack.bid)
  447. {
  448. callInterfaceIfPresent(cl, town->tempOwner, &IGameEventsReceiver::buildChanged, town, id, 2);
  449. }
  450. }
  451. void ApplyClientNetPackVisitor::visitSetAvailableCreatures(SetAvailableCreatures & pack)
  452. {
  453. const CGDwelling * dw = static_cast<const CGDwelling*>(cl.getObj(pack.tid));
  454. PlayerColor p;
  455. if(dw->ID == Obj::WAR_MACHINE_FACTORY) //War Machines Factory is not flaggable, it's "owned" by visitor
  456. p = cl.getTile(dw->visitablePos())->visitableObjects.back()->tempOwner;
  457. else
  458. p = dw->tempOwner;
  459. callInterfaceIfPresent(cl, p, &IGameEventsReceiver::availableCreaturesChanged, dw);
  460. }
  461. void ApplyClientNetPackVisitor::visitSetHeroesInTown(SetHeroesInTown & pack)
  462. {
  463. CGTownInstance * t = gs.getTown(pack.tid);
  464. CGHeroInstance * hGarr = gs.getHero(pack.garrison);
  465. CGHeroInstance * hVisit = gs.getHero(pack.visiting);
  466. //inform all players that see this object
  467. for(auto i = cl.playerint.cbegin(); i != cl.playerint.cend(); ++i)
  468. {
  469. if(i->first >= PlayerColor::PLAYER_LIMIT)
  470. continue;
  471. if(gs.isVisible(t, i->first) ||
  472. (hGarr && gs.isVisible(hGarr, i->first)) ||
  473. (hVisit && gs.isVisible(hVisit, i->first)))
  474. {
  475. cl.playerint[i->first]->heroInGarrisonChange(t);
  476. }
  477. }
  478. }
  479. void ApplyClientNetPackVisitor::visitHeroRecruited(HeroRecruited & pack)
  480. {
  481. CGHeroInstance *h = gs.map->heroesOnMap.back();
  482. if(h->subID != pack.hid)
  483. {
  484. logNetwork->error("Something wrong with hero recruited!");
  485. }
  486. bool needsPrinting = true;
  487. if(callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroCreated, h))
  488. {
  489. if(const CGTownInstance *t = gs.getTown(pack.tid))
  490. {
  491. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroInGarrisonChange, t);
  492. needsPrinting = false;
  493. }
  494. }
  495. if(needsPrinting && CGI->mh)
  496. CGI->mh->printObject(h);
  497. }
  498. void ApplyClientNetPackVisitor::visitGiveHero(GiveHero & pack)
  499. {
  500. CGHeroInstance *h = gs.getHero(pack.id);
  501. if(CGI->mh)
  502. CGI->mh->printObject(h);
  503. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroCreated, h);
  504. }
  505. void ApplyFirstClientNetPackVisitor::visitGiveHero(GiveHero & pack)
  506. {
  507. if(CGI->mh)
  508. CGI->mh->hideObject(gs.getHero(pack.id));
  509. }
  510. void ApplyClientNetPackVisitor::visitInfoWindow(InfoWindow & pack)
  511. {
  512. std::string str;
  513. pack.text.toString(str);
  514. if(!callInterfaceIfPresent(cl, pack.player, &CGameInterface::showInfoDialog, str, pack.components,(soundBase::soundID)pack.soundID))
  515. logNetwork->warn("We received InfoWindow for not our player...");
  516. }
  517. void ApplyClientNetPackVisitor::visitSetObjectProperty(SetObjectProperty & pack)
  518. {
  519. //inform all players that see this object
  520. for(auto it = cl.playerint.cbegin(); it != cl.playerint.cend(); ++it)
  521. {
  522. if(gs.isVisible(gs.getObjInstance(pack.id), it->first))
  523. callInterfaceIfPresent(cl, it->first, &IGameEventsReceiver::objectPropertyChanged, &pack);
  524. }
  525. }
  526. void ApplyClientNetPackVisitor::visitHeroLevelUp(HeroLevelUp & pack)
  527. {
  528. const CGHeroInstance * hero = cl.getHero(pack.heroId);
  529. assert(hero);
  530. callOnlyThatInterface(cl, pack.player, &CGameInterface::heroGotLevel, hero, pack.primskill, pack.skills, pack.queryID);
  531. }
  532. void ApplyClientNetPackVisitor::visitCommanderLevelUp(CommanderLevelUp & pack)
  533. {
  534. const CGHeroInstance * hero = cl.getHero(pack.heroId);
  535. assert(hero);
  536. const CCommanderInstance * commander = hero->commander;
  537. assert(commander);
  538. assert(commander->armyObj); //is it possible for Commander to exist beyond armed instance?
  539. callOnlyThatInterface(cl, pack.player, &CGameInterface::commanderGotLevel, commander, pack.skills, pack.queryID);
  540. }
  541. void ApplyClientNetPackVisitor::visitBlockingDialog(BlockingDialog & pack)
  542. {
  543. std::string str;
  544. pack.text.toString(str);
  545. if(!callOnlyThatInterface(cl, pack.player, &CGameInterface::showBlockingDialog, str, pack.components, pack.queryID, (soundBase::soundID)pack.soundID, pack.selection(), pack.cancel()))
  546. logNetwork->warn("We received YesNoDialog for not our player...");
  547. }
  548. void ApplyClientNetPackVisitor::visitGarrisonDialog(GarrisonDialog & pack)
  549. {
  550. const CGHeroInstance *h = cl.getHero(pack.hid);
  551. const CArmedInstance *obj = static_cast<const CArmedInstance*>(cl.getObj(pack.objid));
  552. callOnlyThatInterface(cl, h->getOwner(), &CGameInterface::showGarrisonDialog, obj, h, pack.removableUnits, pack.queryID);
  553. }
  554. void ApplyClientNetPackVisitor::visitExchangeDialog(ExchangeDialog & pack)
  555. {
  556. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::heroExchangeStarted, pack.hero1, pack.hero2, pack.queryID);
  557. }
  558. void ApplyClientNetPackVisitor::visitTeleportDialog(TeleportDialog & pack)
  559. {
  560. callOnlyThatInterface(cl, pack.player, &CGameInterface::showTeleportDialog, pack.channel, pack.exits, pack.impassable, pack.queryID);
  561. }
  562. void ApplyClientNetPackVisitor::visitMapObjectSelectDialog(MapObjectSelectDialog & pack)
  563. {
  564. callOnlyThatInterface(cl, pack.player, &CGameInterface::showMapObjectSelectDialog, pack.queryID, pack.icon, pack.title, pack.description, pack.objects);
  565. }
  566. void ApplyFirstClientNetPackVisitor::visitBattleStart(BattleStart & pack)
  567. {
  568. // Cannot use the usual code because curB is not set yet
  569. callOnlyThatBattleInterface(cl, pack.info->sides[0].color, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  570. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  571. callOnlyThatBattleInterface(cl, pack.info->sides[1].color, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  572. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  573. callOnlyThatBattleInterface(cl, PlayerColor::SPECTATOR, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  574. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  575. }
  576. void ApplyClientNetPackVisitor::visitBattleStart(BattleStart & pack)
  577. {
  578. cl.battleStarted(pack.info);
  579. }
  580. void ApplyFirstClientNetPackVisitor::visitBattleNextRound(BattleNextRound & pack)
  581. {
  582. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleNewRoundFirst, pack.round);
  583. }
  584. void ApplyClientNetPackVisitor::visitBattleNextRound(BattleNextRound & pack)
  585. {
  586. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleNewRound, pack.round);
  587. }
  588. void ApplyClientNetPackVisitor::visitBattleSetActiveStack(BattleSetActiveStack & pack)
  589. {
  590. if(!pack.askPlayerInterface)
  591. return;
  592. const CStack *activated = gs.curB->battleGetStackByID(pack.stack);
  593. PlayerColor playerToCall; //pack.player that will move activated stack
  594. if (activated->hasBonusOfType(Bonus::HYPNOTIZED))
  595. {
  596. playerToCall = (gs.curB->sides[0].color == activated->owner
  597. ? gs.curB->sides[1].color
  598. : gs.curB->sides[0].color);
  599. }
  600. else
  601. {
  602. playerToCall = activated->owner;
  603. }
  604. cl.startPlayerBattleAction(playerToCall);
  605. }
  606. void ApplyClientNetPackVisitor::visitBattleLogMessage(BattleLogMessage & pack)
  607. {
  608. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleLogMessage, pack.lines);
  609. }
  610. void ApplyClientNetPackVisitor::visitBattleTriggerEffect(BattleTriggerEffect & pack)
  611. {
  612. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleTriggerEffect, pack);
  613. }
  614. void ApplyFirstClientNetPackVisitor::visitBattleUpdateGateState(BattleUpdateGateState & pack)
  615. {
  616. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleGateStateChanged, pack.state);
  617. }
  618. void ApplyFirstClientNetPackVisitor::visitBattleResult(BattleResult & pack)
  619. {
  620. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleEnd, &pack);
  621. cl.battleFinished();
  622. }
  623. void ApplyFirstClientNetPackVisitor::visitBattleStackMoved(BattleStackMoved & pack)
  624. {
  625. const CStack * movedStack = gs.curB->battleGetStackByID(pack.stack);
  626. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStackMoved, movedStack, pack.tilesToMove, pack.distance, pack.teleporting);
  627. }
  628. void ApplyFirstClientNetPackVisitor::visitBattleAttack(BattleAttack & pack)
  629. {
  630. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleAttack, &pack);
  631. }
  632. void ApplyClientNetPackVisitor::visitBattleAttack(BattleAttack & pack)
  633. {
  634. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksAttacked, pack.bsa, pack.shot());
  635. }
  636. void ApplyFirstClientNetPackVisitor::visitStartAction(StartAction & pack)
  637. {
  638. cl.curbaction = boost::make_optional(pack.ba);
  639. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionStarted, pack.ba);
  640. }
  641. void ApplyClientNetPackVisitor::visitBattleSpellCast(BattleSpellCast & pack)
  642. {
  643. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleSpellCast, &pack);
  644. }
  645. void ApplyClientNetPackVisitor::visitSetStackEffect(SetStackEffect & pack)
  646. {
  647. //informing about effects
  648. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksEffectsSet, pack);
  649. }
  650. void ApplyClientNetPackVisitor::visitStacksInjured(StacksInjured & pack)
  651. {
  652. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksAttacked, pack.stacks, false);
  653. }
  654. void ApplyClientNetPackVisitor::visitBattleResultsApplied(BattleResultsApplied & pack)
  655. {
  656. callInterfaceIfPresent(cl, pack.player1, &IGameEventsReceiver::battleResultsApplied);
  657. callInterfaceIfPresent(cl, pack.player2, &IGameEventsReceiver::battleResultsApplied);
  658. callInterfaceIfPresent(cl, PlayerColor::SPECTATOR, &IGameEventsReceiver::battleResultsApplied);
  659. }
  660. void ApplyClientNetPackVisitor::visitBattleUnitsChanged(BattleUnitsChanged & pack)
  661. {
  662. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleUnitsChanged, pack.changedStacks);
  663. }
  664. void ApplyClientNetPackVisitor::visitBattleObstaclesChanged(BattleObstaclesChanged & pack)
  665. {
  666. //inform interfaces about removed obstacles
  667. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleObstaclesChanged, pack.changes);
  668. }
  669. void ApplyClientNetPackVisitor::visitCatapultAttack(CatapultAttack & pack)
  670. {
  671. //inform interfaces about catapult attack
  672. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleCatapultAttacked, pack);
  673. }
  674. void ApplyClientNetPackVisitor::visitEndAction(EndAction & pack)
  675. {
  676. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionFinished, *cl.curbaction);
  677. cl.curbaction.reset();
  678. }
  679. void ApplyClientNetPackVisitor::visitPackageApplied(PackageApplied & pack)
  680. {
  681. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::requestRealized, &pack);
  682. if(!CClient::waitingRequest.tryRemovingElement(pack.requestID))
  683. logNetwork->warn("Surprising server message! PackageApplied for unknown requestID!");
  684. }
  685. void ApplyClientNetPackVisitor::visitSystemMessage(SystemMessage & pack)
  686. {
  687. std::ostringstream str;
  688. str << "System message: " << pack.text;
  689. logNetwork->error(str.str()); // usually used to receive error messages from server
  690. if(LOCPLINT && !settings["session"]["hideSystemMessages"].Bool())
  691. LOCPLINT->cingconsole->print(str.str());
  692. }
  693. void ApplyClientNetPackVisitor::visitPlayerBlocked(PlayerBlocked & pack)
  694. {
  695. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::playerBlocked, pack.reason, pack.startOrEnd == PlayerBlocked::BLOCKADE_STARTED);
  696. }
  697. void ApplyClientNetPackVisitor::visitYourTurn(YourTurn & pack)
  698. {
  699. logNetwork->debug("Server gives turn to %s", pack.player.getStr());
  700. callAllInterfaces(cl, &IGameEventsReceiver::playerStartsTurn, pack.player);
  701. callOnlyThatInterface(cl, pack.player, &CGameInterface::yourTurn);
  702. }
  703. void ApplyClientNetPackVisitor::visitSaveGameClient(SaveGameClient & pack)
  704. {
  705. const auto stem = FileInfo::GetPathStem(pack.fname);
  706. if(!CResourceHandler::get("local")->createResource(stem.to_string() + ".vcgm1"))
  707. {
  708. logNetwork->error("Failed to create resource %s", stem.to_string() + ".vcgm1");
  709. return;
  710. }
  711. try
  712. {
  713. CSaveFile save(*CResourceHandler::get()->getResourceName(ResourceID(stem.to_string(), EResType::CLIENT_SAVEGAME)));
  714. cl.saveCommonState(save);
  715. save << cl;
  716. }
  717. catch(std::exception &e)
  718. {
  719. logNetwork->error("Failed to save game:%s", e.what());
  720. }
  721. }
  722. void ApplyClientNetPackVisitor::visitPlayerMessageClient(PlayerMessageClient & pack)
  723. {
  724. logNetwork->debug("pack.player %s sends a message: %s", pack.player.getStr(), pack.text);
  725. std::ostringstream str;
  726. if(pack.player.isSpectator())
  727. str << "Spectator: " << pack.text;
  728. else
  729. str << cl.getPlayerState(pack.player)->nodeName() <<": " << pack.text;
  730. if(LOCPLINT)
  731. LOCPLINT->cingconsole->print(str.str());
  732. }
  733. void ApplyClientNetPackVisitor::visitShowInInfobox(ShowInInfobox & pack)
  734. {
  735. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::showComp, pack.c, pack.text.toString());
  736. }
  737. void ApplyClientNetPackVisitor::visitAdvmapSpellCast(AdvmapSpellCast & pack)
  738. {
  739. cl.invalidatePaths();
  740. auto caster = cl.getHero(pack.casterID);
  741. if(caster)
  742. //consider notifying other interfaces that see hero?
  743. callInterfaceIfPresent(cl, caster->getOwner(), &IGameEventsReceiver::advmapSpellCast, caster, pack.spellID);
  744. else
  745. logNetwork->error("Invalid hero instance");
  746. }
  747. void ApplyClientNetPackVisitor::visitShowWorldViewEx(ShowWorldViewEx & pack)
  748. {
  749. callOnlyThatInterface(cl, pack.player, &CGameInterface::showWorldViewEx, pack.objectPositions);
  750. }
  751. void ApplyClientNetPackVisitor::visitOpenWindow(OpenWindow & pack)
  752. {
  753. switch(pack.window)
  754. {
  755. case OpenWindow::RECRUITMENT_FIRST:
  756. case OpenWindow::RECRUITMENT_ALL:
  757. {
  758. const CGDwelling *dw = dynamic_cast<const CGDwelling*>(cl.getObj(ObjectInstanceID(pack.id1)));
  759. const CArmedInstance *dst = dynamic_cast<const CArmedInstance*>(cl.getObj(ObjectInstanceID(pack.id2)));
  760. callInterfaceIfPresent(cl, dst->tempOwner, &IGameEventsReceiver::showRecruitmentDialog, dw, dst, pack.window == OpenWindow::RECRUITMENT_FIRST ? 0 : -1);
  761. }
  762. break;
  763. case OpenWindow::SHIPYARD_WINDOW:
  764. {
  765. const IShipyard *sy = IShipyard::castFrom(cl.getObj(ObjectInstanceID(pack.id1)));
  766. callInterfaceIfPresent(cl, sy->o->tempOwner, &IGameEventsReceiver::showShipyardDialog, sy);
  767. }
  768. break;
  769. case OpenWindow::THIEVES_GUILD:
  770. {
  771. //displays Thieves' Guild window (when hero enters Den of Thieves)
  772. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id2));
  773. callInterfaceIfPresent(cl, PlayerColor(pack.id1), &IGameEventsReceiver::showThievesGuildWindow, obj);
  774. }
  775. break;
  776. case OpenWindow::UNIVERSITY_WINDOW:
  777. {
  778. //displays University window (when hero enters University on adventure map)
  779. const IMarket *market = IMarket::castFrom(cl.getObj(ObjectInstanceID(pack.id1)));
  780. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  781. callInterfaceIfPresent(cl, hero->tempOwner, &IGameEventsReceiver::showUniversityWindow, market, hero);
  782. }
  783. break;
  784. case OpenWindow::MARKET_WINDOW:
  785. {
  786. //displays Thieves' Guild window (when hero enters Den of Thieves)
  787. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id1));
  788. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  789. const IMarket *market = IMarket::castFrom(obj);
  790. callInterfaceIfPresent(cl, cl.getTile(obj->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::showMarketWindow, market, hero);
  791. }
  792. break;
  793. case OpenWindow::HILL_FORT_WINDOW:
  794. {
  795. //displays Hill fort window
  796. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id1));
  797. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  798. callInterfaceIfPresent(cl, cl.getTile(obj->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::showHillFortWindow, obj, hero);
  799. }
  800. break;
  801. case OpenWindow::PUZZLE_MAP:
  802. {
  803. callInterfaceIfPresent(cl, PlayerColor(pack.id1), &IGameEventsReceiver::showPuzzleMap);
  804. }
  805. break;
  806. case OpenWindow::TAVERN_WINDOW:
  807. const CGObjectInstance *obj1 = cl.getObj(ObjectInstanceID(pack.id1)),
  808. *obj2 = cl.getObj(ObjectInstanceID(pack.id2));
  809. callInterfaceIfPresent(cl, obj1->tempOwner, &IGameEventsReceiver::showTavernWindow, obj2);
  810. break;
  811. }
  812. }
  813. void ApplyClientNetPackVisitor::visitCenterView(CenterView & pack)
  814. {
  815. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::centerView, pack.pos, pack.focusTime);
  816. }
  817. void ApplyClientNetPackVisitor::visitNewObject(NewObject & pack)
  818. {
  819. cl.invalidatePaths();
  820. const CGObjectInstance *obj = cl.getObj(pack.id);
  821. if(CGI->mh)
  822. CGI->mh->printObject(obj, true);
  823. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  824. {
  825. if(gs.isVisible(obj, i->first))
  826. i->second->newObject(obj);
  827. }
  828. }
  829. void ApplyClientNetPackVisitor::visitSetAvailableArtifacts(SetAvailableArtifacts & pack)
  830. {
  831. if(pack.id < 0) //artifact merchants globally
  832. {
  833. callAllInterfaces(cl, &IGameEventsReceiver::availableArtifactsChanged, nullptr);
  834. }
  835. else
  836. {
  837. const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(cl.getObj(ObjectInstanceID(pack.id)));
  838. assert(bm);
  839. callInterfaceIfPresent(cl, cl.getTile(bm->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::availableArtifactsChanged, bm);
  840. }
  841. }
  842. void ApplyClientNetPackVisitor::visitEntitiesChanged(EntitiesChanged & pack)
  843. {
  844. cl.invalidatePaths();
  845. }