BattleActionProcessor.cpp 52 KB

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