BattleFlowProcessor.cpp 34 KB

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