BattleFlowProcessor.cpp 29 KB

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