BattleActionProcessor.cpp 53 KB

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