BattleActionProcessor.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  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, PrimarySkill::DEFENSE, BonusValueType::PERCENT_TO_ALL);
  133. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE), -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  134. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  135. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, 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) < 0)
  334. spellID = gameHandler->battleGetRandomStackSpell(gameHandler->getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  335. if (spellID < 0)
  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::NO_ACTION:
  417. return doEmptyAction(ba);
  418. case EActionType::END_TACTIC_PHASE:
  419. return doEndTacticsAction(ba);
  420. case EActionType::RETREAT:
  421. return doRetreatAction(ba);
  422. case EActionType::SURRENDER:
  423. return doSurrenderAction(ba);
  424. case EActionType::HERO_SPELL:
  425. return doHeroSpellAction(ba);
  426. case EActionType::WALK:
  427. return doWalkAction(ba);
  428. case EActionType::WAIT:
  429. return doWaitAction(ba);
  430. case EActionType::DEFEND:
  431. return doDefendAction(ba);
  432. case EActionType::WALK_AND_ATTACK:
  433. return doAttackAction(ba);
  434. case EActionType::SHOOT:
  435. return doShootAction(ba);
  436. case EActionType::CATAPULT:
  437. return doCatapultAction(ba);
  438. case EActionType::MONSTER_SPELL:
  439. return doUnitSpellAction(ba);
  440. case EActionType::STACK_HEAL:
  441. return doHealAction(ba);
  442. }
  443. gameHandler->complain("Unrecognized action type received!!");
  444. return false;
  445. }
  446. bool BattleActionProcessor::makeBattleActionImpl(const BattleAction &ba)
  447. {
  448. logGlobal->trace("Making action: %s", ba.toString());
  449. const CStack * stack = gameHandler->gameState()->curB->battleGetStackByID(ba.stackNumber);
  450. StartAction startAction(ba);
  451. gameHandler->sendAndApply(&startAction);
  452. bool result = dispatchBattleAction(ba);
  453. EndAction endAction;
  454. gameHandler->sendAndApply(&endAction);
  455. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  456. gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *stack);
  457. return result;
  458. }
  459. int BattleActionProcessor::moveStack(int stack, BattleHex dest)
  460. {
  461. int ret = 0;
  462. const CStack *curStack = gameHandler->battleGetStackByID(stack);
  463. const CStack *stackAtEnd = gameHandler->gameState()->curB->battleGetStackByPos(dest);
  464. assert(curStack);
  465. assert(dest < GameConstants::BFIELD_SIZE);
  466. if (gameHandler->gameState()->curB->tacticDistance)
  467. {
  468. assert(gameHandler->gameState()->curB->isInTacticRange(dest));
  469. }
  470. auto start = curStack->getPosition();
  471. if (start == dest)
  472. return 0;
  473. //initing necessary tables
  474. auto accessibility = gameHandler->getAccesibility(curStack);
  475. std::set<BattleHex> passed;
  476. //Ignore obstacles on starting position
  477. passed.insert(curStack->getPosition());
  478. if(curStack->doubleWide())
  479. passed.insert(curStack->occupiedHex());
  480. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  481. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  482. {
  483. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  484. if(accessibility.accessible(shifted, curStack))
  485. dest = shifted;
  486. }
  487. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  488. {
  489. gameHandler->complain("Given destination is not accessible!");
  490. return 0;
  491. }
  492. bool canUseGate = false;
  493. auto dbState = gameHandler->gameState()->curB->si.gateState;
  494. if(gameHandler->battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  495. dbState != EGateState::DESTROYED &&
  496. dbState != EGateState::BLOCKED)
  497. {
  498. canUseGate = true;
  499. }
  500. std::pair< std::vector<BattleHex>, int > path = gameHandler->gameState()->curB->getPath(start, dest, curStack);
  501. ret = path.second;
  502. int creSpeed = curStack->speed(0, true);
  503. if (gameHandler->gameState()->curB->tacticDistance > 0 && creSpeed > 0)
  504. creSpeed = GameConstants::BFIELD_SIZE;
  505. bool hasWideMoat = vstd::contains_if(gameHandler->battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  506. {
  507. return obst->obstacleType == CObstacleInstance::MOAT;
  508. });
  509. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  510. {
  511. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  512. return true;
  513. if (hex == ESiegeHex::GATE_OUTER)
  514. return true;
  515. if (hex == ESiegeHex::GATE_INNER)
  516. return true;
  517. return false;
  518. };
  519. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  520. {
  521. if (isGateDrawbridgeHex(hex))
  522. return true;
  523. if (curStack->doubleWide())
  524. {
  525. BattleHex otherHex = curStack->occupiedHex(hex);
  526. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  527. return true;
  528. }
  529. return false;
  530. };
  531. if (curStack->hasBonusOfType(BonusType::FLYING))
  532. {
  533. if (path.second <= creSpeed && path.first.size() > 0)
  534. {
  535. if (canUseGate && dbState != EGateState::OPENED &&
  536. occupyGateDrawbridgeHex(dest))
  537. {
  538. BattleUpdateGateState db;
  539. db.state = EGateState::OPENED;
  540. gameHandler->sendAndApply(&db);
  541. }
  542. //inform clients about move
  543. BattleStackMoved sm;
  544. sm.stack = curStack->unitId();
  545. std::vector<BattleHex> tiles;
  546. tiles.push_back(path.first[0]);
  547. sm.tilesToMove = tiles;
  548. sm.distance = path.second;
  549. sm.teleporting = false;
  550. gameHandler->sendAndApply(&sm);
  551. }
  552. }
  553. else //for non-flying creatures
  554. {
  555. std::vector<BattleHex> tiles;
  556. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  557. int v = (int)path.first.size()-1;
  558. path.first.push_back(start);
  559. // check if gate need to be open or closed at some point
  560. BattleHex openGateAtHex, gateMayCloseAtHex;
  561. if (canUseGate)
  562. {
  563. for (int i = (int)path.first.size()-1; i >= 0; i--)
  564. {
  565. auto needOpenGates = [&](BattleHex hex) -> bool
  566. {
  567. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  568. return true;
  569. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == ESiegeHex::GATE_OUTER)
  570. return true;
  571. else if (hex == ESiegeHex::GATE_OUTER || hex == ESiegeHex::GATE_INNER)
  572. return true;
  573. return false;
  574. };
  575. auto hex = path.first[i];
  576. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  577. {
  578. if (needOpenGates(hex))
  579. openGateAtHex = path.first[i+1];
  580. //TODO we need find batter way to handle double-wide stacks
  581. //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.
  582. if (curStack->doubleWide())
  583. {
  584. BattleHex otherHex = curStack->occupiedHex(hex);
  585. if (otherHex.isValid() && needOpenGates(otherHex))
  586. openGateAtHex = path.first[i+2];
  587. }
  588. //gate may be opened and then closed during stack movement, but not other way around
  589. if (openGateAtHex.isValid())
  590. dbState = EGateState::OPENED;
  591. }
  592. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  593. {
  594. if (hex == ESiegeHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  595. {
  596. gateMayCloseAtHex = path.first[i-1];
  597. }
  598. if (hasWideMoat)
  599. {
  600. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  601. {
  602. gateMayCloseAtHex = path.first[i-1];
  603. }
  604. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 &&
  605. path.first[i-1] != ESiegeHex::GATE_INNER &&
  606. path.first[i-1] != ESiegeHex::GATE_BRIDGE)
  607. {
  608. gateMayCloseAtHex = path.first[i-1];
  609. }
  610. }
  611. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_INNER)
  612. {
  613. gateMayCloseAtHex = path.first[i-1];
  614. }
  615. }
  616. }
  617. }
  618. bool stackIsMoving = true;
  619. while(stackIsMoving)
  620. {
  621. if (v<tilesToMove)
  622. {
  623. logGlobal->error("Movement terminated abnormally");
  624. break;
  625. }
  626. bool gateStateChanging = false;
  627. //special handling for opening gate on from starting hex
  628. if (openGateAtHex.isValid() && openGateAtHex == start)
  629. gateStateChanging = true;
  630. else
  631. {
  632. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  633. {
  634. BattleHex hex = path.first[v];
  635. tiles.push_back(hex);
  636. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  637. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  638. {
  639. gateStateChanging = true;
  640. }
  641. //if we walked onto something, finalize this portion of stack movement check into obstacle
  642. if(!gameHandler->battleGetAllObstaclesOnPos(hex, false).empty())
  643. obstacleHit = true;
  644. if (curStack->doubleWide())
  645. {
  646. BattleHex otherHex = curStack->occupiedHex(hex);
  647. //two hex creature hit obstacle by backside
  648. auto obstacle2 = gameHandler->battleGetAllObstaclesOnPos(otherHex, false);
  649. if(otherHex.isValid() && !obstacle2.empty())
  650. obstacleHit = true;
  651. }
  652. if(!obstacleHit)
  653. passed.insert(hex);
  654. }
  655. }
  656. if (!tiles.empty())
  657. {
  658. //commit movement
  659. BattleStackMoved sm;
  660. sm.stack = curStack->unitId();
  661. sm.distance = path.second;
  662. sm.teleporting = false;
  663. sm.tilesToMove = tiles;
  664. gameHandler->sendAndApply(&sm);
  665. tiles.clear();
  666. }
  667. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  668. if (curStack->getPosition() != dest)
  669. {
  670. if(stackIsMoving && start != curStack->getPosition())
  671. {
  672. stackIsMoving = gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  673. passed.insert(curStack->getPosition());
  674. if(curStack->doubleWide())
  675. passed.insert(curStack->occupiedHex());
  676. }
  677. if (gateStateChanging)
  678. {
  679. if (curStack->getPosition() == openGateAtHex)
  680. {
  681. openGateAtHex = BattleHex();
  682. //only open gate if stack is still alive
  683. if (curStack->alive())
  684. {
  685. BattleUpdateGateState db;
  686. db.state = EGateState::OPENED;
  687. gameHandler->sendAndApply(&db);
  688. }
  689. }
  690. else if (curStack->getPosition() == gateMayCloseAtHex)
  691. {
  692. gateMayCloseAtHex = BattleHex();
  693. owner->updateGateState();
  694. }
  695. }
  696. }
  697. else
  698. //movement finished normally: we reached destination
  699. stackIsMoving = false;
  700. }
  701. }
  702. //handle last hex separately for deviation
  703. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  704. {
  705. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  706. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  707. passed.clear(); //Just empty passed, obstacles will handled automatically
  708. }
  709. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  710. gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  711. return ret;
  712. }
  713. void BattleActionProcessor::makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  714. {
  715. if(first && !counter)
  716. handleAttackBeforeCasting(ranged, attacker, defender);
  717. FireShieldInfo fireShield;
  718. BattleAttack bat;
  719. BattleLogMessage blm;
  720. bat.stackAttacking = attacker->unitId();
  721. bat.tile = targetHex;
  722. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  723. if(ranged)
  724. bat.flags |= BattleAttack::SHOT;
  725. if(counter)
  726. bat.flags |= BattleAttack::COUNTER;
  727. const int attackerLuck = attacker->luckVal();
  728. if(attackerLuck > 0)
  729. {
  730. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  731. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, attackerLuck);
  732. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  733. bat.flags |= BattleAttack::LUCKY;
  734. }
  735. if(attackerLuck < 0)
  736. {
  737. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  738. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, -attackerLuck);
  739. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  740. bat.flags |= BattleAttack::UNLUCKY;
  741. }
  742. if (gameHandler->getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  743. {
  744. bat.flags |= BattleAttack::DEATH_BLOW;
  745. }
  746. const auto * owner = gameHandler->gameState()->curB->getHero(attacker->unitOwner());
  747. if(owner)
  748. {
  749. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, attacker->creatureIndex());
  750. if (chance > gameHandler->getRandomGenerator().nextInt(99))
  751. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  752. }
  753. int64_t drainedLife = 0;
  754. // only primary target
  755. if(defender->alive())
  756. drainedLife += applyBattleEffects(bat, attackerState, fireShield, defender, distance, false);
  757. //multiple-hex normal attack
  758. std::set<const CStack*> attackedCreatures = gameHandler->gameState()->curB->getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  759. for(const CStack * stack : attackedCreatures)
  760. {
  761. if(stack != defender && stack->alive()) //do not hit same stack twice
  762. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  763. }
  764. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  765. if(bonus && ranged) //TODO: make it work in melee?
  766. {
  767. //this is need for displaying hit animation
  768. bat.flags |= BattleAttack::SPELL_LIKE;
  769. bat.spellID = SpellID(bonus->subtype);
  770. //TODO: should spell override creature`s projectile?
  771. auto spell = bat.spellID.toSpell();
  772. battle::Target target;
  773. target.emplace_back(defender, targetHex);
  774. spells::BattleCast event(gameHandler->gameState()->curB, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  775. event.setSpellLevel(bonus->val);
  776. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  777. //TODO: get exact attacked hex for defender
  778. for(const CStack * stack : attackedCreatures)
  779. {
  780. if(stack != defender && stack->alive()) //do not hit same stack twice
  781. {
  782. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  783. }
  784. }
  785. //now add effect info for all attacked stacks
  786. for (BattleStackAttacked & bsa : bat.bsa)
  787. {
  788. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  789. {
  790. //this is need for displaying affect animation
  791. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  792. bsa.spellID = SpellID(bonus->subtype);
  793. }
  794. }
  795. }
  796. attackerState->afterAttack(ranged, counter);
  797. {
  798. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  799. attackerState->save(info.data);
  800. bat.attackerChanges.changedStacks.push_back(info);
  801. }
  802. if (drainedLife > 0)
  803. bat.flags |= BattleAttack::LIFE_DRAIN;
  804. gameHandler->sendAndApply(&bat);
  805. {
  806. const bool multipleTargets = bat.bsa.size() > 1;
  807. int64_t totalDamage = 0;
  808. int32_t totalKills = 0;
  809. for(const BattleStackAttacked & bsa : bat.bsa)
  810. {
  811. totalDamage += bsa.damageAmount;
  812. totalKills += bsa.killedAmount;
  813. }
  814. {
  815. MetaString text;
  816. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  817. attacker->addNameReplacement(text);
  818. text.replaceNumber(totalDamage);
  819. blm.lines.push_back(text);
  820. }
  821. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  822. }
  823. // drain life effect (as well as log entry) must be applied after the attack
  824. if(drainedLife > 0)
  825. {
  826. MetaString text;
  827. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  828. attackerState->addNameReplacement(text, false);
  829. text.replaceNumber(drainedLife);
  830. defender->addNameReplacement(text, true);
  831. blm.lines.push_back(std::move(text));
  832. }
  833. if(!fireShield.empty())
  834. {
  835. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  836. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  837. int64_t totalDamage = 0;
  838. for(const auto & item : fireShield)
  839. {
  840. const CStack * actor = item.first;
  841. int64_t rawDamage = item.second;
  842. const CGHeroInstance * actorOwner = gameHandler->gameState()->curB->getHero(actor->unitOwner());
  843. if(actorOwner)
  844. {
  845. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  846. }
  847. else
  848. {
  849. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  850. }
  851. totalDamage+=rawDamage;
  852. //FIXME: add custom effect on actor
  853. }
  854. if (totalDamage > 0)
  855. {
  856. BattleStackAttacked bsa;
  857. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  858. bsa.stackAttacked = attacker->unitId(); //invert
  859. bsa.attackerID = defender->unitId();
  860. bsa.damageAmount = totalDamage;
  861. attacker->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  862. StacksInjured pack;
  863. pack.stacks.push_back(bsa);
  864. gameHandler->sendAndApply(&pack);
  865. // TODO: this is already implemented in Damage::describeEffect()
  866. {
  867. MetaString text;
  868. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  869. text.replaceLocalString(EMetaText::SPELL_NAME, SpellID::FIRE_SHIELD);
  870. text.replaceNumber(totalDamage);
  871. blm.lines.push_back(std::move(text));
  872. }
  873. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  874. }
  875. }
  876. gameHandler->sendAndApply(&blm);
  877. handleAfterAttackCasting(ranged, attacker, defender);
  878. }
  879. void BattleActionProcessor::attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  880. {
  881. if(attacker->hasBonusOfType(attackMode))
  882. {
  883. std::set<SpellID> spellsToCast;
  884. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  885. for(const auto & sf : *spells)
  886. {
  887. spellsToCast.insert(SpellID(sf->subtype));
  888. }
  889. for(SpellID spellID : spellsToCast)
  890. {
  891. bool castMe = false;
  892. if(!defender->alive())
  893. {
  894. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  895. return;
  896. }
  897. int32_t spellLevel = 0;
  898. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  899. for(const auto & sf : *spellsByType)
  900. {
  901. int meleeRanged;
  902. if(sf->additionalInfo.size() < 2)
  903. {
  904. // legacy format
  905. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  906. meleeRanged = sf->additionalInfo[0] / 1000;
  907. }
  908. else
  909. {
  910. vstd::amax(spellLevel, sf->additionalInfo[0]);
  911. meleeRanged = sf->additionalInfo[1];
  912. }
  913. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  914. castMe = true;
  915. }
  916. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  917. vstd::amin(chance, 100);
  918. const CSpell * spell = SpellID(spellID).toSpell();
  919. spells::AbilityCaster caster(attacker, spellLevel);
  920. spells::Target target;
  921. target.emplace_back(defender);
  922. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  923. auto m = spell->battleMechanics(&parameters);
  924. spells::detail::ProblemImpl ignored;
  925. if(!m->canBeCastAt(target, ignored))
  926. continue;
  927. //check if spell should be cast (probability handling)
  928. if(gameHandler->getRandomGenerator().nextInt(99) >= chance)
  929. continue;
  930. //casting
  931. if(castMe)
  932. {
  933. parameters.cast(gameHandler->spellEnv, target);
  934. }
  935. }
  936. }
  937. }
  938. void BattleActionProcessor::handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender)
  939. {
  940. attackCasting(ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  941. }
  942. void BattleActionProcessor::handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender)
  943. {
  944. if(!attacker->alive() || !defender->alive()) // can be already dead
  945. return;
  946. attackCasting(ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  947. if(!defender->alive())
  948. {
  949. //don't try death stare or acid breath on dead stack (crash!)
  950. return;
  951. }
  952. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  953. {
  954. // mechanics of Death Stare as in H3:
  955. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  956. //original formula x = min(x, (gorgons_count + 9)/10);
  957. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, 0) / 100.0f;
  958. vstd::amin(chanceToKill, 1); //cap at 100%
  959. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  960. int staredCreatures = distribution(gameHandler->getRandomGenerator().getStdGenerator());
  961. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  962. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  963. vstd::amin(staredCreatures, maxToKill);
  964. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, 1)) / defender->level();
  965. if(staredCreatures)
  966. {
  967. //TODO: death stare was not originally available for multiple-hex attacks, but...
  968. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  969. spells::AbilityCaster caster(attacker, 0);
  970. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  971. spells::Target target;
  972. target.emplace_back(defender);
  973. parameters.setEffectValue(staredCreatures);
  974. parameters.cast(gameHandler->spellEnv, target);
  975. }
  976. }
  977. if(!defender->alive())
  978. return;
  979. int64_t acidDamage = 0;
  980. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  981. for(const auto & b : *acidBreath)
  982. {
  983. if(b->additionalInfo[0] > gameHandler->getRandomGenerator().nextInt(99))
  984. acidDamage += b->val;
  985. }
  986. if(acidDamage > 0)
  987. {
  988. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  989. spells::AbilityCaster caster(attacker, 0);
  990. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  991. spells::Target target;
  992. target.emplace_back(defender);
  993. parameters.setEffectValue(acidDamage * attacker->getCount());
  994. parameters.cast(gameHandler->spellEnv, target);
  995. }
  996. if(!defender->alive())
  997. return;
  998. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  999. {
  1000. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  1001. vstd::amin(chanceToTrigger, 1); //cap at 100%
  1002. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1003. return;
  1004. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  1005. if(defender->unitType()->getId() == bonusAdditionalInfo ||
  1006. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  1007. return;
  1008. battle::UnitInfo resurrectInfo;
  1009. resurrectInfo.id = gameHandler->gameState()->curB->battleNextUnitId();
  1010. resurrectInfo.summoned = false;
  1011. resurrectInfo.position = defender->getPosition();
  1012. resurrectInfo.side = defender->unitSide();
  1013. if(bonusAdditionalInfo != CAddInfo::NONE)
  1014. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  1015. else
  1016. resurrectInfo.type = attacker->creatureId();
  1017. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), 0))
  1018. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  1019. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), 1))
  1020. resurrectInfo.count = defender->getCount();
  1021. else
  1022. return; //wrong subtype
  1023. BattleUnitsChanged addUnits;
  1024. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  1025. resurrectInfo.save(addUnits.changedStacks.back().data);
  1026. BattleUnitsChanged removeUnits;
  1027. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  1028. gameHandler->sendAndApply(&removeUnits);
  1029. gameHandler->sendAndApply(&addUnits);
  1030. }
  1031. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0) || attacker->hasBonusOfType(BonusType::DESTRUCTION, 1))
  1032. {
  1033. double chanceToTrigger = 0;
  1034. int amountToDie = 0;
  1035. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0)) //killing by percentage
  1036. {
  1037. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 0) / 100.0f;
  1038. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(0)))->additionalInfo[0];
  1039. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  1040. }
  1041. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 1)) //killing by count
  1042. {
  1043. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 1) / 100.0f;
  1044. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(1)))->additionalInfo[0];
  1045. }
  1046. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  1047. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  1048. return;
  1049. BattleStackAttacked bsa;
  1050. bsa.attackerID = -1;
  1051. bsa.stackAttacked = defender->unitId();
  1052. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  1053. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  1054. bsa.spellID = SpellID::SLAYER;
  1055. defender->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  1056. StacksInjured si;
  1057. si.stacks.push_back(bsa);
  1058. gameHandler->sendAndApply(&si);
  1059. sendGenericKilledLog(defender, bsa.killedAmount, false);
  1060. }
  1061. }
  1062. int64_t BattleActionProcessor::applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  1063. {
  1064. BattleStackAttacked bsa;
  1065. if(secondary)
  1066. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  1067. bsa.attackerID = attackerState->unitId();
  1068. bsa.stackAttacked = def->unitId();
  1069. {
  1070. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  1071. bai.deathBlow = bat.deathBlow();
  1072. bai.doubleDamage = bat.ballistaDoubleDmg();
  1073. bai.luckyStrike = bat.lucky();
  1074. bai.unluckyStrike = bat.unlucky();
  1075. auto range = gameHandler->gameState()->curB->calculateDmgRange(bai);
  1076. bsa.damageAmount = gameHandler->gameState()->curB->getActualDamage(range.damage, attackerState->getCount(), gameHandler->getRandomGenerator());
  1077. CStack::prepareAttacked(bsa, gameHandler->getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  1078. }
  1079. int64_t drainedLife = 0;
  1080. //life drain handling
  1081. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  1082. {
  1083. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1084. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1085. drainedLife += toHeal;
  1086. }
  1087. //soul steal handling
  1088. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1089. {
  1090. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1091. //try to use permanent first, use only one of two
  1092. for(si32 subtype = 1; subtype >= 0; subtype--)
  1093. {
  1094. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1095. {
  1096. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1097. attackerState->heal(toHeal, EHealLevel::OVERHEAL, ((subtype == 0) ? EHealPower::ONE_BATTLE : EHealPower::PERMANENT));
  1098. drainedLife += toHeal;
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1104. //fire shield handling
  1105. if(!bat.shot() &&
  1106. !def->isClone() &&
  1107. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1108. !attackerState->hasBonusOfType(BonusType::SPELL_SCHOOL_IMMUNITY, SpellSchool(ESpellSchool::FIRE)) &&
  1109. !attackerState->hasBonusOfType(BonusType::NEGATIVE_EFFECTS_IMMUNITY, SpellSchool(ESpellSchool::FIRE)) &&
  1110. attackerState->valOfBonuses(BonusType::SPELL_DAMAGE_REDUCTION, SpellSchool(ESpellSchool::FIRE)) < 100 &&
  1111. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1112. )
  1113. {
  1114. //TODO: use damage with bonus but without penalties
  1115. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1116. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1117. }
  1118. return drainedLife;
  1119. }
  1120. void BattleActionProcessor::sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple)
  1121. {
  1122. if(killed > 0)
  1123. {
  1124. BattleLogMessage blm;
  1125. addGenericKilledLog(blm, defender, killed, multiple);
  1126. gameHandler->sendAndApply(&blm);
  1127. }
  1128. }
  1129. void BattleActionProcessor::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1130. {
  1131. if(killed > 0)
  1132. {
  1133. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1134. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1135. // 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)
  1136. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1137. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1138. boost::algorithm::trim(formatString);
  1139. boost::format txt(formatString);
  1140. if(killed > 1)
  1141. {
  1142. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1143. }
  1144. else //killed == 1
  1145. {
  1146. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1147. }
  1148. MetaString line;
  1149. line.appendRawString(txt.str());
  1150. blm.lines.push_back(std::move(line));
  1151. }
  1152. }
  1153. bool BattleActionProcessor::makeAutomaticBattleAction(const BattleAction & ba)
  1154. {
  1155. return makeBattleActionImpl(ba);
  1156. }
  1157. bool BattleActionProcessor::makePlayerBattleAction(PlayerColor player, const BattleAction &ba)
  1158. {
  1159. const BattleInfo * battle = gameHandler->gameState()->curB;
  1160. if(!battle && gameHandler->complain("Can not make action - there is no battle ongoing!"))
  1161. return false;
  1162. if (ba.side != 0 && ba.side != 1 && gameHandler->complain("Can not make action - invalid battle side!"))
  1163. return false;
  1164. if(battle->tacticDistance != 0)
  1165. {
  1166. if(!ba.isTacticsAction())
  1167. {
  1168. gameHandler->complain("Can not make actions while in tactics mode!");
  1169. return false;
  1170. }
  1171. if(player != battle->sides[ba.side].color)
  1172. {
  1173. gameHandler->complain("Can not make actions in battles you are not part of!");
  1174. return false;
  1175. }
  1176. }
  1177. else
  1178. {
  1179. if (ba.isUnitAction() && ba.stackNumber != battle->getActiveStackID())
  1180. {
  1181. gameHandler->complain("Can not make actions - stack is not active!");
  1182. return false;
  1183. }
  1184. auto active = battle->battleActiveUnit();
  1185. if(!active && gameHandler->complain("No active unit in battle!"))
  1186. return false;
  1187. auto unitOwner = battle->battleGetOwner(active);
  1188. if(player != unitOwner && gameHandler->complain("Can not make actions in battles you are not part of!"))
  1189. return false;
  1190. }
  1191. return makeBattleActionImpl(ba);
  1192. }