BattleActionProcessor.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. /*
  2. * BattleActionProcessor.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 "BattleActionProcessor.h"
  12. #include "BattleProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../../lib/texts/CGeneralTextHandler.h"
  15. #include "../../lib/CStack.h"
  16. #include "../../lib/GameSettings.h"
  17. #include "../../lib/battle/CBattleInfoCallback.h"
  18. #include "../../lib/battle/CObstacleInstance.h"
  19. #include "../../lib/battle/IBattleState.h"
  20. #include "../../lib/battle/BattleAction.h"
  21. #include "../../lib/entities/building/TownFortifications.h"
  22. #include "../../lib/gameState/CGameState.h"
  23. #include "../../lib/networkPacks/PacksForClientBattle.h"
  24. #include "../../lib/networkPacks/SetStackEffect.h"
  25. #include "../../lib/spells/AbilityCaster.h"
  26. #include "../../lib/spells/CSpellHandler.h"
  27. #include "../../lib/spells/ISpellMechanics.h"
  28. #include "../../lib/spells/Problem.h"
  29. #include <vstd/RNG.h>
  30. BattleActionProcessor::BattleActionProcessor(BattleProcessor * owner, CGameHandler * newGameHandler)
  31. : owner(owner)
  32. , gameHandler(newGameHandler)
  33. {
  34. }
  35. bool BattleActionProcessor::doEmptyAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  36. {
  37. return true;
  38. }
  39. bool BattleActionProcessor::doEndTacticsAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  40. {
  41. return true;
  42. }
  43. bool BattleActionProcessor::doWaitAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  44. {
  45. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  46. if (!canStackAct(battle, stack))
  47. return false;
  48. return true;
  49. }
  50. bool BattleActionProcessor::doRetreatAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  51. {
  52. if (!battle.battleCanFlee(battle.sideToPlayer(ba.side)))
  53. {
  54. gameHandler->complain("Cannot retreat!");
  55. return false;
  56. }
  57. owner->setBattleResult(battle, EBattleResult::ESCAPE, battle.otherSide(ba.side));
  58. return true;
  59. }
  60. bool BattleActionProcessor::doSurrenderAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  61. {
  62. PlayerColor player = battle.sideToPlayer(ba.side);
  63. int cost = battle.battleGetSurrenderCost(player);
  64. if (cost < 0)
  65. {
  66. gameHandler->complain("Cannot surrender!");
  67. return false;
  68. }
  69. if (gameHandler->getResource(player, EGameResID::GOLD) < cost)
  70. {
  71. gameHandler->complain("Not enough gold to surrender!");
  72. return false;
  73. }
  74. gameHandler->giveResource(player, EGameResID::GOLD, -cost);
  75. owner->setBattleResult(battle, EBattleResult::SURRENDER, battle.otherSide(ba.side));
  76. return true;
  77. }
  78. bool BattleActionProcessor::doHeroSpellAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  79. {
  80. const CGHeroInstance *h = battle.battleGetFightingHero(ba.side);
  81. if (!h)
  82. {
  83. logGlobal->error("Wrong caster!");
  84. return false;
  85. }
  86. if (!ba.spell.hasValue())
  87. {
  88. logGlobal->error("Wrong spell id (%d)!", ba.spell.getNum());
  89. return false;
  90. }
  91. const CSpell * s = ba.spell.toSpell();
  92. spells::BattleCast parameters(&battle, h, spells::Mode::HERO, s);
  93. spells::detail::ProblemImpl problem;
  94. auto m = s->battleMechanics(&parameters);
  95. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  96. {
  97. logGlobal->warn("Spell cannot be cast!");
  98. std::vector<std::string> texts;
  99. problem.getAll(texts);
  100. for(auto s : texts)
  101. logGlobal->warn(s);
  102. return false;
  103. }
  104. parameters.cast(gameHandler->spellEnv, ba.getTarget(&battle));
  105. return true;
  106. }
  107. bool BattleActionProcessor::doWalkAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  108. {
  109. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  110. battle::Target target = ba.getTarget(&battle);
  111. if (!canStackAct(battle, stack))
  112. return false;
  113. if(target.size() < 1)
  114. {
  115. gameHandler->complain("Destination required for move action.");
  116. return false;
  117. }
  118. int walkedTiles = moveStack(battle, ba.stackNumber, target.at(0).hexValue); //move
  119. if (!walkedTiles)
  120. {
  121. gameHandler->complain("Stack failed movement!");
  122. return false;
  123. }
  124. return true;
  125. }
  126. bool BattleActionProcessor::doDefendAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  127. {
  128. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  129. if (!canStackAct(battle, stack))
  130. return false;
  131. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  132. SetStackEffect sse;
  133. sse.battleID = battle.getBattle()->getBattleID();
  134. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::PERCENT_TO_ALL);
  135. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE), BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::ADDITIVE_VALUE);
  136. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE), BonusValueType::ADDITIVE_VALUE);
  137. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE)));
  138. int oldDefenceValue = defence.totalValue();
  139. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  140. defence.push_back(std::make_shared<Bonus>(bonus2));
  141. int difference = defence.totalValue() - oldDefenceValue;
  142. std::vector<Bonus> buffer;
  143. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  144. {
  145. difference = 1;
  146. buffer.push_back(alternativeWeakCreatureBonus);
  147. }
  148. else
  149. {
  150. buffer.push_back(defenseBonusToAdd);
  151. }
  152. buffer.push_back(bonus2);
  153. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  154. gameHandler->sendAndApply(&sse);
  155. BattleLogMessage message;
  156. message.battleID = battle.getBattle()->getBattleID();
  157. MetaString text;
  158. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  159. stack->addNameReplacement(text);
  160. text.replaceNumber(difference);
  161. message.lines.push_back(text);
  162. gameHandler->sendAndApply(&message);
  163. return true;
  164. }
  165. bool BattleActionProcessor::doAttackAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  166. {
  167. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  168. battle::Target target = ba.getTarget(&battle);
  169. if (!canStackAct(battle, stack))
  170. return false;
  171. if(target.size() < 2)
  172. {
  173. gameHandler->complain("Two destinations required for attack action.");
  174. return false;
  175. }
  176. BattleHex attackPos = target.at(0).hexValue;
  177. BattleHex destinationTile = target.at(1).hexValue;
  178. const CStack * destinationStack = battle.battleGetStackByPos(destinationTile, true);
  179. if(!destinationStack)
  180. {
  181. gameHandler->complain("Invalid target to attack");
  182. return false;
  183. }
  184. BattleHex startingPos = stack->getPosition();
  185. int distance = moveStack(battle, ba.stackNumber, attackPos);
  186. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  187. if(stack->getPosition() != attackPos && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false))) )
  188. {
  189. // we were not able to reach destination tile, nor occupy specified hex
  190. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  191. return true;
  192. }
  193. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  194. {
  195. destinationStack = nullptr;
  196. }
  197. if(!destinationStack)
  198. {
  199. gameHandler->complain("Unit can not attack itself");
  200. return false;
  201. }
  202. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  203. {
  204. gameHandler->complain("Attack cannot be performed!");
  205. return false;
  206. }
  207. //attack
  208. int totalAttacks = stack->totalAttacks.getMeleeValue();
  209. //TODO: move to CUnitState
  210. const auto * attackingHero = battle.battleGetFightingHero(ba.side);
  211. if(attackingHero)
  212. {
  213. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, BonusSubtypeID(stack->creatureId()));
  214. }
  215. static const auto firstStrikeSelector = Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeAll).Or(Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeMelee));
  216. const bool firstStrike = destinationStack->hasBonus(firstStrikeSelector);
  217. const bool retaliation = destinationStack->ableToRetaliate();
  218. bool ferocityApplied = false;
  219. int32_t defenderInitialQuantity = destinationStack->getCount();
  220. for (int i = 0; i < totalAttacks; ++i)
  221. {
  222. //first strike
  223. if(i == 0 && firstStrike && retaliation && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION))
  224. {
  225. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, false, true);
  226. }
  227. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  228. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  229. {
  230. makeAttack(battle, stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  231. if(!ferocityApplied && stack->hasBonusOfType(BonusType::FEROCITY))
  232. {
  233. auto ferocityBonus = stack->getBonus(Selector::type()(BonusType::FEROCITY));
  234. int32_t requiredCreaturesToKill = ferocityBonus->additionalInfo != CAddInfo::NONE ? ferocityBonus->additionalInfo[0] : 1;
  235. if(defenderInitialQuantity - destinationStack->getCount() >= requiredCreaturesToKill)
  236. {
  237. ferocityApplied = true;
  238. int additionalAttacksCount = stack->valOfBonuses(BonusType::FEROCITY);
  239. totalAttacks += additionalAttacksCount;
  240. }
  241. }
  242. }
  243. //counterattack
  244. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  245. if(stack->alive()
  246. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  247. && (i == 0 && !firstStrike)
  248. && retaliation && destinationStack->ableToRetaliate())
  249. {
  250. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, false, true);
  251. }
  252. }
  253. //return
  254. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  255. && target.size() == 3
  256. && startingPos != stack->getPosition()
  257. && startingPos == target.at(2).hexValue
  258. && stack->alive())
  259. {
  260. moveStack(battle, ba.stackNumber, startingPos);
  261. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  262. }
  263. return true;
  264. }
  265. bool BattleActionProcessor::doShootAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  266. {
  267. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  268. battle::Target target = ba.getTarget(&battle);
  269. if (!canStackAct(battle, stack))
  270. return false;
  271. if(target.size() < 1)
  272. {
  273. gameHandler->complain("Destination required for shot action.");
  274. return false;
  275. }
  276. auto destination = target.at(0).hexValue;
  277. const CStack * destinationStack = battle.battleGetStackByPos(destination);
  278. if (!battle.battleCanShoot(stack, destination))
  279. {
  280. gameHandler->complain("Cannot shoot!");
  281. return false;
  282. }
  283. if (!destinationStack)
  284. {
  285. gameHandler->complain("No target to shoot!");
  286. return false;
  287. }
  288. static const auto firstStrikeSelector = Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeAll).Or(Selector::typeSubtype(BonusType::FIRST_STRIKE, BonusCustomSubtype::damageTypeRanged));
  289. const bool firstStrike = destinationStack->hasBonus(firstStrikeSelector);
  290. if (!firstStrike)
  291. makeAttack(battle, stack, destinationStack, 0, destination, true, true, false);
  292. //ranged counterattack
  293. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  294. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  295. && destinationStack->ableToRetaliate()
  296. && battle.battleCanShoot(destinationStack, stack->getPosition())
  297. && stack->alive()) //attacker may have died (fire shield)
  298. {
  299. makeAttack(battle, destinationStack, stack, 0, stack->getPosition(), true, true, true);
  300. }
  301. //allow more than one additional attack
  302. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  303. //TODO: move to CUnitState
  304. const auto * attackingHero = battle.battleGetFightingHero(ba.side);
  305. if(attackingHero)
  306. {
  307. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, BonusSubtypeID(stack->creatureId()));
  308. }
  309. for(int i = firstStrike ? 0:1; i < totalRangedAttacks; ++i)
  310. {
  311. if(
  312. stack->alive()
  313. && destinationStack->alive()
  314. && stack->shots.canUse()
  315. )
  316. {
  317. makeAttack(battle, stack, destinationStack, 0, destination, false, true, false);
  318. }
  319. }
  320. return true;
  321. }
  322. bool BattleActionProcessor::doCatapultAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  323. {
  324. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  325. battle::Target target = ba.getTarget(&battle);
  326. if (!canStackAct(battle, stack))
  327. return false;
  328. std::shared_ptr<const Bonus> catapultAbility = stack->getFirstBonus(Selector::type()(BonusType::CATAPULT));
  329. if(!catapultAbility || catapultAbility->subtype == BonusSubtypeID())
  330. {
  331. gameHandler->complain("We do not know how to shoot :P");
  332. }
  333. else
  334. {
  335. const CSpell * spell = catapultAbility->subtype.as<SpellID>().toSpell();
  336. spells::BattleCast parameters(&battle, stack, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  337. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  338. parameters.setSpellLevel(shotLevel);
  339. parameters.cast(gameHandler->spellEnv, target);
  340. }
  341. return true;
  342. }
  343. bool BattleActionProcessor::doUnitSpellAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  344. {
  345. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  346. battle::Target target = ba.getTarget(&battle);
  347. SpellID spellID = ba.spell;
  348. if (!canStackAct(battle, stack))
  349. return false;
  350. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  351. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, BonusSubtypeID(spellID)));
  352. if (!spellcaster && !randSpellcaster)
  353. {
  354. gameHandler->complain("That stack can't cast spells!");
  355. return false;
  356. }
  357. if (randSpellcaster)
  358. {
  359. if (target.size() != 1)
  360. {
  361. gameHandler->complain("Invalid target for random spellcaster!");
  362. return false;
  363. }
  364. const battle::Unit * subject = target[0].unitValue;
  365. if (target[0].unitValue == nullptr)
  366. subject = battle.battleGetStackByPos(target[0].hexValue, true);
  367. if (subject == nullptr)
  368. {
  369. gameHandler->complain("Invalid target for random spellcaster!");
  370. return false;
  371. }
  372. spellID = battle.getRandomBeneficialSpell(gameHandler->getRandomGenerator(), stack, subject);
  373. if (spellID == SpellID::NONE)
  374. {
  375. gameHandler->complain("That stack can't cast spells!");
  376. return false;
  377. }
  378. }
  379. const CSpell * spell = SpellID(spellID).toSpell();
  380. spells::BattleCast parameters(&battle, stack, spells::Mode::CREATURE_ACTIVE, spell);
  381. int32_t spellLvl = 0;
  382. if(spellcaster)
  383. vstd::amax(spellLvl, spellcaster->val);
  384. if(randSpellcaster)
  385. vstd::amax(spellLvl, randSpellcaster->val);
  386. parameters.setSpellLevel(spellLvl);
  387. parameters.cast(gameHandler->spellEnv, target);
  388. return true;
  389. }
  390. bool BattleActionProcessor::doHealAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  391. {
  392. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  393. battle::Target target = ba.getTarget(&battle);
  394. if (!canStackAct(battle, stack))
  395. return false;
  396. if(target.size() < 1)
  397. {
  398. gameHandler->complain("Destination required for heal action.");
  399. return false;
  400. }
  401. const battle::Unit * destStack = nullptr;
  402. std::shared_ptr<const Bonus> healerAbility = stack->getFirstBonus(Selector::type()(BonusType::HEALER));
  403. if(target.at(0).unitValue)
  404. destStack = target.at(0).unitValue;
  405. else
  406. destStack = battle.battleGetUnitByPos(target.at(0).hexValue);
  407. if(stack == nullptr || destStack == nullptr || !healerAbility || !healerAbility->subtype.hasValue())
  408. {
  409. gameHandler->complain("There is either no healer, no destination, or healer cannot heal :P");
  410. }
  411. else
  412. {
  413. const CSpell * spell = healerAbility->subtype.as<SpellID>().toSpell();
  414. spells::BattleCast parameters(&battle, stack, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  415. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  416. parameters.setSpellLevel(0);
  417. parameters.cast(gameHandler->spellEnv, {dest});
  418. }
  419. return true;
  420. }
  421. bool BattleActionProcessor::canStackAct(const CBattleInfoCallback & battle, const CStack * stack)
  422. {
  423. if (!stack)
  424. {
  425. gameHandler->complain("No such stack!");
  426. return false;
  427. }
  428. if (!stack->alive())
  429. {
  430. gameHandler->complain("This stack is dead: " + stack->nodeName());
  431. return false;
  432. }
  433. if (battle.battleTacticDist())
  434. {
  435. if (stack && stack->unitSide() != battle.battleGetTacticsSide())
  436. {
  437. gameHandler->complain("This is not a stack of side that has tactics!");
  438. return false;
  439. }
  440. }
  441. else
  442. {
  443. if (stack != battle.battleActiveUnit())
  444. {
  445. gameHandler->complain("Action has to be about active stack!");
  446. return false;
  447. }
  448. }
  449. return true;
  450. }
  451. bool BattleActionProcessor::dispatchBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  452. {
  453. switch(ba.actionType)
  454. {
  455. case EActionType::BAD_MORALE:
  456. case EActionType::NO_ACTION:
  457. return doEmptyAction(battle, ba);
  458. case EActionType::END_TACTIC_PHASE:
  459. return doEndTacticsAction(battle, ba);
  460. case EActionType::RETREAT:
  461. return doRetreatAction(battle, ba);
  462. case EActionType::SURRENDER:
  463. return doSurrenderAction(battle, ba);
  464. case EActionType::HERO_SPELL:
  465. return doHeroSpellAction(battle, ba);
  466. case EActionType::WALK:
  467. return doWalkAction(battle, ba);
  468. case EActionType::WAIT:
  469. return doWaitAction(battle, ba);
  470. case EActionType::DEFEND:
  471. return doDefendAction(battle, ba);
  472. case EActionType::WALK_AND_ATTACK:
  473. return doAttackAction(battle, ba);
  474. case EActionType::SHOOT:
  475. return doShootAction(battle, ba);
  476. case EActionType::CATAPULT:
  477. return doCatapultAction(battle, ba);
  478. case EActionType::MONSTER_SPELL:
  479. return doUnitSpellAction(battle, ba);
  480. case EActionType::STACK_HEAL:
  481. return doHealAction(battle, ba);
  482. }
  483. gameHandler->complain("Unrecognized action type received!!");
  484. return false;
  485. }
  486. bool BattleActionProcessor::makeBattleActionImpl(const CBattleInfoCallback & battle, const BattleAction &ba)
  487. {
  488. logGlobal->trace("Making action: %s", ba.toString());
  489. const CStack * stack = battle.battleGetStackByID(ba.stackNumber);
  490. // for these events client does not expects StartAction/EndAction wrapper
  491. if (!ba.isBattleEndAction())
  492. {
  493. StartAction startAction(ba);
  494. startAction.battleID = battle.getBattle()->getBattleID();
  495. gameHandler->sendAndApply(&startAction);
  496. }
  497. bool result = dispatchBattleAction(battle, ba);
  498. if (!ba.isBattleEndAction())
  499. {
  500. EndAction endAction;
  501. endAction.battleID = battle.getBattle()->getBattleID();
  502. gameHandler->sendAndApply(&endAction);
  503. }
  504. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  505. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *stack);
  506. return result;
  507. }
  508. int BattleActionProcessor::moveStack(const CBattleInfoCallback & battle, int stack, BattleHex dest)
  509. {
  510. int ret = 0;
  511. const CStack *curStack = battle.battleGetStackByID(stack);
  512. const CStack *stackAtEnd = battle.battleGetStackByPos(dest);
  513. assert(curStack);
  514. assert(dest < GameConstants::BFIELD_SIZE);
  515. if (battle.battleGetTacticDist())
  516. {
  517. assert(battle.isInTacticRange(dest));
  518. }
  519. auto start = curStack->getPosition();
  520. if (start == dest)
  521. return 0;
  522. //initing necessary tables
  523. auto accessibility = battle.getAccessibility(curStack);
  524. std::set<BattleHex> passed;
  525. //Ignore obstacles on starting position
  526. passed.insert(curStack->getPosition());
  527. if(curStack->doubleWide())
  528. passed.insert(curStack->occupiedHex());
  529. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  530. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  531. {
  532. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  533. if(accessibility.accessible(shifted, curStack))
  534. dest = shifted;
  535. }
  536. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  537. {
  538. gameHandler->complain("Given destination is not accessible!");
  539. return 0;
  540. }
  541. bool canUseGate = false;
  542. auto dbState = battle.battleGetGateState();
  543. if(battle.battleGetFortifications().wallsHealth > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  544. dbState != EGateState::DESTROYED &&
  545. dbState != EGateState::BLOCKED)
  546. {
  547. canUseGate = true;
  548. }
  549. std::pair< std::vector<BattleHex>, int > path = battle.getPath(start, dest, curStack);
  550. ret = path.second;
  551. int creSpeed = curStack->getMovementRange(0);
  552. if (battle.battleGetTacticDist() > 0 && creSpeed > 0)
  553. creSpeed = GameConstants::BFIELD_SIZE;
  554. bool hasWideMoat = vstd::contains_if(battle.battleGetAllObstaclesOnPos(BattleHex(BattleHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  555. {
  556. return obst->obstacleType == CObstacleInstance::MOAT;
  557. });
  558. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  559. {
  560. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  561. return true;
  562. if (hex == BattleHex::GATE_OUTER)
  563. return true;
  564. if (hex == BattleHex::GATE_INNER)
  565. return true;
  566. return false;
  567. };
  568. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  569. {
  570. if (isGateDrawbridgeHex(hex))
  571. return true;
  572. if (curStack->doubleWide())
  573. {
  574. BattleHex otherHex = curStack->occupiedHex(hex);
  575. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  576. return true;
  577. }
  578. return false;
  579. };
  580. if (curStack->hasBonusOfType(BonusType::FLYING))
  581. {
  582. if (path.second <= creSpeed && path.first.size() > 0)
  583. {
  584. if (canUseGate && dbState != EGateState::OPENED &&
  585. occupyGateDrawbridgeHex(dest))
  586. {
  587. BattleUpdateGateState db;
  588. db.battleID = battle.getBattle()->getBattleID();
  589. db.state = EGateState::OPENED;
  590. gameHandler->sendAndApply(&db);
  591. }
  592. //inform clients about move
  593. BattleStackMoved sm;
  594. sm.battleID = battle.getBattle()->getBattleID();
  595. sm.stack = curStack->unitId();
  596. std::vector<BattleHex> tiles;
  597. tiles.push_back(path.first[0]);
  598. sm.tilesToMove = tiles;
  599. sm.distance = path.second;
  600. sm.teleporting = false;
  601. gameHandler->sendAndApply(&sm);
  602. }
  603. }
  604. else //for non-flying creatures
  605. {
  606. std::vector<BattleHex> tiles;
  607. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  608. int v = (int)path.first.size()-1;
  609. path.first.push_back(start);
  610. // check if gate need to be open or closed at some point
  611. BattleHex openGateAtHex, gateMayCloseAtHex;
  612. if (canUseGate)
  613. {
  614. for (int i = (int)path.first.size()-1; i >= 0; i--)
  615. {
  616. auto needOpenGates = [&](BattleHex hex) -> bool
  617. {
  618. if (hasWideMoat && hex == BattleHex::GATE_BRIDGE)
  619. return true;
  620. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == BattleHex::GATE_OUTER)
  621. return true;
  622. else if (hex == BattleHex::GATE_OUTER || hex == BattleHex::GATE_INNER)
  623. return true;
  624. return false;
  625. };
  626. auto hex = path.first[i];
  627. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  628. {
  629. if (needOpenGates(hex))
  630. openGateAtHex = path.first[i+1];
  631. //TODO we need find batter way to handle double-wide stacks
  632. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  633. if (curStack->doubleWide() && i + 2 < path.first.size())
  634. {
  635. BattleHex otherHex = curStack->occupiedHex(hex);
  636. if (otherHex.isValid() && needOpenGates(otherHex))
  637. openGateAtHex = path.first[i+2];
  638. }
  639. //gate may be opened and then closed during stack movement, but not other way around
  640. if (openGateAtHex.isValid())
  641. dbState = EGateState::OPENED;
  642. }
  643. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  644. {
  645. if (hex == BattleHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  646. {
  647. gateMayCloseAtHex = path.first[i-1];
  648. }
  649. if (hasWideMoat)
  650. {
  651. if (hex == BattleHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_OUTER)
  652. {
  653. gateMayCloseAtHex = path.first[i-1];
  654. }
  655. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 &&
  656. path.first[i-1] != BattleHex::GATE_INNER &&
  657. path.first[i-1] != BattleHex::GATE_BRIDGE)
  658. {
  659. gateMayCloseAtHex = path.first[i-1];
  660. }
  661. }
  662. else if (hex == BattleHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != BattleHex::GATE_INNER)
  663. {
  664. gateMayCloseAtHex = path.first[i-1];
  665. }
  666. }
  667. }
  668. }
  669. bool stackIsMoving = true;
  670. while(stackIsMoving)
  671. {
  672. if (v<tilesToMove)
  673. {
  674. logGlobal->error("Movement terminated abnormally");
  675. break;
  676. }
  677. bool gateStateChanging = false;
  678. //special handling for opening gate on from starting hex
  679. if (openGateAtHex.isValid() && openGateAtHex == start)
  680. gateStateChanging = true;
  681. else
  682. {
  683. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  684. {
  685. BattleHex hex = path.first[v];
  686. tiles.push_back(hex);
  687. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  688. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  689. {
  690. gateStateChanging = true;
  691. }
  692. //if we walked onto something, finalize this portion of stack movement check into obstacle
  693. if(!battle.battleGetAllObstaclesOnPos(hex, false).empty())
  694. obstacleHit = true;
  695. if (curStack->doubleWide())
  696. {
  697. BattleHex otherHex = curStack->occupiedHex(hex);
  698. //two hex creature hit obstacle by backside
  699. auto obstacle2 = battle.battleGetAllObstaclesOnPos(otherHex, false);
  700. if(otherHex.isValid() && !obstacle2.empty())
  701. obstacleHit = true;
  702. }
  703. if(!obstacleHit)
  704. passed.insert(hex);
  705. }
  706. }
  707. if (!tiles.empty())
  708. {
  709. //commit movement
  710. BattleStackMoved sm;
  711. sm.battleID = battle.getBattle()->getBattleID();
  712. sm.stack = curStack->unitId();
  713. sm.distance = path.second;
  714. sm.teleporting = false;
  715. sm.tilesToMove = tiles;
  716. gameHandler->sendAndApply(&sm);
  717. tiles.clear();
  718. }
  719. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  720. if (curStack->getPosition() != dest)
  721. {
  722. if(stackIsMoving && start != curStack->getPosition())
  723. {
  724. stackIsMoving = battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  725. passed.insert(curStack->getPosition());
  726. if(curStack->doubleWide())
  727. passed.insert(curStack->occupiedHex());
  728. }
  729. if (gateStateChanging)
  730. {
  731. if (curStack->getPosition() == openGateAtHex)
  732. {
  733. openGateAtHex = BattleHex();
  734. //only open gate if stack is still alive
  735. if (curStack->alive())
  736. {
  737. BattleUpdateGateState db;
  738. db.battleID = battle.getBattle()->getBattleID();
  739. db.state = EGateState::OPENED;
  740. gameHandler->sendAndApply(&db);
  741. }
  742. }
  743. else if (curStack->getPosition() == gateMayCloseAtHex)
  744. {
  745. gateMayCloseAtHex = BattleHex();
  746. owner->updateGateState(battle);
  747. }
  748. }
  749. }
  750. else
  751. //movement finished normally: we reached destination
  752. stackIsMoving = false;
  753. }
  754. }
  755. //handle last hex separately for deviation
  756. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  757. {
  758. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  759. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  760. passed.clear(); //Just empty passed, obstacles will handled automatically
  761. }
  762. if(dest == start) //If dest is equal to start, then we should handle obstacles for it anyway
  763. passed.clear(); //Just empty passed, obstacles will handled automatically
  764. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  765. battle.handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  766. return ret;
  767. }
  768. void BattleActionProcessor::makeAttack(const CBattleInfoCallback & battle, const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  769. {
  770. if(first && !counter)
  771. handleAttackBeforeCasting(battle, ranged, attacker, defender);
  772. FireShieldInfo fireShield;
  773. BattleAttack bat;
  774. BattleLogMessage blm;
  775. blm.battleID = battle.getBattle()->getBattleID();
  776. bat.battleID = battle.getBattle()->getBattleID();
  777. bat.attackerChanges.battleID = battle.getBattle()->getBattleID();
  778. bat.stackAttacking = attacker->unitId();
  779. bat.tile = targetHex;
  780. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  781. if(ranged)
  782. bat.flags |= BattleAttack::SHOT;
  783. if(counter)
  784. bat.flags |= BattleAttack::COUNTER;
  785. const int attackerLuck = attacker->luckVal();
  786. if(attackerLuck > 0)
  787. {
  788. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  789. size_t diceIndex = std::min<size_t>(diceSize.size(), attackerLuck) - 1; // array index, so 0-indexed
  790. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  791. bat.flags |= BattleAttack::LUCKY;
  792. }
  793. if(attackerLuck < 0)
  794. {
  795. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  796. size_t diceIndex = std::min<size_t>(diceSize.size(), -attackerLuck) - 1; // array index, so 0-indexed
  797. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  798. bat.flags |= BattleAttack::UNLUCKY;
  799. }
  800. if (gameHandler->getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  801. {
  802. bat.flags |= BattleAttack::DEATH_BLOW;
  803. }
  804. const auto * owner = battle.battleGetFightingHero(attacker->unitSide());
  805. if(owner)
  806. {
  807. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, BonusSubtypeID(attacker->creatureId()));
  808. if (chance > gameHandler->getRandomGenerator().nextInt(99))
  809. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  810. }
  811. battle::HealInfo healInfo;
  812. // only primary target
  813. if(defender->alive())
  814. applyBattleEffects(battle, bat, attackerState, fireShield, defender, healInfo, distance, false);
  815. //multiple-hex normal attack
  816. std::set<const CStack*> attackedCreatures = battle.getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  817. for(const CStack * stack : attackedCreatures)
  818. {
  819. if(stack != defender && stack->alive()) //do not hit same stack twice
  820. applyBattleEffects(battle, bat, attackerState, fireShield, stack, healInfo, distance, true);
  821. }
  822. std::shared_ptr<const Bonus> bonus = attacker->getFirstBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  823. if(bonus && ranged && bonus->subtype.hasValue()) //TODO: make it work in melee?
  824. {
  825. //this is need for displaying hit animation
  826. bat.flags |= BattleAttack::SPELL_LIKE;
  827. bat.spellID = bonus->subtype.as<SpellID>();
  828. //TODO: should spell override creature`s projectile?
  829. auto spell = bat.spellID.toSpell();
  830. battle::Target target;
  831. target.emplace_back(defender, targetHex);
  832. spells::BattleCast event(&battle, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  833. event.setSpellLevel(bonus->val);
  834. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  835. //TODO: get exact attacked hex for defender
  836. for(const CStack * stack : attackedCreatures)
  837. {
  838. if(stack != defender && stack->alive()) //do not hit same stack twice
  839. {
  840. applyBattleEffects(battle, bat, attackerState, fireShield, stack, healInfo, distance, true);
  841. }
  842. }
  843. //now add effect info for all attacked stacks
  844. for (BattleStackAttacked & bsa : bat.bsa)
  845. {
  846. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  847. {
  848. //this is need for displaying affect animation
  849. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  850. bsa.spellID = bonus->subtype.as<SpellID>();
  851. }
  852. }
  853. }
  854. attackerState->afterAttack(ranged, counter);
  855. {
  856. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  857. attackerState->save(info.data);
  858. bat.attackerChanges.changedStacks.push_back(info);
  859. }
  860. if (healInfo.healedHealthPoints > 0)
  861. bat.flags |= BattleAttack::LIFE_DRAIN;
  862. for (BattleStackAttacked & bsa : bat.bsa)
  863. bsa.battleID = battle.getBattle()->getBattleID();
  864. gameHandler->sendAndApply(&bat);
  865. {
  866. const bool multipleTargets = bat.bsa.size() > 1;
  867. int64_t totalDamage = 0;
  868. int32_t totalKills = 0;
  869. for(const BattleStackAttacked & bsa : bat.bsa)
  870. {
  871. totalDamage += bsa.damageAmount;
  872. totalKills += bsa.killedAmount;
  873. }
  874. addGenericDamageLog(blm, attackerState, totalDamage);
  875. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  876. }
  877. // drain life effect (as well as log entry) must be applied after the attack
  878. if(healInfo.healedHealthPoints > 0)
  879. {
  880. addGenericDrainedLifeLog(blm, attackerState, defender, healInfo.healedHealthPoints);
  881. addGenericResurrectedLog(blm, attackerState, defender, healInfo.resurrectedCount);
  882. }
  883. if(!fireShield.empty())
  884. {
  885. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  886. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  887. int64_t totalDamage = 0;
  888. for(const auto & item : fireShield)
  889. {
  890. const CStack * actor = item.first;
  891. int64_t rawDamage = item.second;
  892. const CGHeroInstance * actorOwner = battle.battleGetFightingHero(actor->unitSide());
  893. if(actorOwner)
  894. {
  895. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  896. }
  897. else
  898. {
  899. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  900. }
  901. totalDamage+=rawDamage;
  902. //FIXME: add custom effect on actor
  903. }
  904. if (totalDamage > 0)
  905. {
  906. BattleStackAttacked bsa;
  907. bsa.battleID = battle.getBattle()->getBattleID();
  908. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  909. bsa.stackAttacked = attacker->unitId(); //invert
  910. bsa.attackerID = defender->unitId();
  911. bsa.damageAmount = totalDamage;
  912. attacker->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  913. StacksInjured pack;
  914. pack.battleID = battle.getBattle()->getBattleID();
  915. pack.stacks.push_back(bsa);
  916. gameHandler->sendAndApply(&pack);
  917. // TODO: this is already implemented in Damage::describeEffect()
  918. {
  919. MetaString text;
  920. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  921. text.replaceName(SpellID(SpellID::FIRE_SHIELD));
  922. text.replaceNumber(totalDamage);
  923. blm.lines.push_back(std::move(text));
  924. }
  925. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  926. }
  927. }
  928. gameHandler->sendAndApply(&blm);
  929. handleAfterAttackCasting(battle, ranged, attacker, defender);
  930. }
  931. void BattleActionProcessor::attackCasting(const CBattleInfoCallback & battle, bool ranged, BonusType attackMode, const battle::Unit * attacker, const CStack * defender)
  932. {
  933. if(attacker->hasBonusOfType(attackMode))
  934. {
  935. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  936. std::set<SpellID> spellsToCast = getSpellsForAttackCasting(spells, defender);
  937. for(SpellID spellID : spellsToCast)
  938. {
  939. bool castMe = false;
  940. if(!defender->alive())
  941. {
  942. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  943. return;
  944. }
  945. int32_t spellLevel = 0;
  946. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, BonusSubtypeID(spellID)));
  947. for(const auto & sf : *spellsByType)
  948. {
  949. int meleeRanged;
  950. vstd::amax(spellLevel, sf->additionalInfo[0]);
  951. meleeRanged = sf->additionalInfo[1];
  952. if (meleeRanged == CAddInfo::NONE || meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  953. castMe = true;
  954. }
  955. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, BonusSubtypeID(spellID))));
  956. vstd::amin(chance, 100);
  957. const CSpell * spell = SpellID(spellID).toSpell();
  958. spells::AbilityCaster caster(attacker, spellLevel);
  959. spells::Target target;
  960. target.emplace_back(defender);
  961. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  962. auto m = spell->battleMechanics(&parameters);
  963. spells::detail::ProblemImpl ignored;
  964. if(!m->canBeCastAt(target, ignored))
  965. continue;
  966. //check if spell should be cast (probability handling)
  967. if(gameHandler->getRandomGenerator().nextInt(99) >= chance)
  968. continue;
  969. //casting
  970. if(castMe)
  971. {
  972. parameters.cast(gameHandler->spellEnv, target);
  973. }
  974. }
  975. }
  976. }
  977. std::set<SpellID> BattleActionProcessor::getSpellsForAttackCasting(TConstBonusListPtr spells, const CStack *defender)
  978. {
  979. std::set<SpellID> spellsToCast;
  980. constexpr int unlayeredItemsInternalLayer = -1;
  981. std::map<int, std::vector<std::shared_ptr<Bonus>>> spellsWithBackupLayers;
  982. for(int i = 0; i < spells->size(); i++)
  983. {
  984. std::shared_ptr<Bonus> bonus = spells->operator[](i);
  985. int layer = bonus->additionalInfo[2];
  986. vstd::amax(layer, -1);
  987. spellsWithBackupLayers[layer].push_back(bonus);
  988. }
  989. auto addSpellsFromLayer = [&](int layer) -> void
  990. {
  991. assert(spellsWithBackupLayers.find(layer) != spellsWithBackupLayers.end());
  992. for(const auto & spell : spellsWithBackupLayers[layer])
  993. {
  994. if (spell->subtype.as<SpellID>() != SpellID())
  995. spellsToCast.insert(spell->subtype.as<SpellID>());
  996. else
  997. logGlobal->error("Invalid spell to cast during attack!");
  998. }
  999. };
  1000. if(spellsWithBackupLayers.find(unlayeredItemsInternalLayer) != spellsWithBackupLayers.end())
  1001. {
  1002. addSpellsFromLayer(unlayeredItemsInternalLayer);
  1003. spellsWithBackupLayers.erase(unlayeredItemsInternalLayer);
  1004. }
  1005. for(auto item : spellsWithBackupLayers)
  1006. {
  1007. bool areCurrentLayerSpellsApplied = std::all_of(item.second.begin(), item.second.end(),
  1008. [&](const std::shared_ptr<Bonus> spell)
  1009. {
  1010. std::vector<SpellID> activeSpells = defender->activeSpells();
  1011. return vstd::find(activeSpells, spell->subtype.as<SpellID>()) != activeSpells.end();
  1012. });
  1013. if(!areCurrentLayerSpellsApplied || item.first == spellsWithBackupLayers.rbegin()->first)
  1014. {
  1015. addSpellsFromLayer(item.first);
  1016. break;
  1017. }
  1018. }
  1019. return spellsToCast;
  1020. }
  1021. void BattleActionProcessor::handleAttackBeforeCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1022. {
  1023. attackCasting(battle, ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  1024. }
  1025. void BattleActionProcessor::handleDeathStare(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1026. {
  1027. // mechanics of Death Stare as in H3:
  1028. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  1029. //original formula x = min(x, (gorgons_count + 9)/10);
  1030. /* mechanics of Accurate Shot as in HotA:
  1031. * each creature in an attacking stack has a X% chance of killing a creature in the attacked squad,
  1032. * but the total number of killed creatures cannot be more than (number of creatures in an attacking squad) * X/100 (rounded up).
  1033. * X = 3 multiplier for shooting without penalty and X = 2 if shooting with penalty. Ability doesn't work if shooting at creatures behind walls.
  1034. */
  1035. auto subtype = BonusCustomSubtype::deathStareGorgon;
  1036. if (ranged)
  1037. {
  1038. bool rangePenalty = battle.battleHasDistancePenalty(attacker, attacker->getPosition(), defender->getPosition());
  1039. bool obstaclePenalty = battle.battleHasWallPenalty(attacker, attacker->getPosition(), defender->getPosition());
  1040. if(rangePenalty)
  1041. {
  1042. if(obstaclePenalty)
  1043. subtype = BonusCustomSubtype::deathStareRangeObstaclePenalty;
  1044. else
  1045. subtype = BonusCustomSubtype::deathStareRangePenalty;
  1046. }
  1047. else
  1048. {
  1049. if(obstaclePenalty)
  1050. subtype = BonusCustomSubtype::deathStareObstaclePenalty;
  1051. else
  1052. subtype = BonusCustomSubtype::deathStareNoRangePenalty;
  1053. }
  1054. }
  1055. int singleCreatureKillChancePercent = attacker->valOfBonuses(BonusType::DEATH_STARE, subtype);
  1056. double chanceToKill = singleCreatureKillChancePercent / 100.0;
  1057. vstd::amin(chanceToKill, 1); //cap at 100%
  1058. int killedCreatures = gameHandler->getRandomGenerator().nextBinomialInt(attacker->getCount(), chanceToKill);
  1059. int maxToKill = vstd::divideAndCeil(attacker->getCount() * singleCreatureKillChancePercent, 100);
  1060. vstd::amin(killedCreatures, maxToKill);
  1061. killedCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, BonusCustomSubtype::deathStareCommander)) / defender->level();
  1062. if(killedCreatures)
  1063. {
  1064. //TODO: death stare or accurate shot was not originally available for multiple-hex attacks, but...
  1065. SpellID spellID = SpellID(SpellID::DEATH_STARE); //also used as fallback spell for ACCURATE_SHOT
  1066. auto bonus = attacker->getBonus(Selector::typeSubtype(BonusType::DEATH_STARE, subtype));
  1067. if(bonus && bonus->additionalInfo[0] != SpellID::NONE)
  1068. spellID = SpellID(bonus->additionalInfo[0]);
  1069. const CSpell * spell = spellID.toSpell();
  1070. spells::AbilityCaster caster(attacker, 0);
  1071. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1072. spells::Target target;
  1073. target.emplace_back(defender);
  1074. parameters.setEffectValue(killedCreatures);
  1075. parameters.cast(gameHandler->spellEnv, target);
  1076. }
  1077. }
  1078. void BattleActionProcessor::handleAfterAttackCasting(const CBattleInfoCallback & battle, bool ranged, const CStack * attacker, const CStack * defender)
  1079. {
  1080. if(!attacker->alive() || !defender->alive()) // can be already dead
  1081. return;
  1082. attackCasting(battle, ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  1083. if(!defender->alive())
  1084. {
  1085. //don't try death stare or acid breath on dead stack (crash!)
  1086. return;
  1087. }
  1088. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  1089. handleDeathStare(battle, ranged, attacker, defender);
  1090. if(!defender->alive())
  1091. return;
  1092. int64_t acidDamage = 0;
  1093. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  1094. for(const auto & b : *acidBreath)
  1095. {
  1096. if(b->additionalInfo[0] > gameHandler->getRandomGenerator().nextInt(99))
  1097. acidDamage += b->val;
  1098. }
  1099. if(acidDamage > 0)
  1100. {
  1101. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  1102. spells::AbilityCaster caster(attacker, 0);
  1103. spells::BattleCast parameters(&battle, &caster, spells::Mode::PASSIVE, spell);
  1104. spells::Target target;
  1105. target.emplace_back(defender);
  1106. parameters.setEffectValue(acidDamage * attacker->getCount());
  1107. parameters.cast(gameHandler->spellEnv, target);
  1108. }
  1109. if(!defender->alive())
  1110. return;
  1111. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  1112. {
  1113. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  1114. vstd::amin(chanceToTrigger, 1); //cap at 100%
  1115. if(gameHandler->getRandomGenerator().nextDouble(0, 1) > chanceToTrigger)
  1116. return;
  1117. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  1118. if(defender->unitType()->getIndex() == bonusAdditionalInfo ||
  1119. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  1120. return;
  1121. battle::UnitInfo resurrectInfo;
  1122. resurrectInfo.id = battle.battleNextUnitId();
  1123. resurrectInfo.summoned = false;
  1124. resurrectInfo.position = defender->getPosition();
  1125. resurrectInfo.side = defender->unitSide();
  1126. if(bonusAdditionalInfo != CAddInfo::NONE)
  1127. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  1128. else
  1129. resurrectInfo.type = attacker->creatureId();
  1130. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerHealth))
  1131. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  1132. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), BonusCustomSubtype::transmutationPerUnit))
  1133. resurrectInfo.count = defender->getCount();
  1134. else
  1135. return; //wrong subtype
  1136. BattleUnitsChanged addUnits;
  1137. addUnits.battleID = battle.getBattle()->getBattleID();
  1138. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  1139. resurrectInfo.save(addUnits.changedStacks.back().data);
  1140. BattleUnitsChanged removeUnits;
  1141. removeUnits.battleID = battle.getBattle()->getBattleID();
  1142. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  1143. gameHandler->sendAndApply(&removeUnits);
  1144. gameHandler->sendAndApply(&addUnits);
  1145. // send empty event to client
  1146. // temporary(?) workaround to force animations to trigger
  1147. StacksInjured fakeEvent;
  1148. fakeEvent.battleID = battle.getBattle()->getBattleID();
  1149. gameHandler->sendAndApply(&fakeEvent);
  1150. }
  1151. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) || attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount))
  1152. {
  1153. double chanceToTrigger = 0;
  1154. int amountToDie = 0;
  1155. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage)) //killing by percentage
  1156. {
  1157. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillPercentage) / 100.0f;
  1158. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillPercentage)))->additionalInfo[0];
  1159. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  1160. }
  1161. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount)) //killing by count
  1162. {
  1163. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, BonusCustomSubtype::destructionKillAmount) / 100.0f;
  1164. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(BonusCustomSubtype::destructionKillAmount)))->additionalInfo[0];
  1165. }
  1166. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  1167. if(gameHandler->getRandomGenerator().nextDouble(0, 1) > chanceToTrigger)
  1168. return;
  1169. BattleStackAttacked bsa;
  1170. bsa.attackerID = -1;
  1171. bsa.stackAttacked = defender->unitId();
  1172. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  1173. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  1174. bsa.spellID = SpellID::SLAYER;
  1175. defender->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  1176. StacksInjured si;
  1177. si.battleID = battle.getBattle()->getBattleID();
  1178. si.stacks.push_back(bsa);
  1179. gameHandler->sendAndApply(&si);
  1180. sendGenericKilledLog(battle, defender, bsa.killedAmount, false);
  1181. }
  1182. }
  1183. void BattleActionProcessor::applyBattleEffects(const CBattleInfoCallback & battle, BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, battle::HealInfo & healInfo, int distance, bool secondary) const
  1184. {
  1185. BattleStackAttacked bsa;
  1186. if(secondary)
  1187. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  1188. bsa.attackerID = attackerState->unitId();
  1189. bsa.stackAttacked = def->unitId();
  1190. {
  1191. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  1192. bai.deathBlow = bat.deathBlow();
  1193. bai.doubleDamage = bat.ballistaDoubleDmg();
  1194. bai.luckyStrike = bat.lucky();
  1195. bai.unluckyStrike = bat.unlucky();
  1196. auto range = battle.calculateDmgRange(bai);
  1197. bsa.damageAmount = battle.getBattle()->getActualDamage(range.damage, attackerState->getCount(), gameHandler->getRandomGenerator());
  1198. CStack::prepareAttacked(bsa, gameHandler->getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  1199. }
  1200. //life drain handling
  1201. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  1202. {
  1203. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1204. healInfo += attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1205. }
  1206. //soul steal handling
  1207. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1208. {
  1209. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1210. //try to use permanent first, use only one of two
  1211. for(const auto & subtype : { BonusCustomSubtype::soulStealBattle, BonusCustomSubtype::soulStealPermanent})
  1212. {
  1213. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1214. {
  1215. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1216. bool permanent = subtype == BonusCustomSubtype::soulStealPermanent;
  1217. healInfo += attackerState->heal(toHeal, EHealLevel::OVERHEAL, (permanent ? EHealPower::PERMANENT : EHealPower::ONE_BATTLE));
  1218. break;
  1219. }
  1220. }
  1221. }
  1222. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1223. //fire shield handling
  1224. if(!bat.shot() &&
  1225. !def->isClone() &&
  1226. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1227. !attackerState->hasBonusOfType(BonusType::SPELL_SCHOOL_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1228. !attackerState->hasBonusOfType(BonusType::NEGATIVE_EFFECTS_IMMUNITY, BonusSubtypeID(SpellSchool::FIRE)) &&
  1229. attackerState->valOfBonuses(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(SpellSchool::FIRE)) < 100 &&
  1230. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1231. )
  1232. {
  1233. //TODO: use damage with bonus but without penalties
  1234. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1235. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1236. }
  1237. }
  1238. void BattleActionProcessor::sendGenericKilledLog(const CBattleInfoCallback & battle, const CStack * defender, int32_t killed, bool multiple)
  1239. {
  1240. if(killed > 0)
  1241. {
  1242. BattleLogMessage blm;
  1243. blm.battleID = battle.getBattle()->getBattleID();
  1244. addGenericKilledLog(blm, defender, killed, multiple);
  1245. gameHandler->sendAndApply(&blm);
  1246. }
  1247. }
  1248. void BattleActionProcessor::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple) const
  1249. {
  1250. if(killed > 0)
  1251. {
  1252. MetaString line;
  1253. if (killed > 1)
  1254. {
  1255. line.appendTextID("core.genrltxt.379"); // %d %s perished
  1256. line.replaceNumber(killed);
  1257. }
  1258. else
  1259. line.appendTextID("core.genrltxt.378"); // One %s perishes
  1260. if (multiple)
  1261. {
  1262. if (killed > 1)
  1263. line.replaceTextID("core.genrltxt.43"); // creatures
  1264. else
  1265. line.replaceTextID("core.genrltxt.42"); // creature
  1266. }
  1267. else
  1268. line.replaceName(defender->unitType()->getId(), killed);
  1269. blm.lines.push_back(line);
  1270. }
  1271. }
  1272. void BattleActionProcessor::addGenericDamageLog(BattleLogMessage& blm, const std::shared_ptr<battle::CUnitState> &attackerState, int64_t damageDealt) const
  1273. {
  1274. MetaString text;
  1275. attackerState->addText(text, EMetaText::GENERAL_TXT, 376);
  1276. attackerState->addNameReplacement(text);
  1277. text.replaceNumber(damageDealt);
  1278. blm.lines.push_back(std::move(text));
  1279. }
  1280. void BattleActionProcessor::addGenericDrainedLifeLog(BattleLogMessage& blm, const std::shared_ptr<battle::CUnitState>& attackerState, const CStack* defender, int64_t drainedLife) const
  1281. {
  1282. MetaString text;
  1283. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  1284. attackerState->addNameReplacement(text);
  1285. text.replaceNumber(drainedLife);
  1286. defender->addNameReplacement(text);
  1287. blm.lines.push_back(std::move(text));
  1288. }
  1289. void BattleActionProcessor::addGenericResurrectedLog(BattleLogMessage& blm, const std::shared_ptr<battle::CUnitState>& attackerState, const CStack* defender, int64_t resurrected) const
  1290. {
  1291. if (resurrected > 0)
  1292. {
  1293. auto text = blm.lines.back().toString();
  1294. text.pop_back(); // erase '.' at the end of line with life drain info
  1295. MetaString ms = MetaString::createFromRawString(text);
  1296. if (resurrected == 1)
  1297. {
  1298. ms.appendLocalString(EMetaText::GENERAL_TXT, 363); // "\n and one rises from the dead."
  1299. }
  1300. else
  1301. {
  1302. ms.appendLocalString(EMetaText::GENERAL_TXT, 364); // "\n and %d rise from the dead."
  1303. ms.replaceNumber(resurrected);
  1304. }
  1305. blm.lines[blm.lines.size() - 1] = std::move(ms);
  1306. }
  1307. }
  1308. bool BattleActionProcessor::makeAutomaticBattleAction(const CBattleInfoCallback & battle, const BattleAction & ba)
  1309. {
  1310. return makeBattleActionImpl(battle, ba);
  1311. }
  1312. bool BattleActionProcessor::makePlayerBattleAction(const CBattleInfoCallback & battle, PlayerColor player, const BattleAction &ba)
  1313. {
  1314. if (ba.side != BattleSide::ATTACKER && ba.side != BattleSide::DEFENDER && gameHandler->complain("Can not make action - invalid battle side!"))
  1315. return false;
  1316. if(battle.battleGetTacticDist() != 0)
  1317. {
  1318. if(!ba.isTacticsAction())
  1319. {
  1320. gameHandler->complain("Can not make actions while in tactics mode!");
  1321. return false;
  1322. }
  1323. if(player != battle.sideToPlayer(ba.side))
  1324. {
  1325. gameHandler->complain("Can not make actions in battles you are not part of!");
  1326. return false;
  1327. }
  1328. }
  1329. else
  1330. {
  1331. auto active = battle.battleActiveUnit();
  1332. if(!active)
  1333. {
  1334. gameHandler->complain("No active unit in battle!");
  1335. return false;
  1336. }
  1337. if (ba.isUnitAction() && ba.stackNumber != active->unitId())
  1338. {
  1339. gameHandler->complain("Can not make actions - stack is not active!");
  1340. return false;
  1341. }
  1342. auto unitOwner = battle.battleGetOwner(active);
  1343. if(player != unitOwner)
  1344. {
  1345. gameHandler->complain("Can not make actions in battles you are not part of!");
  1346. return false;
  1347. }
  1348. }
  1349. return makeBattleActionImpl(battle, ba);
  1350. }