BattleActionProcessor.cpp 43 KB

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