BattleActionProcessor.cpp 44 KB

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