BattleActionProcessor.cpp 53 KB

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