BattleActionProcessor.cpp 46 KB

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