BattleResultProcessor.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 "../CGameHandler.h"
  13. #include "../processors/HeroPoolProcessor.h"
  14. #include "../queries/QueriesProcessor.h"
  15. #include "../queries/BattleQueries.h"
  16. #include "../../lib/ArtifactUtils.h"
  17. #include "../../lib/CStack.h"
  18. #include "../../lib/GameSettings.h"
  19. #include "../../lib/battle/CBattleInfoCallback.h"
  20. #include "../../lib/battle/IBattleState.h"
  21. #include "../../lib/battle/SideInBattle.h"
  22. #include "../../lib/gameState/CGameState.h"
  23. #include "../../lib/mapObjects/CGTownInstance.h"
  24. #include "../../lib/serializer/Cast.h"
  25. #include "../../lib/spells/CSpellHandler.h"
  26. BattleResultProcessor::BattleResultProcessor(BattleProcessor * owner)
  27. // : owner(owner)
  28. : gameHandler(nullptr)
  29. {
  30. }
  31. void BattleResultProcessor::setGameHandler(CGameHandler * newGameHandler)
  32. {
  33. gameHandler = newGameHandler;
  34. }
  35. CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle, uint8_t sideInBattle):
  36. army(battle.battleGetArmyObject(sideInBattle))
  37. {
  38. heroWithDeadCommander = ObjectInstanceID();
  39. PlayerColor color = battle.sideToPlayer(sideInBattle);
  40. for(const CStack * stConst : battle.battleGetAllStacks(true))
  41. {
  42. // Use const cast - in order to call non-const "takeResurrected" for proper calculation of casualties
  43. // TODO: better solution
  44. CStack * st = const_cast<CStack*>(stConst);
  45. if(st->summoned) //don't take into account temporary summoned stacks
  46. continue;
  47. if(st->unitOwner() != color) //remove only our stacks
  48. continue;
  49. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  50. st->health.takeResurrected();
  51. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  52. {
  53. logGlobal->debug("Ignored arrow towers stack.");
  54. }
  55. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  56. {
  57. auto warMachine = st->unitType()->warMachine;
  58. if(warMachine == ArtifactID::NONE)
  59. {
  60. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  61. }
  62. //catapult artifact remain even if "creature" killed in siege
  63. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  64. {
  65. logGlobal->debug("War machine has been destroyed");
  66. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  67. if (hero)
  68. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  69. else
  70. logGlobal->error("War machine in army without hero");
  71. }
  72. }
  73. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  74. {
  75. if(st->alive() && st->getCount() > 0)
  76. {
  77. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  78. const CreatureID summonedType = st->creatureId();
  79. summoned[summonedType] += st->getCount();
  80. }
  81. }
  82. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  83. {
  84. if (nullptr == st->base)
  85. {
  86. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  87. }
  88. else
  89. {
  90. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  91. if(c)
  92. {
  93. auto h = dynamic_cast <const CGHeroInstance *>(army);
  94. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  95. {
  96. logGlobal->debug("Commander is dead.");
  97. heroWithDeadCommander = army->id; //TODO: unify commander handling
  98. }
  99. }
  100. else
  101. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  102. }
  103. }
  104. else if(st->base && !army->slotEmpty(st->unitSlot()))
  105. {
  106. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  107. if(st->getCount() == 0 || !st->alive())
  108. {
  109. logGlobal->debug("Stack has been destroyed.");
  110. StackLocation sl(army, st->unitSlot());
  111. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  112. }
  113. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  114. {
  115. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  116. StackLocation sl(army, st->unitSlot());
  117. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  118. }
  119. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  120. {
  121. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  122. StackLocation sl(army, st->unitSlot());
  123. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  124. }
  125. }
  126. else
  127. {
  128. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  129. }
  130. }
  131. }
  132. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  133. {
  134. for (TStackAndItsNewCount &ncount : newStackCounts)
  135. {
  136. if (ncount.second > 0)
  137. gh->changeStackCount(ncount.first, ncount.second, true);
  138. else
  139. gh->eraseStack(ncount.first, true);
  140. }
  141. for (auto summoned_iter : summoned)
  142. {
  143. SlotID slot = army->getSlotFor(summoned_iter.first);
  144. if (slot.validSlot())
  145. {
  146. StackLocation location(army, slot);
  147. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  148. }
  149. else
  150. {
  151. //even if it will be possible to summon anything permanently it should be checked for free slot
  152. //necromancy is handled separately
  153. gh->complain("No free slot to put summoned creature");
  154. }
  155. }
  156. for (auto al : removedWarMachines)
  157. {
  158. gh->removeArtifact(al);
  159. }
  160. if (heroWithDeadCommander != ObjectInstanceID())
  161. {
  162. SetCommanderProperty scp;
  163. scp.heroid = heroWithDeadCommander;
  164. scp.which = SetCommanderProperty::ALIVE;
  165. scp.amount = 0;
  166. gh->sendAndApply(&scp);
  167. }
  168. }
  169. FinishingBattleHelper::FinishingBattleHelper(const CBattleInfoCallback & info, const BattleResult & result, int remainingBattleQueriesCount)
  170. {
  171. if (result.winner == BattleSide::ATTACKER)
  172. {
  173. winnerHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  174. loserHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  175. victor = info.getBattle()->getSidePlayer(BattleSide::ATTACKER);
  176. loser = info.getBattle()->getSidePlayer(BattleSide::DEFENDER);
  177. }
  178. else
  179. {
  180. winnerHero = info.getBattle()->getSideHero(BattleSide::DEFENDER);
  181. loserHero = info.getBattle()->getSideHero(BattleSide::ATTACKER);
  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. //FinishingBattleHelper::FinishingBattleHelper()
  189. //{
  190. // winnerHero = loserHero = nullptr;
  191. // winnerSide = 0;
  192. // remainingBattleQueriesCount = 0;
  193. //}
  194. void BattleResultProcessor::endBattle(const CBattleInfoCallback & battle)
  195. {
  196. auto const & giveExp = [](BattleResult &r)
  197. {
  198. if (r.winner > 1)
  199. {
  200. // draw
  201. return;
  202. }
  203. r.exp[0] = 0;
  204. r.exp[1] = 0;
  205. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  206. {
  207. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  208. }
  209. };
  210. LOG_TRACE(logGlobal);
  211. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  212. const auto * heroAttacker = battle.battleGetFightingHero(BattleSide::ATTACKER);
  213. const auto * heroDefender = battle.battleGetFightingHero(BattleSide::DEFENDER);
  214. //Fill BattleResult structure with exp info
  215. giveExp(*battleResult);
  216. if (battleResult->result == EBattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  217. {
  218. if(heroAttacker)
  219. battleResult->exp[1] += 500;
  220. if(heroDefender)
  221. battleResult->exp[0] += 500;
  222. }
  223. // Give 500 exp to winner if a town was conquered during the battle
  224. const auto * defendedTown = battle.battleGetDefendedTown();
  225. if (defendedTown && battleResult->winner == BattleSide::ATTACKER)
  226. battleResult->exp[BattleSide::ATTACKER] += 500;
  227. if(heroAttacker)
  228. battleResult->exp[0] = heroAttacker->calculateXp(battleResult->exp[0]);//scholar skill
  229. if(heroDefender)
  230. battleResult->exp[1] = heroDefender->calculateXp(battleResult->exp[1]);
  231. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  232. if (!battleQuery)
  233. {
  234. logGlobal->error("Cannot find battle query!");
  235. gameHandler->complain("Player " + boost::lexical_cast<std::string>(battle.sideToPlayer(0)) + " has no battle query at the top!");
  236. return;
  237. }
  238. battleQuery->result = std::make_optional(*battleResult);
  239. //Check how many battle gameHandler->queries were created (number of players blocked by battle)
  240. const int queriedPlayers = battleQuery ? (int)boost::count(gameHandler->queries->allQueries(), battleQuery) : 0;
  241. assert(finishingBattles.count(battle.getBattle()->getBattleID()) == 0);
  242. finishingBattles[battle.getBattle()->getBattleID()] = std::make_unique<FinishingBattleHelper>(battle, *battleResult, queriedPlayers);
  243. // in battles against neutrals, 1st player can ask to replay battle manually
  244. if (!battle.sideToPlayer(1).isValidPlayer())
  245. {
  246. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, battle.getBattle());
  247. battleResult->queryID = battleDialogQuery->queryID;
  248. gameHandler->queries->addQuery(battleDialogQuery);
  249. }
  250. else
  251. battleResult->queryID = -1;
  252. //set same battle result for all gameHandler->queries
  253. for(auto q : gameHandler->queries->allQueries())
  254. {
  255. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  256. if(otherBattleQuery && otherBattleQuery->battleID == battle.getBattle()->getBattleID())
  257. otherBattleQuery->result = battleQuery->result;
  258. }
  259. gameHandler->turnTimerHandler.onBattleEnd(battle.getBattle()->getBattleID());
  260. gameHandler->sendAndApply(battleResult);
  261. if (battleResult->queryID == QueryID::NONE)
  262. endBattleConfirm(battle);
  263. }
  264. void BattleResultProcessor::endBattleConfirm(const CBattleInfoCallback & battle)
  265. {
  266. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battle.sideToPlayer(0)));
  267. if(!battleQuery)
  268. {
  269. logGlobal->trace("No battle query, battle end was confirmed by another player");
  270. return;
  271. }
  272. auto * battleResult = battleResults.at(battle.getBattle()->getBattleID()).get();
  273. auto * finishingBattle = finishingBattles.at(battle.getBattle()->getBattleID()).get();
  274. const EBattleResult result = battleResult->result;
  275. //calculate casualties before deleting battle
  276. CasualtiesAfterBattle cab1(battle, BattleSide::ATTACKER);
  277. CasualtiesAfterBattle cab2(battle, BattleSide::DEFENDER);
  278. ChangeSpells cs; //for Eagle Eye
  279. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  280. {
  281. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  282. {
  283. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  284. for(auto & spellId : battle.getBattle()->getUsedSpells(battle.otherSide(battleResult->winner)))
  285. {
  286. auto spell = spellId.toSpell(VLC->spells());
  287. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && gameHandler->getRandomGenerator().nextInt(99) < eagleEyeChance)
  288. cs.spells.insert(spell->getId());
  289. }
  290. }
  291. }
  292. std::vector<const CArtifactInstance *> arts; //display them in window
  293. if(result == EBattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  294. {
  295. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  296. {
  297. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  298. if(slot != ArtifactPosition::PRE_FIRST)
  299. {
  300. arts.push_back(art);
  301. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  302. if(ArtifactUtils::isSlotBackpack(slot))
  303. ma->askAssemble = false;
  304. gameHandler->sendAndApply(ma);
  305. }
  306. };
  307. if (finishingBattle->loserHero)
  308. {
  309. //TODO: wrap it into a function, somehow (std::variant -_-)
  310. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  311. for (auto artSlot : artifactsWorn)
  312. {
  313. MoveArtifact ma;
  314. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  315. const CArtifactInstance * art = ma.src.getArt();
  316. if (art && !art->artType->isBig() &&
  317. art->artType->getId() != ArtifactID::SPELLBOOK)
  318. // don't move war machines or locked arts (spellbook)
  319. {
  320. sendMoveArtifact(art, &ma);
  321. }
  322. }
  323. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  324. {
  325. //we assume that no big artifacts can be found
  326. MoveArtifact ma;
  327. ma.src = ArtifactLocation(finishingBattle->loserHero,
  328. ArtifactPosition(ArtifactPosition::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  329. const CArtifactInstance * art = ma.src.getArt();
  330. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  331. {
  332. sendMoveArtifact(art, &ma);
  333. }
  334. }
  335. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  336. {
  337. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  338. for (auto artSlot : artifactsWorn)
  339. {
  340. MoveArtifact ma;
  341. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  342. const CArtifactInstance * art = ma.src.getArt();
  343. if (art && !art->artType->isBig())
  344. {
  345. sendMoveArtifact(art, &ma);
  346. }
  347. }
  348. }
  349. }
  350. auto loser = battle.otherSide(battleResult->winner);
  351. for (auto armySlot : battle.battleGetArmyObject(loser)->stacks)
  352. {
  353. auto artifactsWorn = armySlot.second->artifactsWorn;
  354. for (auto artSlot : artifactsWorn)
  355. {
  356. MoveArtifact ma;
  357. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  358. const CArtifactInstance * art = ma.src.getArt();
  359. if (art && !art->artType->isBig())
  360. {
  361. sendMoveArtifact(art, &ma);
  362. }
  363. }
  364. }
  365. }
  366. if (arts.size()) //display loot
  367. {
  368. InfoWindow iw;
  369. iw.player = finishingBattle->winnerHero->tempOwner;
  370. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  371. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  372. {
  373. iw.components.emplace_back(
  374. Component::EComponentType::ARTIFACT, art->artType->getId(),
  375. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : SpellID(0), 0);
  376. if (iw.components.size() >= 14)
  377. {
  378. gameHandler->sendAndApply(&iw);
  379. iw.components.clear();
  380. }
  381. }
  382. if (iw.components.size())
  383. {
  384. gameHandler->sendAndApply(&iw);
  385. }
  386. }
  387. //Eagle Eye secondary skill handling
  388. if (!cs.spells.empty())
  389. {
  390. cs.learn = 1;
  391. cs.hid = finishingBattle->winnerHero->id;
  392. InfoWindow iw;
  393. iw.player = finishingBattle->winnerHero->tempOwner;
  394. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  395. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  396. std::ostringstream names;
  397. for (int i = 0; i < cs.spells.size(); i++)
  398. {
  399. names << "%s";
  400. if (i < cs.spells.size() - 2)
  401. names << ", ";
  402. else if (i < cs.spells.size() - 1)
  403. names << "%s";
  404. }
  405. names << ".";
  406. iw.text.replaceRawString(names.str());
  407. auto it = cs.spells.begin();
  408. for (int i = 0; i < cs.spells.size(); i++, it++)
  409. {
  410. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  411. if (i == cs.spells.size() - 2) //we just added pre-last name
  412. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  413. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  414. }
  415. gameHandler->sendAndApply(&iw);
  416. gameHandler->sendAndApply(&cs);
  417. }
  418. cab1.updateArmy(gameHandler);
  419. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  420. if(finishingBattle->loserHero) //remove beaten hero
  421. {
  422. RemoveObject ro(finishingBattle->loserHero->id, battle.battleGetArmyObject(0)->getOwner());
  423. gameHandler->sendAndApply(&ro);
  424. }
  425. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  426. {
  427. RemoveObject ro(finishingBattle->winnerHero->id, battle.battleGetArmyObject(0)->getOwner());
  428. gameHandler->sendAndApply(&ro);
  429. }
  430. if(battleResult->winner == BattleSide::DEFENDER
  431. && finishingBattle->winnerHero
  432. && finishingBattle->winnerHero->visitedTown
  433. && !finishingBattle->winnerHero->inTownGarrison
  434. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  435. {
  436. gameHandler->swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  437. }
  438. //give exp
  439. if(!finishingBattle->isDraw() && battleResult->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  440. gameHandler->changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult->exp[finishingBattle->winnerSide]);
  441. BattleResultAccepted raccepted;
  442. raccepted.battleID = battle.getBattle()->getBattleID();
  443. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(0));
  444. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battle.battleGetArmyObject(1));
  445. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(0));
  446. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battle.battleGetFightingHero(1));
  447. raccepted.heroResult[0].exp = battleResult->exp[0];
  448. raccepted.heroResult[1].exp = battleResult->exp[1];
  449. raccepted.winnerSide = finishingBattle->winnerSide;
  450. gameHandler->sendAndApply(&raccepted);
  451. gameHandler->queries->popIfTop(battleQuery);
  452. //--> continuation (battleAfterLevelUp) occurs after level-up gameHandler->queries are handled or on removing query
  453. }
  454. void BattleResultProcessor::battleAfterLevelUp(const BattleID & battleID, const BattleResult & result)
  455. {
  456. LOG_TRACE(logGlobal);
  457. assert(finishingBattles.count(battleID) != 0);
  458. if(finishingBattles.count(battleID) == 0)
  459. return;
  460. auto & finishingBattle = finishingBattles[battleID];
  461. finishingBattle->remainingBattleQueriesCount--;
  462. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  463. if (finishingBattle->remainingBattleQueriesCount > 0)
  464. //Battle results will be handled when all battle gameHandler->queries are closed
  465. return;
  466. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  467. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  468. // Still, it looks like a hole.
  469. // Necromancy if applicable.
  470. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(result) : CStackBasicDescriptor();
  471. // Give raised units to winner and show dialog, if any were raised,
  472. // units will be given after casualties are taken
  473. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  474. if (necroSlot != SlotID())
  475. {
  476. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, gameHandler->getRandomGenerator());
  477. gameHandler->addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  478. }
  479. BattleResultsApplied resultsApplied;
  480. resultsApplied.battleID = battleID;
  481. resultsApplied.player1 = finishingBattle->victor;
  482. resultsApplied.player2 = finishingBattle->loser;
  483. gameHandler->sendAndApply(&resultsApplied);
  484. //handle victory/loss of engaged players
  485. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  486. gameHandler->checkVictoryLossConditions(playerColors);
  487. if (result.result == EBattleResult::SURRENDER)
  488. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  489. if (result.result == EBattleResult::ESCAPE)
  490. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  491. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  492. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  493. {
  494. RemoveObject ro(finishingBattle->winnerHero->id, finishingBattle->winnerHero->getOwner());
  495. gameHandler->sendAndApply(&ro);
  496. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  497. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  498. }
  499. finishingBattles.erase(battleID);
  500. battleResults.erase(battleID);
  501. }
  502. void BattleResultProcessor::setBattleResult(const CBattleInfoCallback & battle, EBattleResult resultType, int victoriusSide)
  503. {
  504. assert(battleResults.count(battle.getBattle()->getBattleID()) == 0);
  505. battleResults[battle.getBattle()->getBattleID()] = std::make_unique<BattleResult>();
  506. auto & battleResult = battleResults[battle.getBattle()->getBattleID()];
  507. battleResult->battleID = battle.getBattle()->getBattleID();
  508. battleResult->result = resultType;
  509. battleResult->winner = victoriusSide; //surrendering side loses
  510. for(const auto & st : battle.battleGetAllStacks(true)) //setting casualties
  511. {
  512. si32 killed = st->getKilled();
  513. if(killed > 0)
  514. battleResult->casualties[st->unitSide()][st->creatureId()] += killed;
  515. }
  516. }
  517. bool BattleResultProcessor::battleIsEnding(const CBattleInfoCallback & battle) const
  518. {
  519. return battleResults.count(battle.getBattle()->getBattleID()) != 0;
  520. }