BattleFlowProcessor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. if (gameHandler->gameState()->curB->tacticDistance == 0)
  116. onTacticsEnded();
  117. }
  118. void BattleFlowProcessor::trySummonGuardians(const CStack * stack)
  119. {
  120. if (!stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  121. return;
  122. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  123. auto accessibility = gameHandler->getAccesibility();
  124. CreatureID creatureData = CreatureID(summonInfo->subtype);
  125. std::vector<BattleHex> targetHexes;
  126. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  127. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  128. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  129. For one-hex targets there are four guardians - front, back and one per side (up + down).
  130. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  131. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  132. if (!guardianIsBig)
  133. targetHexes = stack->getSurroundingHexes();
  134. else
  135. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  136. for(auto hex : targetHexes)
  137. {
  138. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  139. {
  140. battle::UnitInfo info;
  141. info.id = gameHandler->gameState()->curB->battleNextUnitId();
  142. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  143. info.type = creatureData;
  144. info.side = stack->unitSide();
  145. info.position = hex;
  146. info.summoned = true;
  147. BattleUnitsChanged pack;
  148. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  149. info.save(pack.changedStacks.back().data);
  150. gameHandler->sendAndApply(&pack);
  151. }
  152. }
  153. }
  154. void BattleFlowProcessor::castOpeningSpells()
  155. {
  156. for (int i = 0; i < 2; ++i)
  157. {
  158. auto h = gameHandler->gameState()->curB->battleGetFightingHero(i);
  159. if (!h)
  160. continue;
  161. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  162. for (auto b : *bl)
  163. {
  164. spells::BonusCaster caster(h, b);
  165. const CSpell * spell = SpellID(b->subtype).toSpell();
  166. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  167. parameters.setSpellLevel(3);
  168. parameters.setEffectDuration(b->val);
  169. parameters.massive = true;
  170. parameters.castIfPossible(gameHandler->spellEnv, spells::Target());
  171. }
  172. }
  173. }
  174. void BattleFlowProcessor::onTacticsEnded()
  175. {
  176. //initial stacks appearance triggers, e.g. built-in bonus spells
  177. auto initialStacks = gameHandler->gameState()->curB->stacks; //use temporary variable to outclude summoned stacks added to gameHandler->gameState()->curB->stacks from processing
  178. for (CStack * stack : initialStacks)
  179. {
  180. trySummonGuardians(stack);
  181. stackEnchantedTrigger(stack);
  182. }
  183. castOpeningSpells();
  184. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  185. if (owner->checkBattleStateChanges())
  186. return;
  187. startNextRound(true);
  188. activateNextStack();
  189. }
  190. void BattleFlowProcessor::startNextRound(bool isFirstRound)
  191. {
  192. BattleNextRound bnr;
  193. bnr.round = gameHandler->gameState()->curB->round + 1;
  194. logGlobal->debug("Round %d", bnr.round);
  195. gameHandler->sendAndApply(&bnr);
  196. auto obstacles = gameHandler->gameState()->curB->obstacles; //we copy container, because we're going to modify it
  197. for (auto &obstPtr : obstacles)
  198. {
  199. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  200. if (sco->turnsRemaining == 0)
  201. removeObstacle(*obstPtr);
  202. }
  203. const BattleInfo & curB = *gameHandler->gameState()->curB;
  204. for(auto stack : curB.stacks)
  205. {
  206. if(stack->alive() && !isFirstRound)
  207. stackEnchantedTrigger(stack);
  208. }
  209. }
  210. const CStack * BattleFlowProcessor::getNextStack()
  211. {
  212. std::vector<battle::Units> q;
  213. gameHandler->gameState()->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  214. if(q.empty())
  215. return nullptr;
  216. if(q.front().empty())
  217. return nullptr;
  218. auto next = q.front().front();
  219. const auto stack = dynamic_cast<const CStack *>(next);
  220. // regeneration takes place before everything else but only during first turn attempt in each round
  221. // also works under blind and similar effects
  222. if(stack && stack->alive() && !stack->waiting)
  223. {
  224. BattleTriggerEffect bte;
  225. bte.stackID = stack->unitId();
  226. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  227. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  228. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  229. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  230. if(bte.val) // anything to heal
  231. gameHandler->sendAndApply(&bte);
  232. }
  233. if(!next->willMove())
  234. return nullptr;
  235. return stack;
  236. }
  237. void BattleFlowProcessor::activateNextStack()
  238. {
  239. //TODO: activate next round if next == nullptr
  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. const CStack * actedStack = battle->battleGetStackByID(ba.stackNumber, false);
  427. const CStack * activeStack = battle->battleGetStackByID(battle->getActiveStackID(), false);
  428. //we're after action, all results applied
  429. // check whether action has ended the battle
  430. if(owner->checkBattleStateChanges())
  431. return;
  432. // tactics - next stack will be selected by player
  433. if(battle->tacticDistance != 0)
  434. return;
  435. if (ba.isUnitAction())
  436. {
  437. assert(activeStack != nullptr);
  438. assert(actedStack != nullptr);
  439. if (rollGoodMorale(actedStack))
  440. {
  441. // Good morale - same stack makes 2nd turn
  442. setActiveStack(actedStack);
  443. return;
  444. }
  445. }
  446. else
  447. {
  448. if (activeStack && activeStack->alive())
  449. {
  450. // this is action made by hero AND unit is alive (e.g. not killed by casted spell)
  451. // keep current active stack for next action
  452. setActiveStack(activeStack);
  453. return;
  454. }
  455. }
  456. activateNextStack();
  457. }
  458. void BattleFlowProcessor::makeStackDoNothing(const CStack * next)
  459. {
  460. BattleAction doNothing;
  461. doNothing.actionType = EActionType::NO_ACTION;
  462. doNothing.side = next->unitSide();
  463. doNothing.stackNumber = next->unitId();
  464. makeAutomaticAction(next, doNothing);
  465. }
  466. bool BattleFlowProcessor::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  467. {
  468. BattleSetActiveStack bsa;
  469. bsa.stack = stack->unitId();
  470. bsa.askPlayerInterface = false;
  471. gameHandler->sendAndApply(&bsa);
  472. bool ret = owner->makeAutomaticBattleAction(ba);
  473. return ret;
  474. }
  475. void BattleFlowProcessor::stackEnchantedTrigger(const CStack * st)
  476. {
  477. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  478. for(auto b : bl)
  479. {
  480. const CSpell * sp = SpellID(b->subtype).toSpell();
  481. if(!sp)
  482. continue;
  483. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  484. const int32_t level = ((val > 3) ? (val - 3) : val);
  485. spells::BattleCast battleCast(gameHandler->gameState()->curB, st, spells::Mode::PASSIVE, sp);
  486. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  487. battleCast.setEffectDuration(50);
  488. battleCast.setSpellLevel(level);
  489. spells::Target target;
  490. if(val > 3)
  491. {
  492. for(auto s : gameHandler->gameState()->curB->battleGetAllStacks())
  493. if(gameHandler->battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  494. target.emplace_back(s);
  495. }
  496. else
  497. {
  498. target.emplace_back(st);
  499. }
  500. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  501. }
  502. }
  503. void BattleFlowProcessor::removeObstacle(const CObstacleInstance & obstacle)
  504. {
  505. BattleObstaclesChanged obsRem;
  506. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  507. gameHandler->sendAndApply(&obsRem);
  508. }
  509. void BattleFlowProcessor::stackTurnTrigger(const CStack *st)
  510. {
  511. BattleTriggerEffect bte;
  512. bte.stackID = st->unitId();
  513. bte.effect = -1;
  514. bte.val = 0;
  515. bte.additionalInfo = 0;
  516. if (st->alive())
  517. {
  518. //unbind
  519. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  520. {
  521. bool unbind = true;
  522. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  523. auto adjacent = gameHandler->gameState()->curB->battleAdjacentUnits(st);
  524. for (auto b : bl)
  525. {
  526. if(b->additionalInfo != CAddInfo::NONE)
  527. {
  528. const CStack * stack = gameHandler->gameState()->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  529. if(stack)
  530. {
  531. if(vstd::contains(adjacent, stack)) //binding stack is still present
  532. unbind = false;
  533. }
  534. }
  535. else
  536. {
  537. unbind = false;
  538. }
  539. }
  540. if (unbind)
  541. {
  542. BattleSetStackProperty ssp;
  543. ssp.which = BattleSetStackProperty::UNBIND;
  544. ssp.stackID = st->unitId();
  545. gameHandler->sendAndApply(&ssp);
  546. }
  547. }
  548. if (st->hasBonusOfType(BonusType::POISON))
  549. {
  550. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  551. if (b) //TODO: what if not?...
  552. {
  553. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  554. if (bte.val < b->val) //(negative) poison effect increases - update it
  555. {
  556. bte.effect = vstd::to_underlying(BonusType::POISON);
  557. gameHandler->sendAndApply(&bte);
  558. }
  559. }
  560. }
  561. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  562. {
  563. const PlayerColor opponent = gameHandler->gameState()->curB->otherPlayer(gameHandler->gameState()->curB->battleGetOwner(st));
  564. const CGHeroInstance * opponentHero = gameHandler->gameState()->curB->getHero(opponent);
  565. if(opponentHero)
  566. {
  567. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  568. vstd::amin(manaDrained, opponentHero->mana);
  569. if(manaDrained)
  570. {
  571. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  572. bte.val = manaDrained;
  573. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  574. gameHandler->sendAndApply(&bte);
  575. }
  576. }
  577. }
  578. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  579. {
  580. bool fearsomeCreature = false;
  581. for (CStack * stack : gameHandler->gameState()->curB->stacks)
  582. {
  583. if (gameHandler->battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  584. {
  585. fearsomeCreature = true;
  586. break;
  587. }
  588. }
  589. if (fearsomeCreature)
  590. {
  591. if (gameHandler->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  592. {
  593. bte.effect = vstd::to_underlying(BonusType::FEAR);
  594. gameHandler->sendAndApply(&bte);
  595. }
  596. }
  597. }
  598. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  599. int side = gameHandler->gameState()->curB->whatSide(st->unitOwner());
  600. if(st->canCast() && gameHandler->gameState()->curB->battleGetEnchanterCounter(side) == 0)
  601. {
  602. bool cast = false;
  603. while(!bl.empty() && !cast)
  604. {
  605. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  606. auto spellID = SpellID(bonus->subtype);
  607. const CSpell * spell = SpellID(spellID).toSpell();
  608. bl.remove_if([&bonus](const Bonus * b)
  609. {
  610. return b == bonus.get();
  611. });
  612. spells::BattleCast parameters(gameHandler->gameState()->curB, st, spells::Mode::ENCHANTER, spell);
  613. parameters.setSpellLevel(bonus->val);
  614. parameters.massive = true;
  615. parameters.smart = true;
  616. //todo: recheck effect level
  617. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  618. {
  619. cast = true;
  620. int cooldown = bonus->additionalInfo[0];
  621. BattleSetStackProperty ssp;
  622. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  623. ssp.absolute = false;
  624. ssp.val = cooldown;
  625. ssp.stackID = st->unitId();
  626. gameHandler->sendAndApply(&ssp);
  627. }
  628. }
  629. }
  630. }
  631. }
  632. void BattleFlowProcessor::setActiveStack(const CStack * stack)
  633. {
  634. assert(stack);
  635. logGlobal->trace("Activating %s", stack->nodeName());
  636. BattleSetActiveStack sas;
  637. sas.stack = stack->unitId();
  638. gameHandler->sendAndApply(&sas);
  639. }