BattleResultProcessor.cpp 21 KB

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