BattleActionProcessor.cpp 45 KB

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