BattleActionProcessor.cpp 46 KB

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