BattleFlowProcessor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. int32_t spellLevel = b->additionalInfo != CAddInfo::NONE ? b->additionalInfo[0] : 3;
  177. parameters.setSpellLevel(spellLevel);
  178. parameters.setEffectDuration(b->val);
  179. parameters.massive = true;
  180. parameters.castIfPossible(gameHandler->spellcastEnvironment(), spells::Target());
  181. }
  182. }
  183. }
  184. void BattleFlowProcessor::onTacticsEnded(const CBattleInfoCallback & battle)
  185. {
  186. //initial stacks appearance triggers, e.g. built-in bonus spells
  187. auto initialStacks = battle.battleGetAllStacks(true);
  188. for (const CStack * stack : initialStacks)
  189. {
  190. trySummonGuardians(battle, stack);
  191. stackEnchantedTrigger(battle, stack);
  192. }
  193. castOpeningSpells(battle);
  194. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  195. if (owner->checkBattleStateChanges(battle))
  196. return;
  197. startNextRound(battle, true);
  198. activateNextStack(battle);
  199. }
  200. void BattleFlowProcessor::startNextRound(const CBattleInfoCallback & battle, bool isFirstRound)
  201. {
  202. BattleNextRound bnr;
  203. bnr.battleID = battle.getBattle()->getBattleID();
  204. logGlobal->debug("Next round starts");
  205. gameHandler->sendAndApply(bnr);
  206. // operate on copy - removing obstacles will invalidate iterator on 'battle' container
  207. auto obstacles = battle.battleGetAllObstacles();
  208. for (const auto & obstPtr : obstacles)
  209. {
  210. const auto * sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get());
  211. if (sco && sco->turnsRemaining == 0)
  212. removeObstacle(battle, *obstPtr);
  213. }
  214. for(const auto * stack : battle.battleGetAllStacks(true))
  215. {
  216. if(stack->alive() && !isFirstRound)
  217. stackEnchantedTrigger(battle, stack);
  218. }
  219. }
  220. const CStack * BattleFlowProcessor::getNextStack(const CBattleInfoCallback & battle)
  221. {
  222. std::vector<battle::Units> q;
  223. battle.battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  224. if(q.empty())
  225. return nullptr;
  226. if(q.front().empty())
  227. return nullptr;
  228. const auto * next = q.front().front();
  229. const auto * stack = dynamic_cast<const CStack *>(next);
  230. // regeneration takes place before everything else but only during first turn attempt in each round
  231. // also works under blind and similar effects
  232. if(stack && stack->alive() && !stack->waiting)
  233. {
  234. BattleTriggerEffect bte;
  235. bte.battleID = battle.getBattle()->getBattleID();
  236. bte.stackID = stack->unitId();
  237. bte.effect = BonusType::HP_REGENERATION;
  238. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  239. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  240. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  241. if(bte.val) // anything to heal
  242. gameHandler->sendAndApply(bte);
  243. }
  244. if(!next || !next->willMove())
  245. return nullptr;
  246. return stack;
  247. }
  248. void BattleFlowProcessor::activateNextStack(const CBattleInfoCallback & battle)
  249. {
  250. // Find next stack that requires manual control
  251. for (;;)
  252. {
  253. // battle has ended
  254. if (owner->checkBattleStateChanges(battle))
  255. return;
  256. const CStack * next = getNextStack(battle);
  257. if (!next)
  258. {
  259. // No stacks to move - start next round
  260. startNextRound(battle, false);
  261. next = getNextStack(battle);
  262. if (!next)
  263. throw std::runtime_error("Failed to find valid stack to act!");
  264. }
  265. BattleUnitsChanged removeGhosts;
  266. removeGhosts.battleID = battle.getBattle()->getBattleID();
  267. auto pendingGhosts = battle.battleGetStacksIf([](const CStack * stack){
  268. return stack->ghostPending;
  269. });
  270. for(const auto * stack : pendingGhosts)
  271. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  272. if(!removeGhosts.changedStacks.empty())
  273. gameHandler->sendAndApply(removeGhosts);
  274. gameHandler->turnTimerHandler->onBattleNextStack(battle.getBattle()->getBattleID(), *next);
  275. if (!tryMakeAutomaticAction(battle, next))
  276. {
  277. if(next->alive()) {
  278. setActiveStack(battle, next, BattleUnitTurnReason::TURN_QUEUE);
  279. break;
  280. }
  281. }
  282. }
  283. }
  284. bool BattleFlowProcessor::tryMakeAutomaticAction(const CBattleInfoCallback & battle, const CStack * next)
  285. {
  286. if(tryActivateMoralePenalty(battle, next))
  287. return true;
  288. if(tryActivateBerserkPenalty(battle, next))
  289. return true;
  290. if(tryAutomaticActionOfWarMachines(battle, next))
  291. return true;
  292. stackTurnTrigger(battle, next); //various effects
  293. if(next->fear)
  294. {
  295. makeStackDoNothing(battle, next); //end immediately if stack was affected by fear
  296. return true;
  297. }
  298. return false;
  299. }
  300. bool BattleFlowProcessor::tryActivateMoralePenalty(const CBattleInfoCallback & battle, const CStack * next)
  301. {
  302. // check for bad morale => freeze
  303. int nextStackMorale = next->moraleVal();
  304. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  305. {
  306. ObjectInstanceID ownerArmy = battle.getBattle()->getSideArmy(next->unitSide())->id;
  307. if (gameHandler->randomizer->rollBadMorale(ownerArmy, -nextStackMorale))
  308. {
  309. //unit loses its turn - empty freeze action
  310. BattleAction ba;
  311. ba.actionType = EActionType::BAD_MORALE;
  312. ba.side = next->unitSide();
  313. ba.stackNumber = next->unitId();
  314. makeAutomaticAction(battle, next, ba);
  315. return true;
  316. }
  317. }
  318. return false;
  319. }
  320. bool BattleFlowProcessor::tryActivateBerserkPenalty(const CBattleInfoCallback & battle, const CStack * next)
  321. {
  322. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  323. {
  324. ForcedAction forcedAction = battle.getBerserkForcedAction(next);
  325. if (forcedAction.type == EActionType::SHOOT)
  326. {
  327. BattleAction rangeAttack;
  328. rangeAttack.actionType = EActionType::SHOOT;
  329. rangeAttack.side = next->unitSide();
  330. rangeAttack.stackNumber = next->unitId();
  331. rangeAttack.aimToUnit(forcedAction.target);
  332. makeAutomaticAction(battle, next, rangeAttack);
  333. }
  334. else if (forcedAction.type == EActionType::WALK_AND_ATTACK)
  335. {
  336. BattleAction meleeAttack;
  337. meleeAttack.actionType = EActionType::WALK_AND_ATTACK;
  338. meleeAttack.side = next->unitSide();
  339. meleeAttack.stackNumber = next->unitId();
  340. meleeAttack.aimToHex(forcedAction.position);
  341. meleeAttack.aimToUnit(forcedAction.target);
  342. makeAutomaticAction(battle, next, meleeAttack);
  343. } else if (forcedAction.type == EActionType::WALK)
  344. {
  345. BattleAction movement;
  346. movement.actionType = EActionType::WALK;
  347. movement.stackNumber = next->unitId();
  348. movement.aimToHex(forcedAction.position);
  349. makeAutomaticAction(battle, next, movement);
  350. }
  351. else
  352. {
  353. makeStackDoNothing(battle, next);
  354. }
  355. return true;
  356. }
  357. return false;
  358. }
  359. bool BattleFlowProcessor::tryAutomaticActionOfWarMachines(const CBattleInfoCallback & battle, const CStack * next)
  360. {
  361. if (tryMakeAutomaticActionOfBallistaOrTowers(battle, next))
  362. return true;
  363. if (tryMakeAutomaticActionOfCatapult(battle, next))
  364. return true;
  365. if (tryMakeAutomaticActionOfFirstAidTent(battle, next))
  366. return true;
  367. return false;
  368. }
  369. bool BattleFlowProcessor::tryMakeAutomaticActionOfBallistaOrTowers(const CBattleInfoCallback & battle, const CStack * next)
  370. {
  371. const CGHeroInstance * curOwner = battle.battleGetOwnerHero(next);
  372. const CreatureID stackCreatureId = next->unitType()->getId();
  373. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  374. && (!curOwner || !gameHandler->randomizer->rollCombatAbility(curOwner->id, curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(stackCreatureId)))))
  375. {
  376. BattleAction attack;
  377. attack.actionType = EActionType::SHOOT;
  378. attack.side = next->unitSide();
  379. attack.stackNumber = next->unitId();
  380. const TStacks possibleTargets = battle.battleGetStacksIf([&next, &battle](const CStack * s)
  381. {
  382. return s->unitOwner() != next->unitOwner() && s->isValidTarget() && battle.battleCanShoot(next, s->getPosition());
  383. });
  384. struct TargetInfo
  385. {
  386. bool insideTheWalls;
  387. bool canAttackNextTurn;
  388. bool isParalyzed;
  389. bool isMachine;
  390. float towerAttackValue;
  391. const CStack * stack;
  392. };
  393. const auto & getCanAttackNextTurn = [&battle] (const battle::Unit * unit)
  394. {
  395. if (battle.battleCanShoot(unit))
  396. return true;
  397. BattleHexArray attackableHexes;
  398. battle.battleGetAvailableHexes(unit, true, false, &attackableHexes);
  399. return !attackableHexes.empty();
  400. };
  401. const auto & getTowerAttackValue = [&battle, &next] (const battle::Unit * unit)
  402. {
  403. float unitValue = static_cast<float>(unit->unitType()->getAIValue());
  404. float singleHpValue = unitValue / static_cast<float>(unit->getMaxHealth());
  405. float fullHp = static_cast<float>(unit->getTotalHealth());
  406. int distance = BattleHex::getDistance(next->getPosition(), unit->getPosition());
  407. BattleAttackInfo attackInfo(next, unit, distance, true);
  408. DamageEstimation estimation = battle.calculateDmgRange(attackInfo);
  409. float avgDmg = (static_cast<float>(estimation.damage.max) + static_cast<float>(estimation.damage.min)) / 2;
  410. float realAvgDmg = avgDmg > fullHp ? fullHp : avgDmg;
  411. float avgUnitKilled = (static_cast<float>(estimation.kills.max) + static_cast<float>(estimation.kills.min)) / 2;
  412. float dmgValue = realAvgDmg * singleHpValue;
  413. float killValue = avgUnitKilled * unitValue;
  414. return dmgValue + killValue;
  415. };
  416. std::vector<TargetInfo>targetsInfo;
  417. for (const CStack * possibleTarget : possibleTargets)
  418. {
  419. bool isMachine = possibleTarget->unitType()->warMachine != ArtifactID::NONE;
  420. bool isParalyzed = possibleTarget->hasBonusOfType(BonusType::NOT_ACTIVE) && !isMachine;
  421. const TargetInfo targetInfo =
  422. {
  423. battle.battleIsInsideWalls(possibleTarget->getPosition()),
  424. getCanAttackNextTurn(possibleTarget),
  425. isParalyzed,
  426. isMachine,
  427. getTowerAttackValue(possibleTarget),
  428. possibleTarget
  429. };
  430. targetsInfo.push_back(targetInfo);
  431. }
  432. const auto & isBetterTarget = [](const TargetInfo & candidate, const TargetInfo & current)
  433. {
  434. if (candidate.isParalyzed != current.isParalyzed)
  435. return candidate.isParalyzed < current.isParalyzed;
  436. if (candidate.isMachine != current.isMachine)
  437. return candidate.isMachine < current.isMachine;
  438. if (candidate.canAttackNextTurn != current.canAttackNextTurn)
  439. return candidate.canAttackNextTurn > current.canAttackNextTurn;
  440. if (candidate.insideTheWalls != current.insideTheWalls)
  441. return candidate.insideTheWalls > current.insideTheWalls;
  442. return candidate.towerAttackValue > current.towerAttackValue;
  443. };
  444. const TargetInfo * target = nullptr;
  445. for(const auto & elem : targetsInfo)
  446. {
  447. if (target == nullptr || isBetterTarget(elem, *target))
  448. target = &elem;
  449. }
  450. if(target == nullptr)
  451. {
  452. makeStackDoNothing(battle, next);
  453. }
  454. else
  455. {
  456. attack.aimToUnit(target->stack);
  457. makeAutomaticAction(battle, next, attack);
  458. }
  459. return true;
  460. }
  461. return false;
  462. }
  463. bool BattleFlowProcessor::tryMakeAutomaticActionOfCatapult(const CBattleInfoCallback & battle, const CStack * next)
  464. {
  465. const CGHeroInstance * curOwner = battle.battleGetOwnerHero(next);
  466. if (next->unitType()->getId() == CreatureID::CATAPULT)
  467. {
  468. const auto & attackableBattleHexes = battle.getAttackableWallParts();
  469. if (attackableBattleHexes.empty())
  470. {
  471. makeStackDoNothing(battle, next);
  472. return true;
  473. }
  474. if (!curOwner || !gameHandler->randomizer->rollCombatAbility(curOwner->id, curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::CATAPULT)))))
  475. {
  476. BattleAction attack;
  477. attack.actionType = EActionType::CATAPULT;
  478. attack.side = next->unitSide();
  479. attack.stackNumber = next->unitId();
  480. makeAutomaticAction(battle, next, attack);
  481. return true;
  482. }
  483. }
  484. return false;
  485. }
  486. bool BattleFlowProcessor::tryMakeAutomaticActionOfFirstAidTent(const CBattleInfoCallback & battle, const CStack * next)
  487. {
  488. const CGHeroInstance * curOwner = battle.battleGetOwnerHero(next);
  489. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  490. {
  491. TStacks possibleStacks = battle.battleGetStacksIf([&next](const CStack * s)
  492. {
  493. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  494. });
  495. if (possibleStacks.empty())
  496. {
  497. makeStackDoNothing(battle, next);
  498. return true;
  499. }
  500. if (!curOwner || !gameHandler->randomizer->rollCombatAbility(curOwner->id, curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::FIRST_AID_TENT)))))
  501. {
  502. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  503. const CStack * toBeHealed = possibleStacks.front();
  504. BattleAction heal;
  505. heal.actionType = EActionType::STACK_HEAL;
  506. heal.aimToUnit(toBeHealed);
  507. heal.side = next->unitSide();
  508. heal.stackNumber = next->unitId();
  509. makeAutomaticAction(battle, next, heal);
  510. return true;
  511. }
  512. }
  513. return false;
  514. }
  515. bool BattleFlowProcessor::rollGoodMorale(const CBattleInfoCallback & battle, const CStack * next)
  516. {
  517. //check for good morale
  518. auto nextStackMorale = next->moraleVal();
  519. if( !next->hadMorale
  520. && !next->defending
  521. && !next->waited()
  522. && !next->fear
  523. && next->alive()
  524. && next->canMove()
  525. && nextStackMorale > 0)
  526. {
  527. ObjectInstanceID ownerArmy = battle.getBattle()->getSideArmy(next->unitSide())->id;
  528. if (gameHandler->randomizer->rollGoodMorale(ownerArmy, nextStackMorale))
  529. {
  530. BattleTriggerEffect bte;
  531. bte.battleID = battle.getBattle()->getBattleID();
  532. bte.stackID = next->unitId();
  533. bte.effect = BonusType::MORALE;
  534. bte.val = 1;
  535. bte.additionalInfo = 0;
  536. gameHandler->sendAndApply(bte); //play animation
  537. return true;
  538. }
  539. }
  540. return false;
  541. }
  542. void BattleFlowProcessor::onActionMade(const CBattleInfoCallback & battle, const BattleAction &ba)
  543. {
  544. const auto * actedStack = battle.battleGetStackByID(ba.stackNumber, false);
  545. const auto * activeStack = battle.battleActiveUnit();
  546. if (ba.actionType == EActionType::END_TACTIC_PHASE)
  547. {
  548. onTacticsEnded(battle);
  549. return;
  550. }
  551. //we're after action, all results applied
  552. // check whether action has ended the battle
  553. if(owner->checkBattleStateChanges(battle))
  554. return;
  555. // tactics - next stack will be selected by player
  556. if(battle.battleGetTacticDist() != 0)
  557. return;
  558. // creature will not skip the turn after casting a spell if spell uses canCastWithoutSkip
  559. if(ba.actionType == EActionType::MONSTER_SPELL)
  560. {
  561. assert(activeStack != nullptr);
  562. assert(actedStack != nullptr);
  563. // 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
  564. if(actedStack->castSpellThisTurn && ba.spell.hasValue() && ba.spell.toSpell()->canCastWithoutSkip())
  565. {
  566. setActiveStack(battle, actedStack, BattleUnitTurnReason::UNIT_SPELLCAST);
  567. return;
  568. }
  569. }
  570. if (ba.isUnitAction())
  571. {
  572. assert(activeStack != nullptr);
  573. assert(actedStack != nullptr);
  574. if (rollGoodMorale(battle, actedStack))
  575. {
  576. // Good morale - same stack makes 2nd turn
  577. setActiveStack(battle, actedStack, BattleUnitTurnReason::MORALE);
  578. return;
  579. }
  580. }
  581. else
  582. {
  583. if (activeStack && activeStack->alive())
  584. {
  585. bool activeStackAffectedBySpell = !activeStack->canMove() ||
  586. tryActivateBerserkPenalty(battle, battle.battleGetStackByID(battle.getBattle()->getActiveStackID()));
  587. // this is action made by hero AND unit is neither killed nor affected by reflected spell like blind or berserk
  588. // keep current active stack for next action
  589. if (!activeStackAffectedBySpell)
  590. {
  591. setActiveStack(battle, activeStack, BattleUnitTurnReason::HERO_SPELLCAST);
  592. return;
  593. }
  594. }
  595. }
  596. activateNextStack(battle);
  597. }
  598. void BattleFlowProcessor::makeStackDoNothing(const CBattleInfoCallback & battle, const CStack * next)
  599. {
  600. BattleAction doNothing;
  601. doNothing.actionType = EActionType::NO_ACTION;
  602. doNothing.side = next->unitSide();
  603. doNothing.stackNumber = next->unitId();
  604. makeAutomaticAction(battle, next, doNothing);
  605. }
  606. bool BattleFlowProcessor::makeAutomaticAction(const CBattleInfoCallback & battle, const CStack *stack, const BattleAction &ba)
  607. {
  608. BattleSetActiveStack bsa;
  609. bsa.battleID = battle.getBattle()->getBattleID();
  610. bsa.stack = stack->unitId();
  611. bsa.reason = BattleUnitTurnReason::AUTOMATIC_ACTION;
  612. gameHandler->sendAndApply(bsa);
  613. bool ret = owner->makeAutomaticBattleAction(battle, ba);
  614. return ret;
  615. }
  616. void BattleFlowProcessor::stackEnchantedTrigger(const CBattleInfoCallback & battle, const CStack * st)
  617. {
  618. auto bl = *(st->getBonusesOfType(BonusType::ENCHANTED));
  619. for(const auto & b : bl)
  620. {
  621. if (!b->subtype.as<SpellID>().hasValue())
  622. continue;
  623. const CSpell * sp = b->subtype.as<SpellID>().toSpell();
  624. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  625. const int32_t level = ((val > 3) ? (val - 3) : val);
  626. spells::BattleCast battleCast(&battle, st, spells::Mode::PASSIVE, sp);
  627. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  628. battleCast.setEffectDuration(50);
  629. battleCast.setSpellLevel(level);
  630. spells::Target target;
  631. if(val > 3)
  632. {
  633. for(const auto * s : battle.battleGetAllStacks())
  634. if(battle.battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  635. target.emplace_back(s);
  636. }
  637. else
  638. {
  639. target.emplace_back(st);
  640. }
  641. battleCast.applyEffects(gameHandler->spellcastEnvironment(), target, false, true);
  642. }
  643. }
  644. void BattleFlowProcessor::removeObstacle(const CBattleInfoCallback & battle, const CObstacleInstance & obstacle)
  645. {
  646. BattleObstaclesChanged obsRem;
  647. obsRem.battleID = battle.getBattle()->getBattleID();
  648. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  649. gameHandler->sendAndApply(obsRem);
  650. }
  651. void BattleFlowProcessor::stackTurnTrigger(const CBattleInfoCallback & battle, const CStack *st)
  652. {
  653. BattleTriggerEffect bte;
  654. bte.battleID = battle.getBattle()->getBattleID();
  655. bte.stackID = st->unitId();
  656. bte.effect = BonusType::NONE;
  657. bte.val = 0;
  658. bte.additionalInfo = 0;
  659. if (st->alive())
  660. {
  661. //unbind
  662. if (st->hasBonusOfType(BonusType::BIND_EFFECT))
  663. {
  664. bool unbind = true;
  665. BonusList bl = *(st->getBonusesOfType(BonusType::BIND_EFFECT));
  666. auto adjacent = battle.battleAdjacentUnits(st);
  667. for (const auto & b : bl)
  668. {
  669. if(b->additionalInfo != CAddInfo::NONE)
  670. {
  671. const CStack * stack = battle.battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  672. if(stack && vstd::contains(adjacent, stack)) //binding stack is still present
  673. unbind = false;
  674. }
  675. else
  676. {
  677. unbind = false;
  678. }
  679. }
  680. if (unbind)
  681. {
  682. BattleSetStackProperty ssp;
  683. ssp.battleID = battle.getBattle()->getBattleID();
  684. ssp.which = BattleSetStackProperty::UNBIND;
  685. ssp.stackID = st->unitId();
  686. gameHandler->sendAndApply(ssp);
  687. }
  688. }
  689. if (st->hasBonusOfType(BonusType::POISON))
  690. {
  691. std::shared_ptr<const Bonus> b = st->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(SpellID(SpellID::POISON))).And(Selector::type()(BonusType::STACK_HEALTH)));
  692. if (b) //TODO: what if not?...
  693. {
  694. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  695. if (bte.val < b->val) //(negative) poison effect increases - update it
  696. {
  697. bte.effect = BonusType::POISON;
  698. gameHandler->sendAndApply(bte);
  699. }
  700. }
  701. }
  702. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  703. {
  704. const CGHeroInstance * opponentHero = battle.battleGetFightingHero(battle.otherSide(st->unitSide()));
  705. if(opponentHero)
  706. {
  707. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  708. vstd::amin(manaDrained, opponentHero->mana);
  709. if(manaDrained)
  710. {
  711. bte.effect = BonusType::MANA_DRAIN;
  712. bte.val = manaDrained;
  713. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  714. gameHandler->sendAndApply(bte);
  715. }
  716. }
  717. }
  718. if (st->hasBonusOfType(BonusType::FEARFUL))
  719. {
  720. int chance = st->valOfBonuses(BonusType::FEARFUL);
  721. ObjectInstanceID opponentArmyID = battle.battleGetArmyObject(battle.otherSide(st->unitSide()))->id;
  722. if (gameHandler->randomizer->rollCombatAbility(opponentArmyID, chance))
  723. {
  724. bte.effect = BonusType::FEARFUL;
  725. gameHandler->sendAndApply(bte);
  726. }
  727. }
  728. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  729. bl.remove_if([](const Bonus * b)
  730. {
  731. return b->subtype.as<SpellID>() == SpellID::NONE;
  732. });
  733. BattleSide side = battle.playerToSide(st->unitOwner());
  734. if(st->canCast())
  735. {
  736. bool cast = false;
  737. while(!bl.empty() && !cast)
  738. {
  739. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  740. auto spellID = bonus->subtype.as<SpellID>();
  741. const CSpell * spell = SpellID(spellID).toSpell();
  742. bl.remove_if([&bonus](const Bonus * b)
  743. {
  744. return b == bonus.get();
  745. });
  746. if (battle.battleGetEnchanterCounter(side) != 0 && bonus->additionalInfo[0] != 0)
  747. continue; // cooldown
  748. spells::BattleCast parameters(&battle, st, spells::Mode::ENCHANTER, spell);
  749. parameters.setSpellLevel(bonus->val);
  750. //todo: recheck effect level
  751. if(parameters.castIfPossible(gameHandler->spellcastEnvironment(), spells::Target(1, parameters.massive ? spells::Destination() : spells::Destination(st))))
  752. {
  753. cast = true;
  754. int cooldown = bonus->additionalInfo[0];
  755. if (cooldown != 0)
  756. {
  757. BattleSetStackProperty ssp;
  758. ssp.battleID = battle.getBattle()->getBattleID();
  759. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  760. ssp.absolute = false;
  761. ssp.val = cooldown;
  762. ssp.stackID = st->unitId();
  763. gameHandler->sendAndApply(ssp);
  764. }
  765. }
  766. }
  767. }
  768. }
  769. }
  770. void BattleFlowProcessor::setActiveStack(const CBattleInfoCallback & battle, const battle::Unit * stack, BattleUnitTurnReason reason)
  771. {
  772. assert(stack);
  773. BattleSetActiveStack sas;
  774. sas.battleID = battle.getBattle()->getBattleID();
  775. sas.stack = stack->unitId();
  776. sas.reason = reason;
  777. gameHandler->sendAndApply(sas);
  778. }