BattleResultProcessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * BattleResultProcessor.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 "BattleResultProcessor.h"
  12. #include "battle/BattleInfo.h"
  13. #include "../CGameHandler.h"
  14. #include "../TurnTimerHandler.h"
  15. #include "../processors/HeroPoolProcessor.h"
  16. #include "../queries/QueriesProcessor.h"
  17. #include "../queries/BattleQueries.h"
  18. #include "../../lib/CStack.h"
  19. #include "../../lib/CPlayerState.h"
  20. #include "../../lib/IGameSettings.h"
  21. #include "../../lib/battle/SideInBattle.h"
  22. #include "../../lib/entities/artifact/ArtifactUtils.h"
  23. #include "../../lib/entities/artifact/CArtifact.h"
  24. #include "../../lib/entities/artifact/CArtifactFittingSet.h"
  25. #include "../../lib/gameState/CGameState.h"
  26. #include "../../lib/mapObjects/CGTownInstance.h"
  27. #include "../../lib/networkPacks/PacksForClientBattle.h"
  28. #include "../../lib/spells/CSpellHandler.h"
  29. #include <boost/lexical_cast.hpp>
  30. BattleResultProcessor::BattleResultProcessor(BattleProcessor * owner, CGameHandler * newGameHandler)
  31. // : owner(owner)
  32. : gameHandler(newGameHandler)
  33. {
  34. }
  35. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, BattleSide sideInBattle):
  36. army(battle.battleGetArmyObject(sideInBattle))
  37. {
  38. heroWithDeadCommander = ObjectInstanceID();
  39. PlayerColor color = battle.sideToPlayer(sideInBattle);
  40. auto allStacks = battle.battleGetStacksIf([color](const CStack * stack){
  41. if (stack->summoned)//don't take into account temporary summoned stacks
  42. return false;
  43. if(stack->unitOwner() != color) //remove only our stacks
  44. return false;
  45. if (stack->isTurret())
  46. return false;
  47. return true;
  48. });
  49. for(const CStack * stConst : allStacks)
  50. {
  51. // Use const cast - in order to call non-const "takeResurrected" for proper calculation of casualties
  52. // TODO: better solution
  53. CStack * st = const_cast<CStack*>(stConst);
  54. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  55. st->health.takeResurrected();
  56. if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  57. {
  58. auto warMachine = st->unitType()->warMachine;
  59. if(warMachine == ArtifactID::NONE)
  60. {
  61. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  62. }
  63. //catapult artifact remain even if "creature" killed in siege
  64. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  65. {
  66. logGlobal->debug("War machine has been destroyed");
  67. auto hero = dynamic_cast<const CGHeroInstance*> (army);
  68. if (hero)
  69. removedWarMachines.push_back (ArtifactLocation(hero->id, hero->getArtPos(warMachine, true)));
  70. else
  71. logGlobal->error("War machine in army without hero");
  72. }
  73. }
  74. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  75. {
  76. if(st->alive() && st->getCount() > 0)
  77. {
  78. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  79. const CreatureID summonedType = st->creatureId();
  80. summoned[summonedType] += st->getCount();
  81. }
  82. }
  83. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  84. {
  85. if (nullptr == st->base)
  86. {
  87. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  88. }
  89. else
  90. {
  91. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  92. if(c)
  93. {
  94. auto h = dynamic_cast <const CGHeroInstance *>(army);
  95. if(h && h->getCommander() == c && (st->getCount() == 0 || !st->alive()))
  96. {
  97. logGlobal->debug("Commander is dead.");
  98. heroWithDeadCommander = army->id; //TODO: unify commander handling
  99. }
  100. }
  101. else
  102. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  103. }
  104. }
  105. else if(st->base && !army->slotEmpty(st->unitSlot()))
  106. {
  107. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  108. if(st->getCount() == 0 || !st->alive())
  109. {
  110. logGlobal->debug("Stack has been destroyed.");
  111. StackLocation sl(army->id, st->unitSlot());
  112. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  113. }
  114. else if(st->getCount() != army->getStackCount(st->unitSlot()))
  115. {
  116. logGlobal->debug("Stack size changed: %d -> %d units.", army->getStackCount(st->unitSlot()), st->getCount());
  117. StackLocation sl(army->id, st->unitSlot());
  118. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  119. }
  120. }
  121. else
  122. {
  123. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  124. }
  125. }
  126. }
  127. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  128. {
  129. if (gh->gameInfo().getObjInstance(army->id) == nullptr)
  130. throw std::runtime_error("Object " + army->getObjectName() + " is not on the map!");
  131. for (TStackAndItsNewCount &ncount : newStackCounts)
  132. {
  133. if (ncount.second > 0)
  134. gh->changeStackCount(ncount.first, ncount.second, ChangeValueMode::ABSOLUTE);
  135. else
  136. gh->eraseStack(ncount.first, true);
  137. }
  138. for (auto summoned_iter : summoned)
  139. {
  140. SlotID slot = army->getSlotFor(summoned_iter.first);
  141. if (slot.validSlot())
  142. {
  143. StackLocation location(army->id, slot);
  144. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  145. }
  146. else
  147. {
  148. //even if it will be possible to summon anything permanently it should be checked for free slot
  149. //necromancy is handled separately
  150. gh->complain("No free slot to put summoned creature");
  151. }
  152. }
  153. for (auto al : removedWarMachines)
  154. {
  155. gh->removeArtifact(al);
  156. }
  157. if (heroWithDeadCommander != ObjectInstanceID())
  158. {
  159. SetCommanderProperty scp;
  160. scp.heroid = heroWithDeadCommander;
  161. scp.which = SetCommanderProperty::ALIVE;
  162. scp.amount = 0;
  163. gh->sendAndApply(scp);
  164. }
  165. }
  166. FinishingBattleHelper::FinishingBattleHelper(const CBattleInfoCallback & info, const BattleResult & result, int remainingBattleQueriesCount)
  167. {
  168. const auto attackerHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  169. const auto defenderHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  170. if (result.winner == BattleSide::ATTACKER)
  171. {
  172. winnerId = attackerHero ? attackerHero->id : ObjectInstanceID::NONE;
  173. loserId = defenderHero ? defenderHero->id : ObjectInstanceID::NONE;
  174. victor = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  175. loser = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  176. }
  177. else
  178. {
  179. winnerId = defenderHero ? defenderHero->id : ObjectInstanceID::NONE;
  180. loserId = attackerHero ? attackerHero->id : ObjectInstanceID::NONE;
  181. victor = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  182. loser = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  183. }
  184. winnerSide = result.winner;
  185. this->remainingBattleQueriesCount = remainingBattleQueriesCount;
  186. }
  187. void BattleResultProcessor::endBattle(const CBattleInfoCallback & battle)
  188. {
  189. auto const & giveExp = [&battle](BattleResult &r)
  190. {
  191. if (r.winner == BattleSide::NONE)
  192. {
  193. // draw
  194. return;
  195. }
  196. r.exp[BattleSide::ATTACKER] = 0;
  197. r.exp[BattleSide::DEFENDER] = 0;
  198. for (auto i = r.casualties[battle.otherSide(r.winner)].begin(); i!=r.casualties[battle.otherSide(r.winner)].end(); i++)
  199. {
  200. r.exp[r.winner] += i->first.toCreature()->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  201. }
  202. };
  203. LOG_TRACE(logGlobal);
  204. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  205. const auto * heroAttacker = battle.battleGetFightingHero(BattleSide::ATTACKER);
  206. const auto * heroDefender = battle.battleGetFightingHero(BattleSide::DEFENDER);
  207. //Fill BattleResult structure with exp info
  208. giveExp(*battleResult);
  209. if (battleResult->result == EBattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  210. {
  211. if(heroAttacker)
  212. battleResult->exp[BattleSide::DEFENDER] += 500;
  213. if(heroDefender)
  214. battleResult->exp[BattleSide::ATTACKER] += 500;
  215. }
  216. // Give 500 exp to winner if a town was conquered during the battle
  217. const auto * defendedTown = battle.battleGetDefendedTown();
  218. if (defendedTown && battleResult->winner == BattleSide::ATTACKER)
  219. battleResult->exp[BattleSide::ATTACKER] += 500;
  220. if(heroAttacker)
  221. battleResult->exp[BattleSide::ATTACKER] = heroAttacker->calculateXp(battleResult->exp[BattleSide::ATTACKER]);//scholar skill
  222. if(heroDefender)
  223. battleResult->exp[BattleSide::DEFENDER] = heroDefender->calculateXp(battleResult->exp[BattleSide::DEFENDER]);
  224. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::ATTACKER)));
  225. if(!battleQuery)
  226. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::DEFENDER)));
  227. if (!battleQuery)
  228. {
  229. logGlobal->error("Cannot find battle query!");
  230. gameHandler->complain("Player " + boost::lexical_cast<std::string>(battle.sideToPlayer(BattleSide::ATTACKER)) + " has no battle query at the top!");
  231. return;
  232. }
  233. battleQuery->result = std::make_optional(*battleResult);
  234. //Check how many battle gameHandler->queries were created (number of players blocked by battle)
  235. const int queriedPlayers = battleQuery ? (int)boost::count(gameHandler->queries->allQueries(), battleQuery) : 0;
  236. assert(finishingBattles.count(battle.getBattle()->getBattleID()) == 0);
  237. finishingBattles[battle.getBattle()->getBattleID()] = std::make_unique<FinishingBattleHelper>(battle, *battleResult, queriedPlayers);
  238. // in battles against neutrals, 1st player can ask to replay battle manually
  239. const auto * attackerPlayer = gameHandler->gameInfo().getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::ATTACKER));
  240. const auto * defenderPlayer = gameHandler->gameInfo().getPlayerState(battle.getBattle()->getSidePlayer(BattleSide::DEFENDER));
  241. bool isAttackerHuman = attackerPlayer && attackerPlayer->isHuman();
  242. bool isDefenderHuman = defenderPlayer && defenderPlayer->isHuman();
  243. bool onlyOnePlayerHuman = isAttackerHuman != isDefenderHuman;
  244. // in battles against neutrals attacker can ask to replay battle manually, additionally in battles against AI player human side can also ask for replay
  245. if(onlyOnePlayerHuman)
  246. {
  247. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, battle.getBattle(), battleQuery->result);
  248. battleResult->queryID = battleDialogQuery->queryID;
  249. gameHandler->queries->addQuery(battleDialogQuery);
  250. }
  251. else
  252. battleResult->queryID = QueryID::NONE;
  253. //set same battle result for all gameHandler->queries
  254. for(auto q : gameHandler->queries->allQueries())
  255. {
  256. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  257. if(otherBattleQuery && otherBattleQuery->battleID == battle.getBattle()->getBattleID())
  258. otherBattleQuery->result = battleQuery->result;
  259. }
  260. gameHandler->turnTimerHandler->onBattleEnd(battle.getBattle()->getBattleID());
  261. gameHandler->sendAndApply(*battleResult);
  262. if (battleResult->queryID == QueryID::NONE)
  263. endBattleConfirm(battle);
  264. }
  265. void BattleResultProcessor::endBattleConfirm(const CBattleInfoCallback & battle)
  266. {
  267. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::ATTACKER)));
  268. if(!battleQuery)
  269. battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(BattleSide::DEFENDER)));
  270. if(!battleQuery)
  271. {
  272. logGlobal->trace("No battle query, battle end was confirmed by another player");
  273. return;
  274. }
  275. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  276. auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  277. //calculate casualties before deleting battle
  278. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  279. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  280. cab1.updateArmy(gameHandler);
  281. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  282. const auto winnerHero = battle.battleGetFightingHero(finishingBattle->winnerSide);
  283. const auto loserHero = battle.battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  284. if(battleResult->winner == BattleSide::DEFENDER
  285. && winnerHero
  286. && winnerHero->getVisitedTown()
  287. && !winnerHero->isGarrisoned()
  288. && winnerHero->getVisitedTown()->getGarrisonHero() == winnerHero)
  289. {
  290. gameHandler->swapGarrisonOnSiege(winnerHero->getVisitedTown()->id); //return defending visitor from garrison to its rightful place
  291. }
  292. //give exp
  293. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide] && winnerHero)
  294. gameHandler->giveExperience(winnerHero, battleResult->exp[finishingBattle->winnerSide]);
  295. // Add statistics
  296. if(loserHero && !finishingBattle->isDraw())
  297. {
  298. const CGHeroInstance * strongestHero = nullptr;
  299. for(auto & hero : gameHandler->gameState().getPlayerState(finishingBattle->loser)->getHeroes())
  300. if(!strongestHero || hero->exp > strongestHero->exp)
  301. strongestHero = hero;
  302. if(strongestHero->id == finishingBattle->loserId && strongestHero->level > 5)
  303. gameHandler->statistics->accumulatedValues[finishingBattle->victor].lastDefeatedStrongestHeroDay = gameHandler->gameState().getDate(Date::DAY);
  304. }
  305. if(battle.sideToPlayer(BattleSide::ATTACKER) == PlayerColor::NEUTRAL || battle.sideToPlayer(BattleSide::DEFENDER) == PlayerColor::NEUTRAL)
  306. {
  307. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesNeutral++;
  308. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesNeutral++;
  309. if(!finishingBattle->isDraw())
  310. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesNeutral++;
  311. }
  312. else
  313. {
  314. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesPlayer++;
  315. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesPlayer++;
  316. if(!finishingBattle->isDraw())
  317. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesPlayer++;
  318. }
  319. BattleResultAccepted raccepted;
  320. raccepted.battleID = battle.getBattle()->getBattleID();
  321. raccepted.heroResult[finishingBattle->winnerSide].heroID = winnerHero ? winnerHero->id : ObjectInstanceID::NONE;
  322. raccepted.heroResult[CBattleInfoEssentials::otherSide(finishingBattle->winnerSide)].heroID = loserHero ? loserHero->id : ObjectInstanceID::NONE;
  323. raccepted.heroResult[BattleSide::ATTACKER].armyID = battle.battleGetArmyObject(BattleSide::ATTACKER)->id;
  324. raccepted.heroResult[BattleSide::DEFENDER].armyID = battle.battleGetArmyObject(BattleSide::DEFENDER)->id;
  325. raccepted.heroResult[BattleSide::ATTACKER].exp = battleResult->exp[BattleSide::ATTACKER];
  326. raccepted.heroResult[BattleSide::DEFENDER].exp = battleResult->exp[BattleSide::DEFENDER];
  327. raccepted.winnerSide = finishingBattle->winnerSide;
  328. gameHandler->sendAndApply(raccepted);
  329. gameHandler->queries->popIfTop(battleQuery); // Workaround to remove battle query for AI case. TODO Think of a cleaner solution.
  330. //--> continuation (battleFinalize) occurs after level-up gameHandler->queries are handled or on removing query
  331. }
  332. void BattleResultProcessor::battleFinalize(const BattleID & battleID, const BattleResult & result)
  333. {
  334. LOG_TRACE(logGlobal);
  335. assert(finishingBattles.count(battleID) != 0);
  336. if(finishingBattles.count(battleID) == 0)
  337. return;
  338. auto & finishingBattle = finishingBattles[battleID];
  339. finishingBattle->remainingBattleQueriesCount--;
  340. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  341. if (finishingBattle->remainingBattleQueriesCount > 0)
  342. //Battle results will be handled when all battle gameHandler->queries are closed
  343. return;
  344. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  345. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  346. // Still, it looks like a hole.
  347. const auto battle = std::find_if(gameHandler->gameState().currentBattles.begin(), gameHandler->gameState().currentBattles.end(),
  348. [battleID](const auto & desiredBattle)
  349. {
  350. return desiredBattle->battleID == battleID;
  351. });
  352. assert(battle != gameHandler->gameState().currentBattles.end());
  353. const auto winnerHero = (*battle)->battleGetFightingHero(finishingBattle->winnerSide);
  354. const auto loserHero = (*battle)->battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  355. BattleResultsApplied resultsApplied;
  356. // Eagle Eye handling
  357. if(!finishingBattle->isDraw() && winnerHero)
  358. {
  359. if(auto eagleEyeLevel = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  360. {
  361. resultsApplied.learnedSpells.learn = 1;
  362. resultsApplied.learnedSpells.hid = finishingBattle->winnerId;
  363. for(const auto & spellId : (*battle)->getUsedSpells(CBattleInfoEssentials::otherSide(result.winner)))
  364. {
  365. const auto spell = spellId.toEntity(LIBRARY->spells());
  366. if(spell
  367. && spell->getLevel() <= eagleEyeLevel
  368. && !winnerHero->spellbookContainsSpell(spell->getId())
  369. && gameHandler->getRandomGenerator().nextInt(99) < winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE))
  370. {
  371. resultsApplied.learnedSpells.spells.insert(spell->getId());
  372. }
  373. }
  374. }
  375. }
  376. // Moving artifacts handling
  377. if(result.result == EBattleResult::NORMAL && !finishingBattle->isDraw() && winnerHero)
  378. {
  379. CArtifactFittingSet artFittingSet(*winnerHero);
  380. const auto addArtifactToTransfer = [&artFittingSet](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  381. {
  382. assert(art);
  383. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  384. if(dstSlot != ArtifactPosition::PRE_FIRST)
  385. {
  386. pack.artsPack0.emplace_back(MoveArtifactInfo(srcSlot, dstSlot));
  387. if(ArtifactUtils::isSlotEquipment(dstSlot))
  388. pack.artsPack0.back().askAssemble = true;
  389. artFittingSet.putArtifact(dstSlot, const_cast<CArtifactInstance*>(art));
  390. }
  391. };
  392. if(loserHero)
  393. {
  394. auto & packHero = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  395. packHero.srcArtHolder = finishingBattle->loserId;
  396. for(const auto & slot : ArtifactUtils::commonWornSlots())
  397. {
  398. if(const auto artSlot = loserHero->artifactsWorn.find(slot); artSlot != loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  399. {
  400. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  401. }
  402. }
  403. for(const auto & artSlot : loserHero->artifactsInBackpack)
  404. {
  405. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  406. addArtifactToTransfer(packHero, loserHero->getArtPos(art), art);
  407. }
  408. if(loserHero->getCommander())
  409. {
  410. auto & packCommander = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  411. packCommander.srcCreature = loserHero->findStack(loserHero->getCommander());
  412. for(const auto & artSlot : loserHero->getCommander()->artifactsWorn)
  413. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  414. }
  415. auto armyObj = dynamic_cast<const CArmedInstance*>(gameHandler->gameInfo().getObj(finishingBattle->loserId));
  416. for(const auto & armySlot : armyObj->stacks)
  417. {
  418. auto & packsArmy = resultsApplied.movingArtifacts.emplace_back(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  419. packsArmy.srcArtHolder = armyObj->id;
  420. packsArmy.srcCreature = armySlot.first;
  421. for(const auto & artSlot : armySlot.second->artifactsWorn)
  422. addArtifactToTransfer(packsArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  423. }
  424. }
  425. }
  426. // Growing artifacts handling
  427. if(!finishingBattle->isDraw() && winnerHero)
  428. {
  429. const auto addArtifactToGrowing = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap)
  430. {
  431. for(const auto & [slot, slotInfo] : artMap)
  432. {
  433. const auto artInst = slotInfo.getArt();
  434. assert(artInst);
  435. if(artInst->getType()->isGrowing())
  436. resultsApplied.growingArtifacts.emplace_back(artInst->getId());
  437. }
  438. };
  439. if(const auto commander = winnerHero->getCommander(); commander && commander->alive)
  440. addArtifactToGrowing(commander->artifactsWorn);
  441. addArtifactToGrowing(winnerHero->artifactsWorn);
  442. }
  443. // Charged artifacts handling
  444. const auto addArtifactToDischarging = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap,
  445. const ObjectInstanceID & id, const std::optional<SlotID> & creature = std::nullopt)
  446. {
  447. for(const auto & [slot, slotInfo] : artMap)
  448. {
  449. auto artInst = slotInfo.getArt();
  450. assert(artInst);
  451. if(const auto condition = artInst->getType()->getDischargeCondition(); condition == DischargeArtifactCondition::BATTLE)
  452. {
  453. auto & discharging = resultsApplied.dischargingArtifacts.emplace_back(artInst->getId(), 1);
  454. discharging.artLoc.emplace(id, creature, slot);
  455. }
  456. }
  457. };
  458. if(winnerHero)
  459. {
  460. addArtifactToDischarging(winnerHero->artifactsWorn, winnerHero->id);
  461. if(const auto commander = winnerHero->getCommander())
  462. addArtifactToDischarging(commander->artifactsWorn, winnerHero->id, winnerHero->findStack(winnerHero->getCommander()));
  463. }
  464. if(loserHero)
  465. {
  466. addArtifactToDischarging(loserHero->artifactsWorn, loserHero->id);
  467. if(const auto commander = loserHero->getCommander())
  468. addArtifactToDischarging(commander->artifactsWorn, loserHero->id, loserHero->findStack(loserHero->getCommander()));
  469. }
  470. // Necromancy handling
  471. // Give raised units to winner, if any were raised, units will be given after casualties are taken
  472. if(winnerHero)
  473. {
  474. resultsApplied.raisedStack = winnerHero->calculateNecromancy(result);
  475. const SlotID necroSlot = resultsApplied.raisedStack.getCreature() ? winnerHero->getSlotFor(resultsApplied.raisedStack.getCreature()) : SlotID();
  476. if(necroSlot != SlotID() && !finishingBattle->isDraw())
  477. gameHandler->addToSlot(StackLocation(finishingBattle->winnerId, necroSlot), resultsApplied.raisedStack.getCreature(), resultsApplied.raisedStack.getCount());
  478. }
  479. resultsApplied.battleID = battleID;
  480. resultsApplied.victor = finishingBattle->victor;
  481. resultsApplied.loser = finishingBattle->loser;
  482. gameHandler->sendAndApply(resultsApplied);
  483. //handle victory/loss of engaged players
  484. gameHandler->checkVictoryLossConditions({finishingBattle->loser, finishingBattle->victor});
  485. // Remove beaten hero
  486. if(loserHero)
  487. {
  488. RemoveObject ro(loserHero->id, finishingBattle->victor);
  489. gameHandler->sendAndApply(ro);
  490. }
  491. // For draw case both heroes should be removed
  492. if(finishingBattle->isDraw() && winnerHero)
  493. {
  494. RemoveObject ro(winnerHero->id, finishingBattle->loser);
  495. gameHandler->sendAndApply(ro);
  496. if(gameHandler->gameInfo().getSettings().getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  497. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, winnerHero);
  498. }
  499. if (result.result == EBattleResult::SURRENDER)
  500. {
  501. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroSurrendered++;
  502. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, loserHero);
  503. }
  504. if (result.result == EBattleResult::ESCAPE)
  505. {
  506. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroEscaped++;
  507. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, loserHero);
  508. }
  509. finishingBattles.erase(battleID);
  510. battleResults.erase(battleID);
  511. }
  512. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, BattleSide victoriusSide)
  513. {
  514. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  515. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  516. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  517. battleResult->battleID = battle.getBattle()->getBattleID();
  518. battleResult->result = resultType;
  519. battleResult->winner = victoriusSide; //surrendering side loses
  520. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  521. if (stack->summoned)//don't take into account temporary summoned stacks
  522. return false;
  523. if (stack->isTurret())
  524. return false;
  525. return true;
  526. });
  527. for(const auto & st : allStacks) //setting casualties
  528. {
  529. si32 killed = st->getKilled();
  530. if(killed > 0)
  531. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  532. }
  533. }
  534. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  535. {
  536. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  537. }