BattleResultProcessor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. bool winnerHasUnitsLeft = true;
  358. if (!finishingBattle->isDraw())
  359. {
  360. winnerHero = (*battle)->battleGetFightingHero(finishingBattle->winnerSide);
  361. loserHero = (*battle)->battleGetFightingHero(CBattleInfoEssentials::otherSide(finishingBattle->winnerSide));
  362. winnerHasUnitsLeft = winnerHero ? winnerHero->stacksCount() > 0 : true;
  363. }
  364. BattleResultsApplied resultsApplied;
  365. const auto addArtifactToDischarging = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap,
  366. const ObjectInstanceID & id, const std::optional<SlotID> & creature = std::nullopt)
  367. {
  368. for(const auto & [slot, slotInfo] : artMap)
  369. {
  370. auto artInst = slotInfo.getArt();
  371. assert(artInst);
  372. if(const auto condition = artInst->getType()->getDischargeCondition(); condition == DischargeArtifactCondition::BATTLE)
  373. {
  374. auto & discharging = resultsApplied.dischargingArtifacts.emplace_back(artInst->getId(), 1);
  375. discharging.artLoc.emplace(id, creature, slot);
  376. }
  377. }
  378. };
  379. if(winnerHero && winnerHasUnitsLeft)
  380. {
  381. // Eagle Eye handling
  382. if(auto eagleEyeLevel = winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT))
  383. {
  384. resultsApplied.learnedSpells.learn = 1;
  385. resultsApplied.learnedSpells.hid = finishingBattle->winnerId;
  386. for(const auto & spellId : (*battle)->getUsedSpells(CBattleInfoEssentials::otherSide(result.winner)))
  387. {
  388. const auto spell = spellId.toEntity(LIBRARY->spells());
  389. if(spell
  390. && spell->getLevel() <= eagleEyeLevel
  391. && !winnerHero->spellbookContainsSpell(spell->getId())
  392. && gameHandler->getRandomGenerator().nextInt(99) < winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE))
  393. {
  394. resultsApplied.learnedSpells.spells.insert(spell->getId());
  395. }
  396. }
  397. }
  398. // Growing artifacts handling
  399. const auto addArtifactToGrowing = [&resultsApplied](const std::map<ArtifactPosition, ArtSlotInfo> & artMap)
  400. {
  401. for(const auto & [slot, slotInfo] : artMap)
  402. {
  403. const auto artInst = slotInfo.getArt();
  404. assert(artInst);
  405. if(artInst->getType()->isGrowing())
  406. resultsApplied.growingArtifacts.emplace_back(artInst->getId());
  407. }
  408. };
  409. if(const auto commander = winnerHero->getCommander(); commander && commander->alive)
  410. addArtifactToGrowing(commander->artifactsWorn);
  411. addArtifactToGrowing(winnerHero->artifactsWorn);
  412. // Charged artifacts handling
  413. addArtifactToDischarging(winnerHero->artifactsWorn, winnerHero->id);
  414. if(const auto commander = winnerHero->getCommander())
  415. addArtifactToDischarging(commander->artifactsWorn, winnerHero->id, winnerHero->findStack(winnerHero->getCommander()));
  416. // Necromancy handling
  417. // Give raised units to winner, if any were raised, units will be given after casualties are taken
  418. resultsApplied.raisedStack = winnerHero->calculateNecromancy(result);
  419. const SlotID necroSlot = resultsApplied.raisedStack.getCreature() ? winnerHero->getSlotFor(resultsApplied.raisedStack.getCreature()) : SlotID();
  420. if(necroSlot != SlotID() && !finishingBattle->isDraw())
  421. gameHandler->addToSlot(StackLocation(finishingBattle->winnerId, necroSlot), resultsApplied.raisedStack.getCreature(), resultsApplied.raisedStack.getCount());
  422. }
  423. if(loserHero)
  424. {
  425. // Charged artifacts handling
  426. addArtifactToDischarging(loserHero->artifactsWorn, loserHero->id);
  427. if(const auto commander = loserHero->getCommander())
  428. addArtifactToDischarging(commander->artifactsWorn, loserHero->id, loserHero->findStack(loserHero->getCommander()));
  429. }
  430. // Moving artifacts handling
  431. if(result.result == EBattleResult::NORMAL && winnerHero && winnerHasUnitsLeft)
  432. {
  433. CArtifactFittingSet artFittingSet(*winnerHero);
  434. const auto addArtifactToTransfer = [&artFittingSet](BulkMoveArtifacts & pack, const ArtifactPosition & srcSlot, const CArtifactInstance * art)
  435. {
  436. assert(art);
  437. const auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, art->getTypeId());
  438. if(dstSlot != ArtifactPosition::PRE_FIRST)
  439. {
  440. pack.artsPack0.emplace_back(MoveArtifactInfo(srcSlot, dstSlot));
  441. if(ArtifactUtils::isSlotEquipment(dstSlot))
  442. pack.artsPack0.back().askAssemble = true;
  443. artFittingSet.putArtifact(dstSlot, art);
  444. }
  445. };
  446. if (loserHero)
  447. {
  448. BulkMoveArtifacts packHero(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  449. packHero.srcArtHolder = finishingBattle->loserId;
  450. for(const auto & slot : ArtifactUtils::commonWornSlots())
  451. {
  452. if(const auto artSlot = loserHero->artifactsWorn.find(slot); artSlot != loserHero->artifactsWorn.end() && ArtifactUtils::isArtRemovable(*artSlot))
  453. {
  454. addArtifactToTransfer(packHero, artSlot->first, artSlot->second.getArt());
  455. }
  456. }
  457. for(const auto & artSlot : loserHero->artifactsInBackpack)
  458. {
  459. if(const auto art = artSlot.getArt(); art->getTypeId() != ArtifactID::GRAIL)
  460. addArtifactToTransfer(packHero, loserHero->getArtPos(art), art);
  461. }
  462. if(!packHero.artsPack0.empty())
  463. resultsApplied.movingArtifacts.emplace_back(std::move(packHero));
  464. if(loserHero->getCommander())
  465. {
  466. BulkMoveArtifacts packCommander(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  467. packCommander.srcCreature = loserHero->findStack(loserHero->getCommander());
  468. for(const auto & artSlot : loserHero->getCommander()->artifactsWorn)
  469. addArtifactToTransfer(packCommander, artSlot.first, artSlot.second.getArt());
  470. if(!packCommander.artsPack0.empty())
  471. resultsApplied.movingArtifacts.emplace_back(std::move(packCommander));
  472. }
  473. auto armyObj = dynamic_cast<const CArmedInstance*>(gameHandler->gameInfo().getObj(finishingBattle->loserId));
  474. for(const auto & armySlot : armyObj->stacks)
  475. {
  476. BulkMoveArtifacts packArmy(finishingBattle->victor, finishingBattle->loserId, finishingBattle->winnerId, false);
  477. packArmy.srcArtHolder = armyObj->id;
  478. packArmy.srcCreature = armySlot.first;
  479. for(const auto & artSlot : armySlot.second->artifactsWorn)
  480. addArtifactToTransfer(packArmy, artSlot.first, armySlot.second->getArt(artSlot.first));
  481. if(!packArmy.artsPack0.empty())
  482. resultsApplied.movingArtifacts.emplace_back(std::move(packArmy));
  483. }
  484. }
  485. }
  486. resultsApplied.battleID = battleID;
  487. resultsApplied.victor = finishingBattle->victor;
  488. resultsApplied.loser = finishingBattle->loser;
  489. gameHandler->sendAndApply(resultsApplied);
  490. // Remove beaten hero
  491. if(loserHero)
  492. {
  493. RemoveObject ro(loserHero->id, finishingBattle->victor);
  494. gameHandler->sendAndApply(ro);
  495. }
  496. //retreat the victor if he/she has no pernament creatures left
  497. if (winnerHero && !winnerHasUnitsLeft)
  498. {
  499. RemoveObject ro(winnerHero->id, finishingBattle->loser);
  500. gameHandler->sendAndApply(ro);
  501. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, winnerHero);
  502. }
  503. // For draw case both heroes should be removed
  504. if(finishingBattle->isDraw())
  505. {
  506. if (attackerHero)
  507. {
  508. RemoveObject ro(attackerHero->id, defenderSide);
  509. gameHandler->sendAndApply(ro);
  510. }
  511. if (defenderHero)
  512. {
  513. RemoveObject ro(defenderHero->id, attackerSide);
  514. gameHandler->sendAndApply(ro);
  515. }
  516. if(gameHandler->gameInfo().getSettings().getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  517. {
  518. if (attackerHero)
  519. gameHandler->heroPool->onHeroEscaped(attackerSide, attackerHero);
  520. if (defenderHero)
  521. gameHandler->heroPool->onHeroEscaped(defenderSide, defenderHero);
  522. }
  523. }
  524. if (result.result == EBattleResult::SURRENDER)
  525. {
  526. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroSurrendered++;
  527. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, loserHero);
  528. }
  529. if (result.result == EBattleResult::ESCAPE)
  530. {
  531. gameHandler->statistics->accumulatedValues[finishingBattle->loser].numHeroEscaped++;
  532. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, loserHero);
  533. }
  534. //handle victory/loss of engaged players
  535. gameHandler->checkVictoryLossConditions({finishingBattle->loser, finishingBattle->victor});
  536. finishingBattles.erase(battleID);
  537. battleResults.erase(battleID);
  538. }
  539. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, BattleSide victoriusSide)
  540. {
  541. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  542. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  543. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  544. battleResult->battleID = battle.getBattle()->getBattleID();
  545. battleResult->result = resultType;
  546. battleResult->winner = victoriusSide; //surrendering side loses
  547. battleResult->attacker = battle.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  548. auto allStacks = battle.battleGetStacksIf([](const CStack * stack){
  549. if (stack->summoned)//don't take into account temporary summoned stacks
  550. return false;
  551. if (stack->isTurret())
  552. return false;
  553. return true;
  554. });
  555. for(const auto & st : allStacks) //setting casualties
  556. {
  557. si32 killed = st->getKilled();
  558. if(killed > 0)
  559. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  560. }
  561. }
  562. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  563. {
  564. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  565. }