BattleResultProcessor.cpp 26 KB

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