BattleActionProcessor.cpp 58 KB

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