BattleFlowProcessor.cpp 24 KB

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