BattleResultProcessor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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/GameLibrary.h"
  19. #include "../../lib/CStack.h"
  20. #include "../../lib/CPlayerState.h"
  21. #include "../../lib/IGameSettings.h"
  22. #include "../../lib/battle/SideInBattle.h"
  23. #include "../../lib/entities/artifact/ArtifactUtils.h"
  24. #include "../../lib/entities/artifact/CArtifact.h"
  25. #include "../../lib/entities/artifact/CArtifactFittingSet.h"
  26. #include "../../lib/gameState/CGameState.h"
  27. #include "../../lib/mapObjects/CGTownInstance.h"
  28. #include "../../lib/networkPacks/PacksForClientBattle.h"
  29. #include "../../lib/spells/CSpellHandler.h"
  30. #include <boost/lexical_cast.hpp>
  31. BattleResultProcessor::BattleResultProcessor(CGameHandler * gameHandler)
  32. : gameHandler(gameHandler)
  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. auto * 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 (const auto & 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 ? 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. const auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  276. const 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 attackerHero = battle.battleGetFightingHero(BattleSide::ATTACKER);
  283. const auto defenderHero = battle.battleGetFightingHero(BattleSide::DEFENDER);
  284. const auto winnerHero = battle.battleGetFightingHero(finishingBattle->winnerSide);
  285. const auto loserHero = battle.battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  286. //give exp
  287. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide])
  288. {
  289. gameHandler->giveStackExperience(battle.battleGetArmyObject(finishingBattle->winnerSide), battleResult->exp[finishingBattle->winnerSide]);
  290. if (winnerHero)
  291. gameHandler->giveExperience(winnerHero, battleResult->exp[finishingBattle->winnerSide]);
  292. }
  293. // Add statistics
  294. if(loserHero && !finishingBattle->isDraw())
  295. {
  296. const CGHeroInstance * strongestHero = nullptr;
  297. for(auto & hero : gameHandler->gameState().getPlayerState(finishingBattle->loser)->getHeroes())
  298. if(!strongestHero || hero->exp > strongestHero->exp)
  299. strongestHero = hero;
  300. if(strongestHero->id == finishingBattle->loserId && strongestHero->level > 5)
  301. gameHandler->statistics->accumulatedValues[finishingBattle->victor].lastDefeatedStrongestHeroDay = gameHandler->gameState().getDate(Date::DAY);
  302. }
  303. if(battle.sideToPlayer(BattleSide::ATTACKER) == PlayerColor::NEUTRAL || battle.sideToPlayer(BattleSide::DEFENDER) == PlayerColor::NEUTRAL)
  304. {
  305. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesNeutral++;
  306. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesNeutral++;
  307. if(!finishingBattle->isDraw())
  308. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesNeutral++;
  309. }
  310. else
  311. {
  312. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::ATTACKER)].numBattlesPlayer++;
  313. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(BattleSide::DEFENDER)].numBattlesPlayer++;
  314. if(!finishingBattle->isDraw())
  315. gameHandler->statistics->accumulatedValues[battle.sideToPlayer(finishingBattle->winnerSide)].numWinBattlesPlayer++;
  316. }
  317. BattleResultAccepted raccepted;
  318. raccepted.battleID = battle.getBattle()->getBattleID();
  319. raccepted.heroResult[BattleSide::ATTACKER].heroID = attackerHero ? attackerHero->id : ObjectInstanceID::NONE;
  320. raccepted.heroResult[BattleSide::DEFENDER].heroID = defenderHero ? defenderHero->id : ObjectInstanceID::NONE;
  321. raccepted.heroResult[BattleSide::ATTACKER].armyID = battle.battleGetArmyObject(BattleSide::ATTACKER)->id;
  322. raccepted.heroResult[BattleSide::DEFENDER].armyID = battle.battleGetArmyObject(BattleSide::DEFENDER)->id;
  323. raccepted.heroResult[BattleSide::ATTACKER].exp = battleResult->exp[BattleSide::ATTACKER];
  324. raccepted.heroResult[BattleSide::DEFENDER].exp = battleResult->exp[BattleSide::DEFENDER];
  325. raccepted.winnerSide = finishingBattle->winnerSide;
  326. gameHandler->sendAndApply(raccepted);
  327. gameHandler->queries->popIfTop(battleQuery); // Workaround to remove battle query for AI case. TODO Think of a cleaner solution.
  328. //--> continuation (battleFinalize) occurs after level-up gameHandler->queries are handled or on removing query
  329. }
  330. void BattleResultProcessor::battleFinalize(const BattleID & battleID, const BattleResult & result)
  331. {
  332. LOG_TRACE(logGlobal);
  333. assert(finishingBattles.count(battleID) != 0);
  334. if(finishingBattles.count(battleID) == 0)
  335. return;
  336. auto & finishingBattle = finishingBattles[battleID];
  337. finishingBattle->remainingBattleQueriesCount--;
  338. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  339. if (finishingBattle->remainingBattleQueriesCount > 0)
  340. //Battle results will be handled when all battle gameHandler->queries are closed
  341. return;
  342. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  343. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  344. // Still, it looks like a hole.
  345. const auto battle = std::find_if(gameHandler->gameState().currentBattles.begin(), gameHandler->gameState().currentBattles.end(),
  346. [battleID](const auto & desiredBattle)
  347. {
  348. return desiredBattle->battleID == battleID;
  349. });
  350. assert(battle != gameHandler->gameState().currentBattles.end());
  351. const CGHeroInstance * winnerHero = nullptr;
  352. const CGHeroInstance * loserHero = nullptr;
  353. const auto attackerHero = (*battle)->battleGetFightingHero(BattleSide::ATTACKER);
  354. const auto defenderHero = (*battle)->battleGetFightingHero(BattleSide::DEFENDER);
  355. const auto attackerSide = (*battle)->getSidePlayer(BattleSide::ATTACKER);
  356. const auto defenderSide = (*battle)->getSidePlayer(BattleSide::DEFENDER);
  357. if (!finishingBattle->isDraw())
  358. {
  359. winnerHero = (*battle)->battleGetFightingHero(finishingBattle->winnerSide);
  360. loserHero = (*battle)->battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  361. }
  362. BattleResultsApplied resultsApplied;
  363. // Eagle Eye handling
  364. if(winnerHero)
  365. {
  366. if(auto eagleEyeLevel = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  367. {
  368. resultsApplied.learnedSpells.learn = 1;
  369. resultsApplied.learnedSpells.hid = finishingBattle->winnerId;
  370. for(const auto & spellId : (*battle)->getUsedSpells(CBattleInfoEssentials::otherSide(result.winner)))
  371. {
  372. const auto spell = spellId.toEntity(LIBRARY->spells());
  373. if(spell
  374. && spell->getLevel() <= eagleEyeLevel
  375. && !winnerHero->spellbookContainsSpell(spell->getId())
  376. && gameHandler->getRandomGenerator().nextInt(99) < winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE))
  377. {
  378. resultsApplied.learnedSpells.spells.insert(spell->getId());
  379. }
  380. }
  381. }
  382. }
  383. // Moving artifacts handling
  384. if(result.result == EBattleResult::NORMAL && winnerHero && loserHero)
  385. {
  386. CArtifactFittingSet artFittingSet(*winnerHero);
  387. const auto addArtifactToTransfer = [&artFittingSet](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  388. {
  389. assert(art);
  390. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  391. if(dstSlot != ArtifactPosition::PRE_FIRST)
  392. {
  393. pack.artsPack0.emplace_back(MoveArtifactInfo(srcSlot, dstSlot));
  394. if(ArtifactUtils::isSlotEquipment(dstSlot))
  395. pack.artsPack0.back().askAssemble = true;
  396. artFittingSet.putArtifact(dstSlot, art);
  397. }
  398. };
  399. BulkMoveArtifacts packHero(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  400. packHero.srcArtHolder = finishingBattle->loserId;
  401. for(const auto & slot : ArtifactUtils::commonWornSlots())
  402. {
  403. if(const auto artSlot = loserHero->artifactsWorn.find(slot); artSlot != loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  404. {
  405. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  406. }
  407. }
  408. for(const auto & artSlot : loserHero->artifactsInBackpack)
  409. {
  410. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  411. addArtifactToTransfer(packHero, loserHero->getArtPos(art), art);
  412. }
  413. if(!packHero.artsPack0.empty())
  414. resultsApplied.movingArtifacts.emplace_back(std::move(packHero));
  415. if(loserHero->getCommander())
  416. {
  417. BulkMoveArtifacts packCommander(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  418. packCommander.srcCreature = loserHero->findStack(loserHero->getCommander());
  419. for(const auto & artSlot : loserHero->getCommander()->artifactsWorn)
  420. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  421. if(!packCommander.artsPack0.empty())
  422. resultsApplied.movingArtifacts.emplace_back(std::move(packCommander));
  423. }
  424. auto armyObj = dynamic_cast<const CArmedInstance*>(gameHandler->gameInfo().getObj(finishingBattle->loserId));
  425. for(const auto & armySlot : armyObj->stacks)
  426. {
  427. BulkMoveArtifacts packArmy(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  428. packArmy.srcArtHolder = armyObj->id;
  429. packArmy.srcCreature = armySlot.first;
  430. for(const auto & artSlot : armySlot.second->artifactsWorn)
  431. addArtifactToTransfer(packArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  432. if(!packArmy.artsPack0.empty())
  433. resultsApplied.movingArtifacts.emplace_back(std::move(packArmy));
  434. }
  435. }
  436. // Growing artifacts handling
  437. if(winnerHero)
  438. {
  439. const auto addArtifactToGrowing = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap)
  440. {
  441. for(const auto & [slot, slotInfo] : artMap)
  442. {
  443. const auto artInst = slotInfo.getArt();
  444. assert(artInst);
  445. if(artInst->getType()->isGrowing())
  446. resultsApplied.growingArtifacts.emplace_back(artInst->getId());
  447. }
  448. };
  449. if(const auto commander = winnerHero->getCommander(); commander && commander->alive)
  450. addArtifactToGrowing(commander->artifactsWorn);
  451. addArtifactToGrowing(winnerHero->artifactsWorn);
  452. }
  453. // Charged artifacts handling
  454. const auto addArtifactToDischarging = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap,
  455. const ObjectInstanceID & id, const std::optional<SlotID> & creature = std::nullopt)
  456. {
  457. for(const auto & [slot, slotInfo] : artMap)
  458. {
  459. auto artInst = slotInfo.getArt();
  460. assert(artInst);
  461. if(const auto condition = artInst->getType()->getDischargeCondition(); condition == DischargeArtifactCondition::BATTLE)
  462. {
  463. auto & discharging = resultsApplied.dischargingArtifacts.emplace_back(artInst->getId(), 1);
  464. discharging.artLoc.emplace(id, creature, slot);
  465. }
  466. }
  467. };
  468. if(winnerHero)
  469. {
  470. addArtifactToDischarging(winnerHero->artifactsWorn, winnerHero->id);
  471. if(const auto commander = winnerHero->getCommander())
  472. addArtifactToDischarging(commander->artifactsWorn, winnerHero->id, winnerHero->findStack(winnerHero->getCommander()));
  473. }
  474. if(loserHero)
  475. {
  476. addArtifactToDischarging(loserHero->artifactsWorn, loserHero->id);
  477. if(const auto commander = loserHero->getCommander())
  478. addArtifactToDischarging(commander->artifactsWorn, loserHero->id, loserHero->findStack(loserHero->getCommander()));
  479. }
  480. // Necromancy handling
  481. // Give raised units to winner, if any were raised, units will be given after casualties are taken
  482. if(winnerHero)
  483. {
  484. resultsApplied.raisedStack = winnerHero->calculateNecromancy(result);
  485. const SlotID necroSlot = resultsApplied.raisedStack.getCreature() ? winnerHero->getSlotFor(resultsApplied.raisedStack.getCreature()) : SlotID();
  486. if(necroSlot != SlotID() && !finishingBattle->isDraw())
  487. gameHandler->addToSlot(StackLocation(finishingBattle->winnerId, necroSlot), resultsApplied.raisedStack.getCreature(), resultsApplied.raisedStack.getCount());
  488. }
  489. resultsApplied.battleID = battleID;
  490. resultsApplied.victor = finishingBattle->victor;
  491. resultsApplied.loser = finishingBattle->loser;
  492. gameHandler->sendAndApply(resultsApplied);
  493. // Remove beaten hero
  494. if(loserHero)
  495. {
  496. RemoveObject ro(loserHero->id, finishingBattle->victor);
  497. gameHandler->sendAndApply(ro);
  498. }
  499. // For draw case both heroes should be removed
  500. if(finishingBattle->isDraw())
  501. {
  502. if (attackerHero)
  503. {
  504. RemoveObject ro(attackerHero->id, defenderSide);
  505. gameHandler->sendAndApply(ro);
  506. }
  507. if (defenderHero)
  508. {
  509. RemoveObject ro(defenderHero->id, attackerSide);
  510. gameHandler->sendAndApply(ro);
  511. }
  512. if(gameHandler->gameInfo().getSettings().getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  513. {
  514. if (attackerHero)
  515. gameHandler->heroPool->onHeroEscaped(attackerSide, attackerHero);
  516. if (defenderHero)
  517. gameHandler->heroPool->onHeroEscaped(defenderSide, defenderHero);
  518. }
  519. }
  520. //handle victory/loss of engaged players
  521. gameHandler->checkVictoryLossConditions({finishingBattle->loser, finishingBattle->victor});
  522. if (result.result == EBattleResult::SURRENDER)
  523. {
  524. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroSurrendered++;
  525. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, loserHero);
  526. }
  527. if (result.result == EBattleResult::ESCAPE)
  528. {
  529. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroEscaped++;
  530. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, loserHero);
  531. }
  532. finishingBattles.erase(battleID);
  533. battleResults.erase(battleID);
  534. }
  535. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, BattleSide victoriusSide)
  536. {
  537. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  538. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  539. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  540. battleResult->battleID = battle.getBattle()->getBattleID();
  541. battleResult->result = resultType;
  542. battleResult->winner = victoriusSide; //surrendering side loses
  543. battleResult->attacker = battle.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  544. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  545. if (stack->summoned)//don't take into account temporary summoned stacks
  546. return false;
  547. if (stack->isTurret())
  548. return false;
  549. return true;
  550. });
  551. for(const auto & st : allStacks) //setting casualties
  552. {
  553. si32 killed = st->getKilled();
  554. if(killed > 0)
  555. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  556. }
  557. }
  558. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  559. {
  560. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  561. }