BattleActionProcessor.cpp 52 KB

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