BattleActionProcessor.cpp 52 KB

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