BattleFlowProcessor.cpp 25 KB

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