BattleFlowProcessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. /*
  2. * BattleFlowProcessor.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 "BattleFlowProcessor.h"
  12. #include "BattleProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../CVCMIServer.h"
  15. #include "../processors/HeroPoolProcessor.h"
  16. #include "../queries/QueriesProcessor.h"
  17. #include "../queries/BattleQueries.h"
  18. #include "../../lib/ArtifactUtils.h"
  19. #include "../../lib/CGeneralTextHandler.h"
  20. #include "../../lib/CStack.h"
  21. #include "../../lib/CondSh.h"
  22. #include "../../lib/GameSettings.h"
  23. #include "../../lib/ScopeGuard.h"
  24. #include "../../lib/TerrainHandler.h"
  25. #include "../../lib/UnlockGuard.h"
  26. #include "../../lib/battle/BattleInfo.h"
  27. #include "../../lib/battle/CUnitState.h"
  28. #include "../../lib/gameState/CGameState.h"
  29. #include "../../lib/mapObjects/CGTownInstance.h"
  30. #include "../../lib/mapping/CMap.h"
  31. #include "../../lib/modding/IdentifierStorage.h"
  32. #include "../../lib/serializer/Cast.h"
  33. #include "../../lib/spells/AbilityCaster.h"
  34. #include "../../lib/spells/BonusCaster.h"
  35. #include "../../lib/spells/CSpellHandler.h"
  36. #include "../../lib/spells/ISpellMechanics.h"
  37. #include "../../lib/spells/ObstacleCasterProxy.h"
  38. #include "../../lib/spells/Problem.h"
  39. BattleFlowProcessor::BattleFlowProcessor(BattleProcessor * owner)
  40. : owner(owner)
  41. , gameHandler(nullptr)
  42. {
  43. }
  44. void BattleFlowProcessor::setGameHandler(CGameHandler * newGameHandler)
  45. {
  46. gameHandler = newGameHandler;
  47. }
  48. void BattleFlowProcessor::summonGuardiansHelper(std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  49. {
  50. int x = targetPosition.getX();
  51. int y = targetPosition.getY();
  52. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  53. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  54. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  55. else
  56. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  57. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  58. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  59. {
  60. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  61. {
  62. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  63. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  64. }
  65. else
  66. { //add back-side guardians for two-hex target, side guardians for one-hex
  67. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  68. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  69. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  70. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  71. else if (targetIsTwoHex)//front-side guardians for two-hex target
  72. {
  73. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  74. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  75. if (x > 3) //back guard for two-hex
  76. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  77. }
  78. }
  79. }
  80. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  81. {
  82. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  83. {
  84. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  85. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  86. }
  87. else
  88. {
  89. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  90. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  91. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  92. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  93. else if (targetIsTwoHex)
  94. {
  95. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  96. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  97. if (x < GameConstants::BFIELD_WIDTH - 4)
  98. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  99. }
  100. }
  101. }
  102. else if (!targetIsAttacker && y % 2 == 0)
  103. {
  104. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  105. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  106. }
  107. else if (targetIsAttacker && y % 2 == 1)
  108. {
  109. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  110. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  111. }
  112. }
  113. void BattleFlowProcessor::tryPlaceMoats()
  114. {
  115. //Moat should be initialized here, because only here we can use spellcasting
  116. if (gameHandler->gameState()->curB->town && gameHandler->gameState()->curB->town->fortLevel() >= CGTownInstance::CITADEL)
  117. {
  118. const auto * h = gameHandler->gameState()->curB->battleGetFightingHero(BattleSide::DEFENDER);
  119. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  120. auto moatCaster = spells::SilentCaster(gameHandler->gameState()->curB->getSidePlayer(BattleSide::DEFENDER), actualCaster);
  121. auto cast = spells::BattleCast(gameHandler->gameState()->curB, &moatCaster, spells::Mode::PASSIVE, gameHandler->gameState()->curB->town->town->moatAbility.toSpell());
  122. auto target = spells::Target();
  123. cast.cast(gameHandler->spellEnv, target);
  124. }
  125. }
  126. void BattleFlowProcessor::onBattleStarted()
  127. {
  128. gameHandler->setBattle(gameHandler->gameState()->curB);
  129. assert(gameHandler->gameState()->curB);
  130. tryPlaceMoats();
  131. if (gameHandler->gameState()->curB->tacticDistance == 0)
  132. onTacticsEnded();
  133. }
  134. void BattleFlowProcessor::trySummonGuardians(const CStack * stack)
  135. {
  136. if (!stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  137. return;
  138. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  139. auto accessibility = gameHandler->getAccesibility();
  140. CreatureID creatureData = CreatureID(summonInfo->subtype);
  141. std::vector<BattleHex> targetHexes;
  142. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  143. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  144. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  145. For one-hex targets there are four guardians - front, back and one per side (up + down).
  146. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  147. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  148. if (!guardianIsBig)
  149. targetHexes = stack->getSurroundingHexes();
  150. else
  151. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  152. for(auto hex : targetHexes)
  153. {
  154. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  155. {
  156. battle::UnitInfo info;
  157. info.id = gameHandler->gameState()->curB->battleNextUnitId();
  158. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  159. info.type = creatureData;
  160. info.side = stack->unitSide();
  161. info.position = hex;
  162. info.summoned = true;
  163. BattleUnitsChanged pack;
  164. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  165. info.save(pack.changedStacks.back().data);
  166. gameHandler->sendAndApply(&pack);
  167. }
  168. }
  169. }
  170. void BattleFlowProcessor::castOpeningSpells()
  171. {
  172. for (int i = 0; i < 2; ++i)
  173. {
  174. auto h = gameHandler->gameState()->curB->battleGetFightingHero(i);
  175. if (!h)
  176. continue;
  177. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  178. for (auto b : *bl)
  179. {
  180. spells::BonusCaster caster(h, b);
  181. const CSpell * spell = SpellID(b->subtype).toSpell();
  182. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  183. parameters.setSpellLevel(3);
  184. parameters.setEffectDuration(b->val);
  185. parameters.massive = true;
  186. parameters.castIfPossible(gameHandler->spellEnv, spells::Target());
  187. }
  188. }
  189. }
  190. void BattleFlowProcessor::onTacticsEnded()
  191. {
  192. //initial stacks appearance triggers, e.g. built-in bonus spells
  193. auto initialStacks = gameHandler->gameState()->curB->stacks; //use temporary variable to outclude summoned stacks added to gameHandler->gameState()->curB->stacks from processing
  194. for (CStack * stack : initialStacks)
  195. {
  196. trySummonGuardians(stack);
  197. stackEnchantedTrigger(stack);
  198. }
  199. castOpeningSpells();
  200. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  201. if (owner->checkBattleStateChanges())
  202. return;
  203. startNextRound(true);
  204. activateNextStack();
  205. }
  206. void BattleFlowProcessor::startNextRound(bool isFirstRound)
  207. {
  208. BattleNextRound bnr;
  209. bnr.round = gameHandler->gameState()->curB->round + 1;
  210. logGlobal->debug("Round %d", bnr.round);
  211. gameHandler->sendAndApply(&bnr);
  212. auto obstacles = gameHandler->gameState()->curB->obstacles; //we copy container, because we're going to modify it
  213. for (auto &obstPtr : obstacles)
  214. {
  215. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  216. if (sco->turnsRemaining == 0)
  217. removeObstacle(*obstPtr);
  218. }
  219. const BattleInfo & curB = *gameHandler->gameState()->curB;
  220. for(auto stack : curB.stacks)
  221. {
  222. if(stack->alive() && !isFirstRound)
  223. stackEnchantedTrigger(stack);
  224. }
  225. }
  226. const CStack * BattleFlowProcessor::getNextStack()
  227. {
  228. std::vector<battle::Units> q;
  229. gameHandler->gameState()->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  230. if(q.empty())
  231. return nullptr;
  232. if(q.front().empty())
  233. return nullptr;
  234. auto next = q.front().front();
  235. const auto stack = dynamic_cast<const CStack *>(next);
  236. // regeneration takes place before everything else but only during first turn attempt in each round
  237. // also works under blind and similar effects
  238. if(stack && stack->alive() && !stack->waiting)
  239. {
  240. BattleTriggerEffect bte;
  241. bte.stackID = stack->unitId();
  242. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  243. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  244. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  245. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  246. if(bte.val) // anything to heal
  247. gameHandler->sendAndApply(&bte);
  248. }
  249. if(!next->willMove())
  250. return nullptr;
  251. return stack;
  252. }
  253. void BattleFlowProcessor::activateNextStack()
  254. {
  255. //TODO: activate next round if next == nullptr
  256. const auto & curB = *gameHandler->gameState()->curB;
  257. // Find next stack that requires manual control
  258. for (;;)
  259. {
  260. // battle has ended
  261. if (owner->checkBattleStateChanges())
  262. return;
  263. const CStack * next = getNextStack();
  264. if (!next)
  265. {
  266. // No stacks to move - start next round
  267. startNextRound(false);
  268. next = getNextStack();
  269. if (!next)
  270. throw std::runtime_error("Failed to find valid stack to act!");
  271. }
  272. BattleUnitsChanged removeGhosts;
  273. for(auto stack : curB.stacks)
  274. {
  275. if(stack->ghostPending)
  276. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  277. }
  278. if(!removeGhosts.changedStacks.empty())
  279. gameHandler->sendAndApply(&removeGhosts);
  280. if (!tryMakeAutomaticAction(next))
  281. {
  282. setActiveStack(next);
  283. break;
  284. }
  285. }
  286. }
  287. bool BattleFlowProcessor::tryMakeAutomaticAction(const CStack * next)
  288. {
  289. const auto & curB = *gameHandler->gameState()->curB;
  290. // check for bad morale => freeze
  291. int nextStackMorale = next->moraleVal();
  292. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  293. {
  294. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  295. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  296. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  297. {
  298. //unit loses its turn - empty freeze action
  299. BattleAction ba;
  300. ba.actionType = EActionType::BAD_MORALE;
  301. ba.side = next->unitSide();
  302. ba.stackNumber = next->unitId();
  303. makeAutomaticAction(next, ba);
  304. return true;
  305. }
  306. }
  307. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  308. {
  309. logGlobal->trace("Handle Berserk effect");
  310. std::pair<const battle::Unit *, BattleHex> attackInfo = curB.getNearestStack(next);
  311. if (attackInfo.first != nullptr)
  312. {
  313. BattleAction attack;
  314. attack.actionType = EActionType::WALK_AND_ATTACK;
  315. attack.side = next->unitSide();
  316. attack.stackNumber = next->unitId();
  317. attack.aimToHex(attackInfo.second);
  318. attack.aimToUnit(attackInfo.first);
  319. makeAutomaticAction(next, attack);
  320. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  321. }
  322. else
  323. {
  324. makeStackDoNothing(next);
  325. logGlobal->trace("No target found");
  326. }
  327. return true;
  328. }
  329. const CGHeroInstance * curOwner = gameHandler->battleGetOwnerHero(next);
  330. const int stackCreatureId = next->unitType()->getId();
  331. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  332. && (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  333. {
  334. BattleAction attack;
  335. attack.actionType = EActionType::SHOOT;
  336. attack.side = next->unitSide();
  337. attack.stackNumber = next->unitId();
  338. //TODO: select target by priority
  339. const battle::Unit * target = nullptr;
  340. for(auto & elem : gameHandler->gameState()->curB->stacks)
  341. {
  342. if(elem->unitType()->getId() != CreatureID::CATAPULT
  343. && elem->unitOwner() != next->unitOwner()
  344. && elem->isValidTarget()
  345. && gameHandler->gameState()->curB->battleCanShoot(next, elem->getPosition()))
  346. {
  347. target = elem;
  348. break;
  349. }
  350. }
  351. if(target == nullptr)
  352. {
  353. makeStackDoNothing(next);
  354. }
  355. else
  356. {
  357. attack.aimToUnit(target);
  358. makeAutomaticAction(next, attack);
  359. }
  360. return true;
  361. }
  362. if (next->unitType()->getId() == CreatureID::CATAPULT)
  363. {
  364. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  365. if (attackableBattleHexes.empty())
  366. {
  367. makeStackDoNothing(next);
  368. return true;
  369. }
  370. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  371. {
  372. BattleAction attack;
  373. attack.actionType = EActionType::CATAPULT;
  374. attack.side = next->unitSide();
  375. attack.stackNumber = next->unitId();
  376. makeAutomaticAction(next, attack);
  377. return true;
  378. }
  379. }
  380. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  381. {
  382. TStacks possibleStacks = gameHandler->battleGetStacksIf([=](const CStack * s)
  383. {
  384. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  385. });
  386. if (possibleStacks.empty())
  387. {
  388. makeStackDoNothing(next);
  389. return true;
  390. }
  391. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  392. {
  393. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  394. const CStack * toBeHealed = possibleStacks.front();
  395. BattleAction heal;
  396. heal.actionType = EActionType::STACK_HEAL;
  397. heal.aimToUnit(toBeHealed);
  398. heal.side = next->unitSide();
  399. heal.stackNumber = next->unitId();
  400. makeAutomaticAction(next, heal);
  401. return true;
  402. }
  403. }
  404. stackTurnTrigger(next); //various effects
  405. if(next->fear)
  406. {
  407. makeStackDoNothing(next); //end immediately if stack was affected by fear
  408. return true;
  409. }
  410. return false;
  411. }
  412. bool BattleFlowProcessor::rollGoodMorale(const CStack * next)
  413. {
  414. //check for good morale
  415. auto nextStackMorale = next->moraleVal();
  416. if( !next->hadMorale
  417. && !next->defending
  418. && !next->waited()
  419. && !next->fear
  420. && next->alive()
  421. && nextStackMorale > 0)
  422. {
  423. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  424. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  425. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  426. {
  427. BattleTriggerEffect bte;
  428. bte.stackID = next->unitId();
  429. bte.effect = vstd::to_underlying(BonusType::MORALE);
  430. bte.val = 1;
  431. bte.additionalInfo = 0;
  432. gameHandler->sendAndApply(&bte); //play animation
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. void BattleFlowProcessor::onActionMade(const BattleAction &ba)
  439. {
  440. const auto & battle = gameHandler->gameState()->curB;
  441. const CStack * actedStack = battle->battleGetStackByID(ba.stackNumber, false);
  442. const CStack * activeStack = battle->battleGetStackByID(battle->getActiveStackID(), false);
  443. //we're after action, all results applied
  444. // check whether action has ended the battle
  445. if(owner->checkBattleStateChanges())
  446. return;
  447. if (ba.isUnitAction())
  448. {
  449. assert(activeStack != nullptr);
  450. assert(actedStack != nullptr);
  451. if (rollGoodMorale(actedStack))
  452. {
  453. // Good morale - same stack makes 2nd turn
  454. setActiveStack(actedStack);
  455. return;
  456. }
  457. }
  458. else
  459. {
  460. if (activeStack && activeStack->alive())
  461. {
  462. // this is action made by hero AND unit is alive (e.g. not killed by casted spell)
  463. // keep current active stack for next action
  464. setActiveStack(activeStack);
  465. return;
  466. }
  467. }
  468. activateNextStack();
  469. }
  470. void BattleFlowProcessor::makeStackDoNothing(const CStack * next)
  471. {
  472. BattleAction doNothing;
  473. doNothing.actionType = EActionType::NO_ACTION;
  474. doNothing.side = next->unitSide();
  475. doNothing.stackNumber = next->unitId();
  476. makeAutomaticAction(next, doNothing);
  477. }
  478. bool BattleFlowProcessor::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  479. {
  480. BattleSetActiveStack bsa;
  481. bsa.stack = stack->unitId();
  482. bsa.askPlayerInterface = false;
  483. gameHandler->sendAndApply(&bsa);
  484. bool ret = owner->makeAutomaticBattleAction(ba);
  485. return ret;
  486. }
  487. void BattleFlowProcessor::stackEnchantedTrigger(const CStack * st)
  488. {
  489. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  490. for(auto b : bl)
  491. {
  492. const CSpell * sp = SpellID(b->subtype).toSpell();
  493. if(!sp)
  494. continue;
  495. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  496. const int32_t level = ((val > 3) ? (val - 3) : val);
  497. spells::BattleCast battleCast(gameHandler->gameState()->curB, st, spells::Mode::PASSIVE, sp);
  498. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  499. battleCast.setEffectDuration(50);
  500. battleCast.setSpellLevel(level);
  501. spells::Target target;
  502. if(val > 3)
  503. {
  504. for(auto s : gameHandler->gameState()->curB->battleGetAllStacks())
  505. if(gameHandler->battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  506. target.emplace_back(s);
  507. }
  508. else
  509. {
  510. target.emplace_back(st);
  511. }
  512. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  513. }
  514. }
  515. void BattleFlowProcessor::removeObstacle(const CObstacleInstance & obstacle)
  516. {
  517. BattleObstaclesChanged obsRem;
  518. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  519. gameHandler->sendAndApply(&obsRem);
  520. }
  521. void BattleFlowProcessor::stackTurnTrigger(const CStack *st)
  522. {
  523. BattleTriggerEffect bte;
  524. bte.stackID = st->unitId();
  525. bte.effect = -1;
  526. bte.val = 0;
  527. bte.additionalInfo = 0;
  528. if (st->alive())
  529. {
  530. //unbind
  531. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  532. {
  533. bool unbind = true;
  534. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  535. auto adjacent = gameHandler->gameState()->curB->battleAdjacentUnits(st);
  536. for (auto b : bl)
  537. {
  538. if(b->additionalInfo != CAddInfo::NONE)
  539. {
  540. const CStack * stack = gameHandler->gameState()->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  541. if(stack)
  542. {
  543. if(vstd::contains(adjacent, stack)) //binding stack is still present
  544. unbind = false;
  545. }
  546. }
  547. else
  548. {
  549. unbind = false;
  550. }
  551. }
  552. if (unbind)
  553. {
  554. BattleSetStackProperty ssp;
  555. ssp.which = BattleSetStackProperty::UNBIND;
  556. ssp.stackID = st->unitId();
  557. gameHandler->sendAndApply(&ssp);
  558. }
  559. }
  560. if (st->hasBonusOfType(BonusType::POISON))
  561. {
  562. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  563. if (b) //TODO: what if not?...
  564. {
  565. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  566. if (bte.val < b->val) //(negative) poison effect increases - update it
  567. {
  568. bte.effect = vstd::to_underlying(BonusType::POISON);
  569. gameHandler->sendAndApply(&bte);
  570. }
  571. }
  572. }
  573. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  574. {
  575. const PlayerColor opponent = gameHandler->gameState()->curB->otherPlayer(gameHandler->gameState()->curB->battleGetOwner(st));
  576. const CGHeroInstance * opponentHero = gameHandler->gameState()->curB->getHero(opponent);
  577. if(opponentHero)
  578. {
  579. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  580. vstd::amin(manaDrained, opponentHero->mana);
  581. if(manaDrained)
  582. {
  583. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  584. bte.val = manaDrained;
  585. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  586. gameHandler->sendAndApply(&bte);
  587. }
  588. }
  589. }
  590. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  591. {
  592. bool fearsomeCreature = false;
  593. for (CStack * stack : gameHandler->gameState()->curB->stacks)
  594. {
  595. if (gameHandler->battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  596. {
  597. fearsomeCreature = true;
  598. break;
  599. }
  600. }
  601. if (fearsomeCreature)
  602. {
  603. if (gameHandler->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  604. {
  605. bte.effect = vstd::to_underlying(BonusType::FEAR);
  606. gameHandler->sendAndApply(&bte);
  607. }
  608. }
  609. }
  610. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  611. int side = gameHandler->gameState()->curB->whatSide(st->unitOwner());
  612. if(st->canCast() && gameHandler->gameState()->curB->battleGetEnchanterCounter(side) == 0)
  613. {
  614. bool cast = false;
  615. while(!bl.empty() && !cast)
  616. {
  617. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  618. auto spellID = SpellID(bonus->subtype);
  619. const CSpell * spell = SpellID(spellID).toSpell();
  620. bl.remove_if([&bonus](const Bonus * b)
  621. {
  622. return b == bonus.get();
  623. });
  624. spells::BattleCast parameters(gameHandler->gameState()->curB, st, spells::Mode::ENCHANTER, spell);
  625. parameters.setSpellLevel(bonus->val);
  626. parameters.massive = true;
  627. parameters.smart = true;
  628. //todo: recheck effect level
  629. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  630. {
  631. cast = true;
  632. int cooldown = bonus->additionalInfo[0];
  633. BattleSetStackProperty ssp;
  634. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  635. ssp.absolute = false;
  636. ssp.val = cooldown;
  637. ssp.stackID = st->unitId();
  638. gameHandler->sendAndApply(&ssp);
  639. }
  640. }
  641. }
  642. }
  643. }
  644. void BattleFlowProcessor::setActiveStack(const CStack * stack)
  645. {
  646. assert(stack);
  647. logGlobal->trace("Activating %s", stack->nodeName());
  648. BattleSetActiveStack sas;
  649. sas.stack = stack->unitId();
  650. gameHandler->sendAndApply(&sas);
  651. }