NetPacksClient.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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 "mapView/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. if(pack.askAssemble)
  228. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::askToAssembleArtifact, pack.al);
  229. }
  230. void ApplyClientNetPackVisitor::visitEraseArtifact(EraseArtifact & pack)
  231. {
  232. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactRemoved, pack.al);
  233. }
  234. void ApplyClientNetPackVisitor::visitMoveArtifact(MoveArtifact & pack)
  235. {
  236. auto moveArtifact = [this, &pack](PlayerColor player) -> void
  237. {
  238. callInterfaceIfPresent(cl, player, &IGameEventsReceiver::artifactMoved, pack.src, pack.dst);
  239. if(pack.askAssemble)
  240. callInterfaceIfPresent(cl, player, &IGameEventsReceiver::askToAssembleArtifact, pack.dst);
  241. };
  242. moveArtifact(pack.src.owningPlayer());
  243. if(pack.src.owningPlayer() != pack.dst.owningPlayer())
  244. moveArtifact(pack.dst.owningPlayer());
  245. }
  246. void ApplyClientNetPackVisitor::visitBulkMoveArtifacts(BulkMoveArtifacts & pack)
  247. {
  248. auto applyMove = [this, &pack](std::vector<BulkMoveArtifacts::LinkedSlots> & artsPack) -> void
  249. {
  250. for(auto & slotToMove : artsPack)
  251. {
  252. auto srcLoc = ArtifactLocation(pack.srcArtHolder, slotToMove.srcPos);
  253. auto dstLoc = ArtifactLocation(pack.dstArtHolder, slotToMove.dstPos);
  254. MoveArtifact ma(&srcLoc, &dstLoc, false);
  255. visitMoveArtifact(ma);
  256. }
  257. };
  258. // Begin a session of bulk movement of arts. It is not necessary but useful for the client optimization.
  259. callInterfaceIfPresent(cl, cl.getCurrentPlayer(), &IGameEventsReceiver::bulkArtMovementStart,
  260. pack.artsPack0.size() + pack.artsPack1.size());
  261. applyMove(pack.artsPack0);
  262. if(pack.swap)
  263. applyMove(pack.artsPack1);
  264. }
  265. void ApplyClientNetPackVisitor::visitAssembledArtifact(AssembledArtifact & pack)
  266. {
  267. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactAssembled, pack.al);
  268. }
  269. void ApplyClientNetPackVisitor::visitDisassembledArtifact(DisassembledArtifact & pack)
  270. {
  271. callInterfaceIfPresent(cl, pack.al.owningPlayer(), &IGameEventsReceiver::artifactDisassembled, pack.al);
  272. }
  273. void ApplyClientNetPackVisitor::visitHeroVisit(HeroVisit & pack)
  274. {
  275. auto hero = cl.getHero(pack.heroId);
  276. auto obj = cl.getObj(pack.objId, false);
  277. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::heroVisit, hero, obj, pack.starting);
  278. }
  279. void ApplyClientNetPackVisitor::visitNewTurn(NewTurn & pack)
  280. {
  281. cl.invalidatePaths();
  282. }
  283. void ApplyClientNetPackVisitor::visitGiveBonus(GiveBonus & pack)
  284. {
  285. cl.invalidatePaths();
  286. switch(pack.who)
  287. {
  288. case GiveBonus::ETarget::HERO:
  289. {
  290. const CGHeroInstance *h = gs.getHero(ObjectInstanceID(pack.id));
  291. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroBonusChanged, h, pack.bonus, true);
  292. }
  293. break;
  294. case GiveBonus::ETarget::PLAYER:
  295. {
  296. callInterfaceIfPresent(cl, PlayerColor(pack.id), &IGameEventsReceiver::playerBonusChanged, pack.bonus, true);
  297. }
  298. break;
  299. }
  300. }
  301. void ApplyFirstClientNetPackVisitor::visitChangeObjPos(ChangeObjPos & pack)
  302. {
  303. CGObjectInstance *obj = gs.getObjInstance(pack.objid);
  304. if(CGI->mh)
  305. CGI->mh->onObjectFadeOut(obj);
  306. CGI->mh->waitForOngoingAnimations();
  307. }
  308. void ApplyClientNetPackVisitor::visitChangeObjPos(ChangeObjPos & pack)
  309. {
  310. CGObjectInstance *obj = gs.getObjInstance(pack.objid);
  311. if(CGI->mh)
  312. CGI->mh->onObjectFadeIn(obj);
  313. CGI->mh->waitForOngoingAnimations();
  314. cl.invalidatePaths();
  315. }
  316. void ApplyClientNetPackVisitor::visitPlayerEndsGame(PlayerEndsGame & pack)
  317. {
  318. callAllInterfaces(cl, &IGameEventsReceiver::gameOver, pack.player, pack.victoryLossCheckResult);
  319. // In auto testing pack.mode we always close client if red pack.player won or lose
  320. if(!settings["session"]["testmap"].isNull() && pack.player == PlayerColor(0))
  321. handleQuit(settings["session"]["spectate"].Bool()); // if spectator is active ask to close client or not
  322. }
  323. void ApplyClientNetPackVisitor::visitPlayerReinitInterface(PlayerReinitInterface & pack)
  324. {
  325. auto initInterfaces = [this]()
  326. {
  327. cl.initPlayerInterfaces();
  328. auto currentPlayer = cl.gameState()->currentPlayer;
  329. callAllInterfaces(cl, &IGameEventsReceiver::playerStartsTurn, currentPlayer);
  330. callOnlyThatInterface(cl, currentPlayer, &CGameInterface::yourTurn);
  331. };
  332. for(auto player : pack.players)
  333. {
  334. auto & plSettings = CSH->si->getIthPlayersSettings(player);
  335. if(pack.playerConnectionId == PlayerSettings::PLAYER_AI)
  336. {
  337. plSettings.connectedPlayerIDs.clear();
  338. cl.initPlayerEnvironments();
  339. initInterfaces();
  340. }
  341. else if(pack.playerConnectionId == CSH->c->connectionID)
  342. {
  343. plSettings.connectedPlayerIDs.insert(pack.playerConnectionId);
  344. cl.playerint.clear();
  345. initInterfaces();
  346. }
  347. }
  348. }
  349. void ApplyClientNetPackVisitor::visitRemoveBonus(RemoveBonus & pack)
  350. {
  351. cl.invalidatePaths();
  352. switch(pack.who)
  353. {
  354. case GiveBonus::ETarget::HERO:
  355. {
  356. const CGHeroInstance *h = gs.getHero(ObjectInstanceID(pack.id));
  357. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroBonusChanged, h, pack.bonus, false);
  358. }
  359. break;
  360. case GiveBonus::ETarget::PLAYER:
  361. {
  362. //const PlayerState *p = gs.getPlayerState(pack.id);
  363. callInterfaceIfPresent(cl, PlayerColor(pack.id), &IGameEventsReceiver::playerBonusChanged, pack.bonus, false);
  364. }
  365. break;
  366. }
  367. }
  368. void ApplyFirstClientNetPackVisitor::visitRemoveObject(RemoveObject & pack)
  369. {
  370. const CGObjectInstance *o = cl.getObj(pack.id);
  371. if(CGI->mh)
  372. CGI->mh->onObjectFadeOut(o);
  373. //notify interfaces about removal
  374. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  375. {
  376. //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
  377. //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
  378. if(gs.isVisible(o, i->first) || (!cl.getPlayerState(i->first)->human && o->ID == Obj::HERO && o->tempOwner != i->first))
  379. i->second->objectRemoved(o);
  380. }
  381. CGI->mh->waitForOngoingAnimations();
  382. }
  383. void ApplyClientNetPackVisitor::visitRemoveObject(RemoveObject & pack)
  384. {
  385. cl.invalidatePaths();
  386. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  387. i->second->objectRemovedAfter();
  388. }
  389. void ApplyFirstClientNetPackVisitor::visitTryMoveHero(TryMoveHero & pack)
  390. {
  391. CGHeroInstance *h = gs.getHero(pack.id);
  392. if(CGI->mh)
  393. {
  394. switch (pack.result)
  395. {
  396. case TryMoveHero::EMBARK:
  397. CGI->mh->onBeforeHeroEmbark(h, pack.start, pack.end);
  398. break;
  399. case TryMoveHero::TELEPORTATION:
  400. CGI->mh->onBeforeHeroTeleported(h, pack.start, pack.end);
  401. break;
  402. case TryMoveHero::DISEMBARK:
  403. CGI->mh->onBeforeHeroDisembark(h, pack.start, pack.end);
  404. break;
  405. }
  406. CGI->mh->waitForOngoingAnimations();
  407. }
  408. }
  409. void ApplyClientNetPackVisitor::visitTryMoveHero(TryMoveHero & pack)
  410. {
  411. const CGHeroInstance *h = cl.getHero(pack.id);
  412. cl.invalidatePaths();
  413. if(CGI->mh)
  414. {
  415. switch(pack.result)
  416. {
  417. case TryMoveHero::SUCCESS:
  418. CGI->mh->onHeroMoved(h, pack.start, pack.end);
  419. break;
  420. case TryMoveHero::EMBARK:
  421. CGI->mh->onAfterHeroEmbark(h, pack.start, pack.end);
  422. break;
  423. case TryMoveHero::TELEPORTATION:
  424. CGI->mh->onAfterHeroTeleported(h, pack.start, pack.end);
  425. break;
  426. case TryMoveHero::DISEMBARK:
  427. CGI->mh->onAfterHeroDisembark(h, pack.start, pack.end);
  428. break;
  429. }
  430. }
  431. PlayerColor player = h->tempOwner;
  432. for(auto &i : cl.playerint)
  433. if(cl.getPlayerRelations(i.first, player) != PlayerRelations::ENEMIES)
  434. i.second->tileRevealed(pack.fowRevealed);
  435. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  436. {
  437. if(i->first != PlayerColor::SPECTATOR && gs.checkForStandardLoss(i->first)) // Do not notify vanquished pack.player's interface
  438. continue;
  439. if(gs.isVisible(h->convertToVisitablePos(pack.start), i->first)
  440. || gs.isVisible(h->convertToVisitablePos(pack.end), i->first))
  441. {
  442. // pack.src and pack.dst of enemy hero move may be not visible => 'verbose' should be false
  443. const bool verbose = cl.getPlayerRelations(i->first, player) != PlayerRelations::ENEMIES;
  444. i->second->heroMoved(pack, verbose);
  445. }
  446. }
  447. }
  448. void ApplyClientNetPackVisitor::visitNewStructures(NewStructures & pack)
  449. {
  450. CGTownInstance *town = gs.getTown(pack.tid);
  451. for(const auto & id : pack.bid)
  452. {
  453. callInterfaceIfPresent(cl, town->tempOwner, &IGameEventsReceiver::buildChanged, town, id, 1);
  454. }
  455. // invalidate section of map view with our object and force an update
  456. CGI->mh->onObjectInstantRemove(town);
  457. CGI->mh->onObjectInstantAdd(town);
  458. }
  459. void ApplyClientNetPackVisitor::visitRazeStructures(RazeStructures & pack)
  460. {
  461. CGTownInstance * town = gs.getTown(pack.tid);
  462. for(const auto & id : pack.bid)
  463. {
  464. callInterfaceIfPresent(cl, town->tempOwner, &IGameEventsReceiver::buildChanged, town, id, 2);
  465. }
  466. // invalidate section of map view with our object and force an update
  467. CGI->mh->onObjectInstantRemove(town);
  468. CGI->mh->onObjectInstantAdd(town);
  469. }
  470. void ApplyClientNetPackVisitor::visitSetAvailableCreatures(SetAvailableCreatures & pack)
  471. {
  472. const CGDwelling * dw = static_cast<const CGDwelling*>(cl.getObj(pack.tid));
  473. PlayerColor p;
  474. if(dw->ID == Obj::WAR_MACHINE_FACTORY) //War Machines Factory is not flaggable, it's "owned" by visitor
  475. p = cl.getTile(dw->visitablePos())->visitableObjects.back()->tempOwner;
  476. else
  477. p = dw->tempOwner;
  478. callInterfaceIfPresent(cl, p, &IGameEventsReceiver::availableCreaturesChanged, dw);
  479. }
  480. void ApplyClientNetPackVisitor::visitSetHeroesInTown(SetHeroesInTown & pack)
  481. {
  482. CGTownInstance * t = gs.getTown(pack.tid);
  483. CGHeroInstance * hGarr = gs.getHero(pack.garrison);
  484. CGHeroInstance * hVisit = gs.getHero(pack.visiting);
  485. //inform all players that see this object
  486. for(auto i = cl.playerint.cbegin(); i != cl.playerint.cend(); ++i)
  487. {
  488. if(i->first >= PlayerColor::PLAYER_LIMIT)
  489. continue;
  490. if(gs.isVisible(t, i->first) ||
  491. (hGarr && gs.isVisible(hGarr, i->first)) ||
  492. (hVisit && gs.isVisible(hVisit, i->first)))
  493. {
  494. cl.playerint[i->first]->heroInGarrisonChange(t);
  495. }
  496. }
  497. }
  498. void ApplyClientNetPackVisitor::visitHeroRecruited(HeroRecruited & pack)
  499. {
  500. CGHeroInstance *h = gs.map->heroesOnMap.back();
  501. if(h->subID != pack.hid)
  502. {
  503. logNetwork->error("Something wrong with hero recruited!");
  504. }
  505. if(callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroCreated, h))
  506. {
  507. if(const CGTownInstance *t = gs.getTown(pack.tid))
  508. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroInGarrisonChange, t);
  509. }
  510. if(CGI->mh)
  511. CGI->mh->onObjectInstantAdd(h);
  512. }
  513. void ApplyClientNetPackVisitor::visitGiveHero(GiveHero & pack)
  514. {
  515. CGHeroInstance *h = gs.getHero(pack.id);
  516. if(CGI->mh)
  517. CGI->mh->onObjectInstantAdd(h);
  518. callInterfaceIfPresent(cl, h->tempOwner, &IGameEventsReceiver::heroCreated, h);
  519. }
  520. void ApplyFirstClientNetPackVisitor::visitGiveHero(GiveHero & pack)
  521. {
  522. }
  523. void ApplyClientNetPackVisitor::visitInfoWindow(InfoWindow & pack)
  524. {
  525. std::string str;
  526. pack.text.toString(str);
  527. if(!callInterfaceIfPresent(cl, pack.player, &CGameInterface::showInfoDialog, pack.type, str, pack.components,(soundBase::soundID)pack.soundID))
  528. logNetwork->warn("We received InfoWindow for not our player...");
  529. }
  530. void ApplyClientNetPackVisitor::visitSetObjectProperty(SetObjectProperty & pack)
  531. {
  532. //inform all players that see this object
  533. for(auto it = cl.playerint.cbegin(); it != cl.playerint.cend(); ++it)
  534. {
  535. if(gs.isVisible(gs.getObjInstance(pack.id), it->first))
  536. callInterfaceIfPresent(cl, it->first, &IGameEventsReceiver::objectPropertyChanged, &pack);
  537. }
  538. if (pack.what == ObjProperty::OWNER)
  539. {
  540. // invalidate section of map view with our object and force an update with new flag color
  541. CGI->mh->onObjectInstantRemove(gs.getObjInstance(pack.id));
  542. CGI->mh->onObjectInstantAdd(gs.getObjInstance(pack.id));
  543. }
  544. }
  545. void ApplyClientNetPackVisitor::visitHeroLevelUp(HeroLevelUp & pack)
  546. {
  547. const CGHeroInstance * hero = cl.getHero(pack.heroId);
  548. assert(hero);
  549. callOnlyThatInterface(cl, pack.player, &CGameInterface::heroGotLevel, hero, pack.primskill, pack.skills, pack.queryID);
  550. }
  551. void ApplyClientNetPackVisitor::visitCommanderLevelUp(CommanderLevelUp & pack)
  552. {
  553. const CGHeroInstance * hero = cl.getHero(pack.heroId);
  554. assert(hero);
  555. const CCommanderInstance * commander = hero->commander;
  556. assert(commander);
  557. assert(commander->armyObj); //is it possible for Commander to exist beyond armed instance?
  558. callOnlyThatInterface(cl, pack.player, &CGameInterface::commanderGotLevel, commander, pack.skills, pack.queryID);
  559. }
  560. void ApplyClientNetPackVisitor::visitBlockingDialog(BlockingDialog & pack)
  561. {
  562. std::string str;
  563. pack.text.toString(str);
  564. if(!callOnlyThatInterface(cl, pack.player, &CGameInterface::showBlockingDialog, str, pack.components, pack.queryID, (soundBase::soundID)pack.soundID, pack.selection(), pack.cancel()))
  565. logNetwork->warn("We received YesNoDialog for not our player...");
  566. }
  567. void ApplyClientNetPackVisitor::visitGarrisonDialog(GarrisonDialog & pack)
  568. {
  569. const CGHeroInstance *h = cl.getHero(pack.hid);
  570. const CArmedInstance *obj = static_cast<const CArmedInstance*>(cl.getObj(pack.objid));
  571. callOnlyThatInterface(cl, h->getOwner(), &CGameInterface::showGarrisonDialog, obj, h, pack.removableUnits, pack.queryID);
  572. }
  573. void ApplyClientNetPackVisitor::visitExchangeDialog(ExchangeDialog & pack)
  574. {
  575. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::heroExchangeStarted, pack.hero1, pack.hero2, pack.queryID);
  576. }
  577. void ApplyClientNetPackVisitor::visitTeleportDialog(TeleportDialog & pack)
  578. {
  579. callOnlyThatInterface(cl, pack.player, &CGameInterface::showTeleportDialog, pack.channel, pack.exits, pack.impassable, pack.queryID);
  580. }
  581. void ApplyClientNetPackVisitor::visitMapObjectSelectDialog(MapObjectSelectDialog & pack)
  582. {
  583. callOnlyThatInterface(cl, pack.player, &CGameInterface::showMapObjectSelectDialog, pack.queryID, pack.icon, pack.title, pack.description, pack.objects);
  584. }
  585. void ApplyFirstClientNetPackVisitor::visitBattleStart(BattleStart & pack)
  586. {
  587. // Cannot use the usual code because curB is not set yet
  588. callOnlyThatBattleInterface(cl, pack.info->sides[0].color, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  589. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  590. callOnlyThatBattleInterface(cl, pack.info->sides[1].color, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  591. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  592. callOnlyThatBattleInterface(cl, PlayerColor::SPECTATOR, &IBattleEventsReceiver::battleStartBefore, pack.info->sides[0].armyObject, pack.info->sides[1].armyObject,
  593. pack.info->tile, pack.info->sides[0].hero, pack.info->sides[1].hero);
  594. }
  595. void ApplyClientNetPackVisitor::visitBattleStart(BattleStart & pack)
  596. {
  597. cl.battleStarted(pack.info);
  598. }
  599. void ApplyFirstClientNetPackVisitor::visitBattleNextRound(BattleNextRound & pack)
  600. {
  601. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleNewRoundFirst, pack.round);
  602. }
  603. void ApplyClientNetPackVisitor::visitBattleNextRound(BattleNextRound & pack)
  604. {
  605. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleNewRound, pack.round);
  606. }
  607. void ApplyClientNetPackVisitor::visitBattleSetActiveStack(BattleSetActiveStack & pack)
  608. {
  609. if(!pack.askPlayerInterface)
  610. return;
  611. const CStack *activated = gs.curB->battleGetStackByID(pack.stack);
  612. PlayerColor playerToCall; //pack.player that will move activated stack
  613. if (activated->hasBonusOfType(BonusType::HYPNOTIZED))
  614. {
  615. playerToCall = (gs.curB->sides[0].color == activated->unitOwner()
  616. ? gs.curB->sides[1].color
  617. : gs.curB->sides[0].color);
  618. }
  619. else
  620. {
  621. playerToCall = activated->unitOwner();
  622. }
  623. cl.startPlayerBattleAction(playerToCall);
  624. }
  625. void ApplyClientNetPackVisitor::visitBattleLogMessage(BattleLogMessage & pack)
  626. {
  627. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleLogMessage, pack.lines);
  628. }
  629. void ApplyClientNetPackVisitor::visitBattleTriggerEffect(BattleTriggerEffect & pack)
  630. {
  631. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleTriggerEffect, pack);
  632. }
  633. void ApplyFirstClientNetPackVisitor::visitBattleUpdateGateState(BattleUpdateGateState & pack)
  634. {
  635. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleGateStateChanged, pack.state);
  636. }
  637. void ApplyFirstClientNetPackVisitor::visitBattleResult(BattleResult & pack)
  638. {
  639. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleEnd, &pack, pack.queryID);
  640. cl.battleFinished();
  641. }
  642. void ApplyFirstClientNetPackVisitor::visitBattleStackMoved(BattleStackMoved & pack)
  643. {
  644. const CStack * movedStack = gs.curB->battleGetStackByID(pack.stack);
  645. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStackMoved, movedStack, pack.tilesToMove, pack.distance, pack.teleporting);
  646. }
  647. void ApplyFirstClientNetPackVisitor::visitBattleAttack(BattleAttack & pack)
  648. {
  649. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleAttack, &pack);
  650. // battleStacksAttacked should be excuted before BattleAttack.applyGs() to play animation before damaging unit
  651. // so this has to be here instead of ApplyClientNetPackVisitor::visitBattleAttack()
  652. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksAttacked, pack.bsa, pack.shot());
  653. }
  654. void ApplyClientNetPackVisitor::visitBattleAttack(BattleAttack & pack)
  655. {
  656. }
  657. void ApplyFirstClientNetPackVisitor::visitStartAction(StartAction & pack)
  658. {
  659. cl.curbaction = std::make_optional(pack.ba);
  660. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionStarted, pack.ba);
  661. }
  662. void ApplyClientNetPackVisitor::visitBattleSpellCast(BattleSpellCast & pack)
  663. {
  664. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleSpellCast, &pack);
  665. }
  666. void ApplyClientNetPackVisitor::visitSetStackEffect(SetStackEffect & pack)
  667. {
  668. //informing about effects
  669. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksEffectsSet, pack);
  670. }
  671. void ApplyClientNetPackVisitor::visitStacksInjured(StacksInjured & pack)
  672. {
  673. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleStacksAttacked, pack.stacks, false);
  674. }
  675. void ApplyClientNetPackVisitor::visitBattleResultsApplied(BattleResultsApplied & pack)
  676. {
  677. callInterfaceIfPresent(cl, pack.player1, &IGameEventsReceiver::battleResultsApplied);
  678. callInterfaceIfPresent(cl, pack.player2, &IGameEventsReceiver::battleResultsApplied);
  679. callInterfaceIfPresent(cl, PlayerColor::SPECTATOR, &IGameEventsReceiver::battleResultsApplied);
  680. }
  681. void ApplyClientNetPackVisitor::visitBattleUnitsChanged(BattleUnitsChanged & pack)
  682. {
  683. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleUnitsChanged, pack.changedStacks);
  684. }
  685. void ApplyClientNetPackVisitor::visitBattleObstaclesChanged(BattleObstaclesChanged & pack)
  686. {
  687. //inform interfaces about removed obstacles
  688. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleObstaclesChanged, pack.changes);
  689. }
  690. void ApplyClientNetPackVisitor::visitCatapultAttack(CatapultAttack & pack)
  691. {
  692. //inform interfaces about catapult attack
  693. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::battleCatapultAttacked, pack);
  694. }
  695. void ApplyClientNetPackVisitor::visitEndAction(EndAction & pack)
  696. {
  697. callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionFinished, *cl.curbaction);
  698. cl.curbaction.reset();
  699. }
  700. void ApplyClientNetPackVisitor::visitPackageApplied(PackageApplied & pack)
  701. {
  702. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::requestRealized, &pack);
  703. if(!CClient::waitingRequest.tryRemovingElement(pack.requestID))
  704. logNetwork->warn("Surprising server message! PackageApplied for unknown requestID!");
  705. }
  706. void ApplyClientNetPackVisitor::visitSystemMessage(SystemMessage & pack)
  707. {
  708. std::ostringstream str;
  709. str << "System message: " << pack.text;
  710. logNetwork->error(str.str()); // usually used to receive error messages from server
  711. if(LOCPLINT && !settings["session"]["hideSystemMessages"].Bool())
  712. LOCPLINT->cingconsole->print(str.str());
  713. }
  714. void ApplyClientNetPackVisitor::visitPlayerBlocked(PlayerBlocked & pack)
  715. {
  716. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::playerBlocked, pack.reason, pack.startOrEnd == PlayerBlocked::BLOCKADE_STARTED);
  717. }
  718. void ApplyClientNetPackVisitor::visitYourTurn(YourTurn & pack)
  719. {
  720. logNetwork->debug("Server gives turn to %s", pack.player.getStr());
  721. callAllInterfaces(cl, &IGameEventsReceiver::playerStartsTurn, pack.player);
  722. callOnlyThatInterface(cl, pack.player, &CGameInterface::yourTurn);
  723. }
  724. void ApplyClientNetPackVisitor::visitSaveGameClient(SaveGameClient & pack)
  725. {
  726. const auto stem = FileInfo::GetPathStem(pack.fname);
  727. if(!CResourceHandler::get("local")->createResource(stem.to_string() + ".vcgm1"))
  728. {
  729. logNetwork->error("Failed to create resource %s", stem.to_string() + ".vcgm1");
  730. return;
  731. }
  732. try
  733. {
  734. CSaveFile save(*CResourceHandler::get()->getResourceName(ResourceID(stem.to_string(), EResType::CLIENT_SAVEGAME)));
  735. save << cl;
  736. }
  737. catch(std::exception &e)
  738. {
  739. logNetwork->error("Failed to save game:%s", e.what());
  740. }
  741. }
  742. void ApplyClientNetPackVisitor::visitPlayerMessageClient(PlayerMessageClient & pack)
  743. {
  744. logNetwork->debug("pack.player %s sends a message: %s", pack.player.getStr(), pack.text);
  745. std::ostringstream str;
  746. if(pack.player.isSpectator())
  747. str << "Spectator: " << pack.text;
  748. else
  749. str << cl.getPlayerState(pack.player)->nodeName() <<": " << pack.text;
  750. if(LOCPLINT)
  751. LOCPLINT->cingconsole->print(str.str());
  752. }
  753. void ApplyClientNetPackVisitor::visitAdvmapSpellCast(AdvmapSpellCast & pack)
  754. {
  755. cl.invalidatePaths();
  756. auto caster = cl.getHero(pack.casterID);
  757. if(caster)
  758. //consider notifying other interfaces that see hero?
  759. callInterfaceIfPresent(cl, caster->getOwner(), &IGameEventsReceiver::advmapSpellCast, caster, pack.spellID);
  760. else
  761. logNetwork->error("Invalid hero instance");
  762. }
  763. void ApplyClientNetPackVisitor::visitShowWorldViewEx(ShowWorldViewEx & pack)
  764. {
  765. callOnlyThatInterface(cl, pack.player, &CGameInterface::showWorldViewEx, pack.objectPositions, pack.showTerrain);
  766. }
  767. void ApplyClientNetPackVisitor::visitOpenWindow(OpenWindow & pack)
  768. {
  769. switch(pack.window)
  770. {
  771. case EOpenWindowMode::RECRUITMENT_FIRST:
  772. case EOpenWindowMode::RECRUITMENT_ALL:
  773. {
  774. const CGDwelling *dw = dynamic_cast<const CGDwelling*>(cl.getObj(ObjectInstanceID(pack.id1)));
  775. const CArmedInstance *dst = dynamic_cast<const CArmedInstance*>(cl.getObj(ObjectInstanceID(pack.id2)));
  776. callInterfaceIfPresent(cl, dst->tempOwner, &IGameEventsReceiver::showRecruitmentDialog, dw, dst, pack.window == EOpenWindowMode::RECRUITMENT_FIRST ? 0 : -1);
  777. }
  778. break;
  779. case EOpenWindowMode::SHIPYARD_WINDOW:
  780. {
  781. const IShipyard *sy = IShipyard::castFrom(cl.getObj(ObjectInstanceID(pack.id1)));
  782. callInterfaceIfPresent(cl, sy->o->tempOwner, &IGameEventsReceiver::showShipyardDialog, sy);
  783. }
  784. break;
  785. case EOpenWindowMode::THIEVES_GUILD:
  786. {
  787. //displays Thieves' Guild window (when hero enters Den of Thieves)
  788. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id2));
  789. callInterfaceIfPresent(cl, PlayerColor(pack.id1), &IGameEventsReceiver::showThievesGuildWindow, obj);
  790. }
  791. break;
  792. case EOpenWindowMode::UNIVERSITY_WINDOW:
  793. {
  794. //displays University window (when hero enters University on adventure map)
  795. const IMarket *market = IMarket::castFrom(cl.getObj(ObjectInstanceID(pack.id1)));
  796. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  797. callInterfaceIfPresent(cl, hero->tempOwner, &IGameEventsReceiver::showUniversityWindow, market, hero);
  798. }
  799. break;
  800. case EOpenWindowMode::MARKET_WINDOW:
  801. {
  802. //displays Thieves' Guild window (when hero enters Den of Thieves)
  803. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id1));
  804. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  805. const IMarket *market = IMarket::castFrom(obj);
  806. callInterfaceIfPresent(cl, cl.getTile(obj->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::showMarketWindow, market, hero);
  807. }
  808. break;
  809. case EOpenWindowMode::HILL_FORT_WINDOW:
  810. {
  811. //displays Hill fort window
  812. const CGObjectInstance *obj = cl.getObj(ObjectInstanceID(pack.id1));
  813. const CGHeroInstance *hero = cl.getHero(ObjectInstanceID(pack.id2));
  814. callInterfaceIfPresent(cl, cl.getTile(obj->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::showHillFortWindow, obj, hero);
  815. }
  816. break;
  817. case EOpenWindowMode::PUZZLE_MAP:
  818. {
  819. callInterfaceIfPresent(cl, PlayerColor(pack.id1), &IGameEventsReceiver::showPuzzleMap);
  820. }
  821. break;
  822. case EOpenWindowMode::TAVERN_WINDOW:
  823. const CGObjectInstance *obj1 = cl.getObj(ObjectInstanceID(pack.id1)),
  824. *obj2 = cl.getObj(ObjectInstanceID(pack.id2));
  825. callInterfaceIfPresent(cl, obj1->tempOwner, &IGameEventsReceiver::showTavernWindow, obj2);
  826. break;
  827. }
  828. }
  829. void ApplyClientNetPackVisitor::visitCenterView(CenterView & pack)
  830. {
  831. callInterfaceIfPresent(cl, pack.player, &IGameEventsReceiver::centerView, pack.pos, pack.focusTime);
  832. }
  833. void ApplyClientNetPackVisitor::visitNewObject(NewObject & pack)
  834. {
  835. cl.invalidatePaths();
  836. const CGObjectInstance *obj = cl.getObj(pack.id);
  837. if(CGI->mh)
  838. CGI->mh->onObjectFadeIn(obj);
  839. for(auto i=cl.playerint.begin(); i!=cl.playerint.end(); i++)
  840. {
  841. if(gs.isVisible(obj, i->first))
  842. i->second->newObject(obj);
  843. }
  844. CGI->mh->waitForOngoingAnimations();
  845. }
  846. void ApplyClientNetPackVisitor::visitSetAvailableArtifacts(SetAvailableArtifacts & pack)
  847. {
  848. if(pack.id < 0) //artifact merchants globally
  849. {
  850. callAllInterfaces(cl, &IGameEventsReceiver::availableArtifactsChanged, nullptr);
  851. }
  852. else
  853. {
  854. const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(cl.getObj(ObjectInstanceID(pack.id)));
  855. assert(bm);
  856. callInterfaceIfPresent(cl, cl.getTile(bm->visitablePos())->visitableObjects.back()->tempOwner, &IGameEventsReceiver::availableArtifactsChanged, bm);
  857. }
  858. }
  859. void ApplyClientNetPackVisitor::visitEntitiesChanged(EntitiesChanged & pack)
  860. {
  861. cl.invalidatePaths();
  862. }