CDefaultSpellMechanics.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /*
  2. * CDefaultSpellMechanics.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 "CDefaultSpellMechanics.h"
  12. #include "../NetPacks.h"
  13. #include "../BattleState.h"
  14. #include "../CGeneralTextHandler.h"
  15. namespace SRSLPraserHelpers
  16. {
  17. static int XYToHex(int x, int y)
  18. {
  19. return x + GameConstants::BFIELD_WIDTH * y;
  20. }
  21. static int XYToHex(std::pair<int, int> xy)
  22. {
  23. return XYToHex(xy.first, xy.second);
  24. }
  25. static int hexToY(int battleFieldPosition)
  26. {
  27. return battleFieldPosition/GameConstants::BFIELD_WIDTH;
  28. }
  29. static int hexToX(int battleFieldPosition)
  30. {
  31. int pos = battleFieldPosition - hexToY(battleFieldPosition) * GameConstants::BFIELD_WIDTH;
  32. return pos;
  33. }
  34. static std::pair<int, int> hexToPair(int battleFieldPosition)
  35. {
  36. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  37. }
  38. //moves hex by one hex in given direction
  39. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  40. static std::pair<int, int> gotoDir(int x, int y, int direction)
  41. {
  42. switch(direction)
  43. {
  44. case 0: //top left
  45. return std::make_pair((y%2) ? x-1 : x, y-1);
  46. case 1: //top right
  47. return std::make_pair((y%2) ? x : x+1, y-1);
  48. case 2: //right
  49. return std::make_pair(x+1, y);
  50. case 3: //right bottom
  51. return std::make_pair((y%2) ? x : x+1, y+1);
  52. case 4: //left bottom
  53. return std::make_pair((y%2) ? x-1 : x, y+1);
  54. case 5: //left
  55. return std::make_pair(x-1, y);
  56. default:
  57. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  58. }
  59. }
  60. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  61. {
  62. return gotoDir(xy.first, xy.second, direction);
  63. }
  64. static bool isGoodHex(std::pair<int, int> xy)
  65. {
  66. return xy.first >=0 && xy.first < GameConstants::BFIELD_WIDTH && xy.second >= 0 && xy.second < GameConstants::BFIELD_HEIGHT;
  67. }
  68. //helper function for rangeInHexes
  69. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  70. {
  71. std::set<ui16> ret;
  72. if(low == 0)
  73. {
  74. ret.insert(center);
  75. }
  76. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  77. for(auto & elem : mainPointForLayer)
  78. elem = hexToPair(center);
  79. for(int it=1; it<=high; ++it) //it - distance to the center
  80. {
  81. for(int b=0; b<6; ++b)
  82. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  83. if(it>=low)
  84. {
  85. std::pair<int, int> curHex;
  86. //adding lines (A-b, B-c, C-d, etc)
  87. for(int v=0; v<6; ++v)
  88. {
  89. curHex = mainPointForLayer[v];
  90. for(int h=0; h<it; ++h)
  91. {
  92. if(isGoodHex(curHex))
  93. ret.insert(XYToHex(curHex));
  94. curHex = gotoDir(curHex, (v+2)%6);
  95. }
  96. }
  97. } //if(it>=low)
  98. }
  99. return ret;
  100. }
  101. }
  102. ///DefaultSpellMechanics
  103. void DefaultSpellMechanics::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  104. {
  105. if (packet->castedByHero)
  106. {
  107. if (packet->side < 2)
  108. {
  109. battle->sides[packet->side].castSpellsCount++;
  110. }
  111. }
  112. //handle countering spells
  113. for(auto stackID : packet->affectedCres)
  114. {
  115. if(vstd::contains(packet->resisted, stackID))
  116. continue;
  117. CStack * s = battle->getStack(stackID);
  118. s->popBonuses([&](const Bonus * b) -> bool
  119. {
  120. //check for each bonus if it should be removed
  121. const bool isSpellEffect = Selector::sourceType(Bonus::SPELL_EFFECT)(b);
  122. const int spellID = isSpellEffect ? b->sid : -1;
  123. return isSpellEffect && vstd::contains(owner->counteredSpells, spellID);
  124. });
  125. }
  126. }
  127. bool DefaultSpellMechanics::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  128. {
  129. if(!owner->isAdventureSpell())
  130. {
  131. env->complain("Attempt to cast non adventure spell in adventure mode");
  132. return false;
  133. }
  134. const CGHeroInstance * caster = parameters.caster;
  135. const int cost = caster->getSpellCost(owner);
  136. if(!caster->canCastThisSpell(owner))
  137. {
  138. env->complain("Hero cannot cast this spell!");
  139. return false;
  140. }
  141. if(caster->mana < cost)
  142. {
  143. env->complain("Hero doesn't have enough spell points to cast this spell!");
  144. return false;
  145. }
  146. {
  147. AdvmapSpellCast asc;
  148. asc.caster = caster;
  149. asc.spellID = owner->id;
  150. env->sendAndApply(&asc);
  151. }
  152. switch(applyAdventureEffects(env, parameters))
  153. {
  154. case ESpellCastResult::OK:
  155. {
  156. SetMana sm;
  157. sm.hid = caster->id;
  158. sm.absolute = false;
  159. sm.val = -cost;
  160. env->sendAndApply(&sm);
  161. return true;
  162. }
  163. break;
  164. case ESpellCastResult::CANCEL:
  165. return true;
  166. }
  167. return false;
  168. }
  169. ESpellCastResult DefaultSpellMechanics::applyAdventureEffects(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  170. {
  171. if(owner->hasEffects())
  172. {
  173. const int schoolLevel = parameters.caster->getSpellSchoolLevel(owner);
  174. std::vector<Bonus> bonuses;
  175. owner->getEffects(bonuses, schoolLevel);
  176. for(Bonus b : bonuses)
  177. {
  178. GiveBonus gb;
  179. gb.id = parameters.caster->id.getNum();
  180. gb.bonus = b;
  181. env->sendAndApply(&gb);
  182. }
  183. return ESpellCastResult::OK;
  184. }
  185. else
  186. {
  187. //There is no generic algorithm of adventure cast
  188. env->complain("Unimplemented adventure spell");
  189. return ESpellCastResult::ERROR;
  190. }
  191. }
  192. void DefaultSpellMechanics::battleCast(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters) const
  193. {
  194. BattleSpellCast sc;
  195. sc.side = parameters.casterSide;
  196. sc.id = owner->id;
  197. sc.skill = parameters.spellLvl;
  198. sc.tile = parameters.destination;
  199. sc.dmgToDisplay = 0;
  200. sc.castedByHero = nullptr != parameters.casterHero;
  201. sc.casterStack = (parameters.casterStack ? parameters.casterStack->ID : -1);
  202. sc.manaGained = 0;
  203. int spellCost = 0;
  204. //calculate spell cost
  205. if(parameters.casterHero)
  206. {
  207. spellCost = parameters.cb->battleGetSpellCost(owner, parameters.casterHero);
  208. if(parameters.secHero && parameters.mode == ECastingMode::HERO_CASTING) //handle mana channel
  209. {
  210. int manaChannel = 0;
  211. for(const CStack * stack : parameters.cb->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  212. {
  213. if(stack->owner == parameters.secHero->tempOwner)
  214. {
  215. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  216. }
  217. }
  218. sc.manaGained = (manaChannel * spellCost) / 100;
  219. }
  220. }
  221. //calculating affected creatures for all spells
  222. //must be vector, as in Chain Lightning order matters
  223. std::vector<const CStack*> attackedCres; //CStack vector is somewhat more suitable than ID vector
  224. auto creatures = owner->getAffectedStacks(parameters.cb, parameters.mode, parameters.casterColor, parameters.spellLvl, parameters.destination, parameters.casterHero);
  225. std::copy(creatures.begin(), creatures.end(), std::back_inserter(attackedCres));
  226. for (auto cre : attackedCres)
  227. {
  228. sc.affectedCres.insert(cre->ID);
  229. }
  230. //checking if creatures resist
  231. //resistance is applied only to negative spells
  232. if(owner->isNegative())
  233. {
  234. for(auto s : attackedCres)
  235. {
  236. const int prob = std::min((s)->magicResistance(), 100); //probability of resistance in %
  237. if(env->getRandomGenerator().nextInt(99) < prob)
  238. {
  239. sc.resisted.push_back(s->ID);
  240. }
  241. }
  242. }
  243. StacksInjured si;
  244. SpellCastContext ctx(attackedCres, sc, si);
  245. applyBattleEffects(env, parameters, ctx);
  246. env->sendAndApply(&sc);
  247. //spend mana
  248. if(parameters.casterHero)
  249. {
  250. SetMana sm;
  251. sm.absolute = false;
  252. sm.hid = parameters.casterHero->id;
  253. sm.val = -spellCost;
  254. env->sendAndApply(&sm);
  255. if(sc.manaGained > 0)
  256. {
  257. assert(parameters.secHero);
  258. sm.hid = parameters.secHero->id;
  259. sm.val = sc.manaGained;
  260. env->sendAndApply(&sm);
  261. }
  262. }
  263. if(!si.stacks.empty()) //after spellcast info shows
  264. env->sendAndApply(&si);
  265. //reduce number of casts remaining
  266. //TODO: this should be part of BattleSpellCast apply
  267. if (parameters.mode == ECastingMode::CREATURE_ACTIVE_CASTING || parameters.mode == ECastingMode::ENCHANTER_CASTING)
  268. {
  269. assert(parameters.casterStack);
  270. BattleSetStackProperty ssp;
  271. ssp.stackID = parameters.casterStack->ID;
  272. ssp.which = BattleSetStackProperty::CASTS;
  273. ssp.val = -1;
  274. ssp.absolute = false;
  275. env->sendAndApply(&ssp);
  276. }
  277. //Magic Mirror effect
  278. if(owner->isNegative() && parameters.mode != ECastingMode::MAGIC_MIRROR && owner->level && owner->getLevelInfo(0).range == "0") //it is actual spell and can be reflected to single target, no recurrence
  279. {
  280. for(auto & attackedCre : attackedCres)
  281. {
  282. int mirrorChance = (attackedCre)->valOfBonuses(Bonus::MAGIC_MIRROR);
  283. if(mirrorChance > env->getRandomGenerator().nextInt(99))
  284. {
  285. std::vector<const CStack *> mirrorTargets;
  286. auto battleStacks = parameters.cb->battleGetAllStacks(true);
  287. for(auto & battleStack : battleStacks)
  288. {
  289. if(battleStack->owner == parameters.casterColor) //get enemy stacks which can be affected by this spell
  290. {
  291. if (ESpellCastProblem::OK == owner->isImmuneByStack(nullptr, battleStack))
  292. mirrorTargets.push_back(battleStack);
  293. }
  294. }
  295. if(!mirrorTargets.empty())
  296. {
  297. int targetHex = (*RandomGeneratorUtil::nextItem(mirrorTargets, env->getRandomGenerator()))->position;
  298. BattleSpellCastParameters mirrorParameters = parameters;
  299. mirrorParameters.spellLvl = 0;
  300. mirrorParameters.casterSide = 1-parameters.casterSide;
  301. mirrorParameters.casterColor = (attackedCre)->owner;
  302. mirrorParameters.casterHero = nullptr;
  303. mirrorParameters.destination = targetHex;
  304. mirrorParameters.secHero = parameters.casterHero;
  305. mirrorParameters.mode = ECastingMode::MAGIC_MIRROR;
  306. mirrorParameters.casterStack = (attackedCre);
  307. mirrorParameters.selectedStack = nullptr;
  308. battleCast(env, mirrorParameters);
  309. }
  310. }
  311. }
  312. }
  313. }
  314. void DefaultSpellMechanics::battleLogSingleTarget(std::vector<std::string> & logLines, const BattleSpellCast * packet,
  315. const std::string & casterName, const CStack * attackedStack, bool & displayDamage) const
  316. {
  317. const std::string attackedName = attackedStack->getName();
  318. const std::string attackedNameSing = attackedStack->getCreature()->nameSing;
  319. const std::string attackedNamePl = attackedStack->getCreature()->namePl;
  320. auto getPluralFormat = [attackedStack](const int baseTextID) -> boost::format
  321. {
  322. return boost::format(VLC->generaltexth->allTexts[(attackedStack->count > 1 ? baseTextID + 1 : baseTextID)]);
  323. };
  324. auto logSimple = [&logLines, getPluralFormat, attackedName](const int baseTextID)
  325. {
  326. boost::format fmt = getPluralFormat(baseTextID);
  327. fmt % attackedName;
  328. logLines.push_back(fmt.str());
  329. };
  330. auto logPlural = [&logLines, attackedNamePl](const int baseTextID)
  331. {
  332. boost::format fmt(VLC->generaltexth->allTexts[baseTextID]);
  333. fmt % attackedNamePl;
  334. logLines.push_back(fmt.str());
  335. };
  336. displayDamage = false; //in most following cases damage info text is custom
  337. switch(owner->id)
  338. {
  339. case SpellID::STONE_GAZE:
  340. logSimple(558);
  341. break;
  342. case SpellID::POISON:
  343. logSimple(561);
  344. break;
  345. case SpellID::BIND:
  346. logPlural(560);//Roots and vines bind the %s to the ground!
  347. break;
  348. case SpellID::DISEASE:
  349. logSimple(553);
  350. break;
  351. case SpellID::PARALYZE:
  352. logSimple(563);
  353. break;
  354. case SpellID::AGE:
  355. {
  356. boost::format text = getPluralFormat(551);
  357. text % attackedName;
  358. //The %s shrivel with age, and lose %d hit points."
  359. TBonusListPtr bl = attackedStack->getBonuses(Selector::type(Bonus::STACK_HEALTH));
  360. const int fullHP = bl->totalValue();
  361. bl->remove_if(Selector::source(Bonus::SPELL_EFFECT, SpellID::AGE));
  362. text % (fullHP - bl->totalValue());
  363. logLines.push_back(text.str());
  364. }
  365. break;
  366. case SpellID::THUNDERBOLT:
  367. {
  368. logPlural(367);
  369. std::string text = VLC->generaltexth->allTexts[343].substr(1, VLC->generaltexth->allTexts[343].size() - 1); //Does %d points of damage.
  370. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(packet->dmgToDisplay)); //no more text afterwards
  371. logLines.push_back(text);
  372. }
  373. break;
  374. case SpellID::DISPEL_HELPFUL_SPELLS:
  375. logPlural(555);
  376. break;
  377. case SpellID::DEATH_STARE:
  378. if (packet->dmgToDisplay > 0)
  379. {
  380. std::string text;
  381. if (packet->dmgToDisplay > 1)
  382. {
  383. text = VLC->generaltexth->allTexts[119]; //%d %s die under the terrible gaze of the %s.
  384. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(packet->dmgToDisplay));
  385. boost::algorithm::replace_first(text, "%s", attackedNamePl);
  386. }
  387. else
  388. {
  389. text = VLC->generaltexth->allTexts[118]; //One %s dies under the terrible gaze of the %s.
  390. boost::algorithm::replace_first(text, "%s", attackedNameSing);
  391. }
  392. boost::algorithm::replace_first(text, "%s", casterName); //casting stack
  393. logLines.push_back(text);
  394. }
  395. break;
  396. default:
  397. {
  398. boost::format text(VLC->generaltexth->allTexts[565]); //The %s casts %s
  399. text % casterName % owner->name;
  400. displayDamage = true;
  401. logLines.push_back(text.str());
  402. }
  403. break;
  404. }
  405. }
  406. int DefaultSpellMechanics::calculateDuration(const CGHeroInstance * caster, int usedSpellPower) const
  407. {
  408. if(!caster)
  409. {
  410. if (!usedSpellPower)
  411. return 3; //default duration of all creature spells
  412. else
  413. return usedSpellPower; //use creature spell power
  414. }
  415. switch(owner->id)
  416. {
  417. case SpellID::FRENZY:
  418. return 1;
  419. default: //other spells
  420. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  421. }
  422. }
  423. ui32 DefaultSpellMechanics::calculateHealedHP(const CGHeroInstance* caster, const CStack* stack, const CStack* sacrificedStack) const
  424. {
  425. int healedHealth;
  426. if(!owner->isHealingSpell())
  427. {
  428. logGlobal->errorStream() << "calculateHealedHP called for nonhealing spell "<< owner->name;
  429. return 0;
  430. }
  431. const int spellPowerSkill = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  432. const int levelPower = owner->getPower(caster->getSpellSchoolLevel(owner));
  433. if (owner->id == SpellID::SACRIFICE && sacrificedStack)
  434. healedHealth = (spellPowerSkill + sacrificedStack->MaxHealth() + levelPower) * sacrificedStack->count;
  435. else
  436. healedHealth = spellPowerSkill * owner->power + levelPower; //???
  437. healedHealth = caster->getSpellBonus(owner, healedHealth, stack);
  438. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (owner->isRisingSpell() ? stack->baseAmount * stack->MaxHealth() : 0));
  439. }
  440. void DefaultSpellMechanics::applyBattleEffects(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters, SpellCastContext & ctx) const
  441. {
  442. //applying effects
  443. if(owner->isOffensiveSpell())
  444. {
  445. int spellDamage = 0;
  446. if(parameters.casterStack && parameters.mode != ECastingMode::MAGIC_MIRROR)
  447. {
  448. int unitSpellPower = parameters.casterStack->valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, owner->id.toEnum());
  449. if(unitSpellPower)
  450. ctx.sc.dmgToDisplay = spellDamage = parameters.casterStack->count * unitSpellPower; //TODO: handle immunities
  451. else //Faerie Dragon
  452. {
  453. parameters.usedSpellPower = parameters.casterStack->valOfBonuses(Bonus::CREATURE_SPELL_POWER) * parameters.casterStack->count / 100;
  454. ctx.sc.dmgToDisplay = 0;
  455. }
  456. }
  457. int chainLightningModifier = 0;
  458. for(auto & attackedCre : ctx.attackedCres)
  459. {
  460. if(vstd::contains(ctx.sc.resisted, (attackedCre)->ID)) //this creature resisted the spell
  461. continue;
  462. BattleStackAttacked bsa;
  463. if(spellDamage)
  464. bsa.damageAmount = spellDamage >> chainLightningModifier;
  465. else
  466. bsa.damageAmount = owner->calculateDamage(parameters.casterHero, attackedCre, parameters.spellLvl, parameters.usedSpellPower) >> chainLightningModifier;
  467. ctx.sc.dmgToDisplay += bsa.damageAmount;
  468. bsa.stackAttacked = (attackedCre)->ID;
  469. if(parameters.mode == ECastingMode::ENCHANTER_CASTING) //multiple damage spells cast
  470. bsa.attackerID = parameters.casterStack->ID;
  471. else
  472. bsa.attackerID = -1;
  473. (attackedCre)->prepareAttacked(bsa, env->getRandomGenerator());
  474. ctx.si.stacks.push_back(bsa);
  475. if(owner->id == SpellID::CHAIN_LIGHTNING)
  476. ++chainLightningModifier;
  477. }
  478. }
  479. if(owner->hasEffects())
  480. {
  481. int stackSpellPower = 0;
  482. if(parameters.casterStack && parameters.mode != ECastingMode::MAGIC_MIRROR)
  483. {
  484. stackSpellPower = parameters.casterStack->valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  485. }
  486. SetStackEffect sse;
  487. Bonus pseudoBonus;
  488. pseudoBonus.sid = owner->id;
  489. pseudoBonus.val = parameters.spellLvl;
  490. pseudoBonus.turnsRemain = calculateDuration(parameters.casterHero, stackSpellPower ? stackSpellPower : parameters.usedSpellPower);
  491. CStack::stackEffectToFeature(sse.effect, pseudoBonus);
  492. if(owner->id == SpellID::SHIELD || owner->id == SpellID::AIR_SHIELD)
  493. {
  494. sse.effect.back().val = (100 - sse.effect.back().val); //fix to original config: shield should display damage reduction
  495. }
  496. if(owner->id == SpellID::BIND && parameters.casterStack)//bind
  497. {
  498. sse.effect.back().additionalInfo = parameters.casterStack->ID; //we need to know who casted Bind
  499. }
  500. const Bonus * bonus = nullptr;
  501. if(parameters.casterHero)
  502. bonus = parameters.casterHero->getBonusLocalFirst(Selector::typeSubtype(Bonus::SPECIAL_PECULIAR_ENCHANT, owner->id));
  503. //TODO does hero specialty should affects his stack casting spells?
  504. si32 power = 0;
  505. for(const CStack * affected : ctx.attackedCres)
  506. {
  507. if(vstd::contains(ctx.sc.resisted, affected->ID)) //this creature resisted the spell
  508. continue;
  509. sse.stacks.push_back(affected->ID);
  510. //Apply hero specials - peculiar enchants
  511. const ui8 tier = std::max((ui8)1, affected->getCreature()->level); //don't divide by 0 for certain creatures (commanders, war machines)
  512. if(bonus)
  513. {
  514. switch(bonus->additionalInfo)
  515. {
  516. case 0: //normal
  517. {
  518. switch(tier)
  519. {
  520. case 1: case 2:
  521. power = 3;
  522. break;
  523. case 3: case 4:
  524. power = 2;
  525. break;
  526. case 5: case 6:
  527. power = 1;
  528. break;
  529. }
  530. Bonus specialBonus(sse.effect.back());
  531. specialBonus.val = power; //it doesn't necessarily make sense for some spells, use it wisely
  532. sse.uniqueBonuses.push_back (std::pair<ui32,Bonus> (affected->ID, specialBonus)); //additional premy to given effect
  533. }
  534. break;
  535. case 1: //only Coronius as yet
  536. {
  537. power = std::max(5 - tier, 0);
  538. Bonus specialBonus = CStack::featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, pseudoBonus.turnsRemain);
  539. specialBonus.sid = owner->id;
  540. sse.uniqueBonuses.push_back(std::pair<ui32,Bonus> (affected->ID, specialBonus)); //additional attack to Slayer effect
  541. }
  542. break;
  543. }
  544. }
  545. if (parameters.casterHero && parameters.casterHero->hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, owner->id)) //TODO: better handling of bonus percentages
  546. {
  547. int damagePercent = parameters.casterHero->level * parameters.casterHero->valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, owner->id.toEnum()) / tier;
  548. Bonus specialBonus = CStack::featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, pseudoBonus.turnsRemain);
  549. specialBonus.valType = Bonus::PERCENT_TO_ALL;
  550. specialBonus.sid = owner->id;
  551. sse.uniqueBonuses.push_back (std::pair<ui32,Bonus> (affected->ID, specialBonus));
  552. }
  553. }
  554. if(!sse.stacks.empty())
  555. env->sendAndApply(&sse);
  556. }
  557. if(owner->isHealingSpell())
  558. {
  559. int hpGained = 0;
  560. if(parameters.casterStack)
  561. {
  562. int unitSpellPower = parameters.casterStack->valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, owner->id.toEnum());
  563. if(unitSpellPower)
  564. hpGained = parameters.casterStack->count * unitSpellPower; //Archangel
  565. else //Faerie Dragon-like effect - unused so far
  566. parameters.usedSpellPower = parameters.casterStack->valOfBonuses(Bonus::CREATURE_SPELL_POWER) * parameters.casterStack->count / 100;
  567. }
  568. StacksHealedOrResurrected shr;
  569. shr.lifeDrain = false;
  570. shr.tentHealing = false;
  571. for(auto & attackedCre : ctx.attackedCres)
  572. {
  573. StacksHealedOrResurrected::HealInfo hi;
  574. hi.stackID = (attackedCre)->ID;
  575. if (parameters.casterStack) //casted by creature
  576. {
  577. const bool resurrect = owner->isRisingSpell();
  578. if (hpGained)
  579. {
  580. //archangel
  581. hi.healedHP = std::min<ui32>(hpGained, attackedCre->MaxHealth() - attackedCre->firstHPleft + (resurrect ? attackedCre->baseAmount * attackedCre->MaxHealth() : 0));
  582. }
  583. else
  584. {
  585. //any typical spell (commander's cure or animate dead)
  586. int healedHealth = parameters.usedSpellPower * owner->power + owner->getPower(parameters.spellLvl);
  587. hi.healedHP = std::min<ui32>(healedHealth, attackedCre->MaxHealth() - attackedCre->firstHPleft + (resurrect ? attackedCre->baseAmount * attackedCre->MaxHealth() : 0));
  588. }
  589. }
  590. else
  591. hi.healedHP = calculateHealedHP(parameters.casterHero, attackedCre, parameters.selectedStack); //Casted by hero
  592. hi.lowLevelResurrection = (parameters.spellLvl <= 1) && (owner->id != SpellID::ANIMATE_DEAD);
  593. shr.healedStacks.push_back(hi);
  594. }
  595. if(!shr.healedStacks.empty())
  596. env->sendAndApply(&shr);
  597. }
  598. }
  599. std::vector<BattleHex> DefaultSpellMechanics::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  600. {
  601. using namespace SRSLPraserHelpers;
  602. std::vector<BattleHex> ret;
  603. std::string rng = owner->getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  604. if(rng.size() >= 2 && rng[0] != 'X') //there is at lest one hex in range (+artificial comma)
  605. {
  606. std::string number1, number2;
  607. int beg, end;
  608. bool readingFirst = true;
  609. for(auto & elem : rng)
  610. {
  611. if(std::isdigit(elem) ) //reading number
  612. {
  613. if(readingFirst)
  614. number1 += elem;
  615. else
  616. number2 += elem;
  617. }
  618. else if(elem == ',') //comma
  619. {
  620. //calculating variables
  621. if(readingFirst)
  622. {
  623. beg = atoi(number1.c_str());
  624. number1 = "";
  625. }
  626. else
  627. {
  628. end = atoi(number2.c_str());
  629. number2 = "";
  630. }
  631. //obtaining new hexes
  632. std::set<ui16> curLayer;
  633. if(readingFirst)
  634. {
  635. curLayer = getInRange(centralHex, beg, beg);
  636. }
  637. else
  638. {
  639. curLayer = getInRange(centralHex, beg, end);
  640. readingFirst = true;
  641. }
  642. //adding abtained hexes
  643. for(auto & curLayer_it : curLayer)
  644. {
  645. ret.push_back(curLayer_it);
  646. }
  647. }
  648. else if(elem == '-') //dash
  649. {
  650. beg = atoi(number1.c_str());
  651. number1 = "";
  652. readingFirst = false;
  653. }
  654. }
  655. }
  656. //remove duplicates (TODO check if actually needed)
  657. range::unique(ret);
  658. return ret;
  659. }
  660. std::set<const CStack *> DefaultSpellMechanics::getAffectedStacks(SpellTargetingContext & ctx) const
  661. {
  662. std::set<const CStack* > attackedCres;//std::set to exclude multiple occurrences of two hex creatures
  663. const ui8 attackerSide = ctx.cb->playerToSide(ctx.casterColor) == 1;
  664. const auto attackedHexes = rangeInHexes(ctx.destination, ctx.schoolLvl, attackerSide);
  665. const CSpell::TargetInfo ti(owner, ctx.schoolLvl, ctx.mode);
  666. //TODO: more generic solution for mass spells
  667. if(owner->getLevelInfo(ctx.schoolLvl).range.size() > 1) //custom many-hex range
  668. {
  669. for(BattleHex hex : attackedHexes)
  670. {
  671. if(const CStack * st = ctx.cb->battleGetStackByPos(hex, ti.onlyAlive))
  672. {
  673. attackedCres.insert(st);
  674. }
  675. }
  676. }
  677. else if(ti.type == CSpell::CREATURE)
  678. {
  679. auto predicate = [=](const CStack * s){
  680. const bool positiveToAlly = owner->isPositive() && s->owner == ctx.casterColor;
  681. const bool negativeToEnemy = owner->isNegative() && s->owner != ctx.casterColor;
  682. const bool validTarget = s->isValidTarget(!ti.onlyAlive); //todo: this should be handled by spell class
  683. //for single target spells select stacks covering destination tile
  684. const bool rangeCovers = ti.massive || s->coversPos(ctx.destination);
  685. //handle smart targeting
  686. const bool positivenessFlag = !ti.smart || owner->isNeutral() || positiveToAlly || negativeToEnemy;
  687. return rangeCovers && positivenessFlag && validTarget;
  688. };
  689. TStacks stacks = ctx.cb->battleGetStacksIf(predicate);
  690. if(ti.massive)
  691. {
  692. //for massive spells add all targets
  693. for (auto stack : stacks)
  694. attackedCres.insert(stack);
  695. }
  696. else
  697. {
  698. //for single target spells we must select one target. Alive stack is preferred (issue #1763)
  699. for(auto stack : stacks)
  700. {
  701. if(stack->alive())
  702. {
  703. attackedCres.insert(stack);
  704. break;
  705. }
  706. }
  707. if(attackedCres.empty() && !stacks.empty())
  708. {
  709. attackedCres.insert(stacks.front());
  710. }
  711. }
  712. }
  713. else //custom range from attackedHexes
  714. {
  715. for(BattleHex hex : attackedHexes)
  716. {
  717. if(const CStack * st = ctx.cb->battleGetStackByPos(hex, ti.onlyAlive))
  718. attackedCres.insert(st);
  719. }
  720. }
  721. return attackedCres;
  722. }
  723. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::canBeCasted(const CBattleInfoCallback * cb, PlayerColor player) const
  724. {
  725. //no problems by default, this method is for spell-specific problems
  726. return ESpellCastProblem::OK;
  727. }
  728. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::isImmuneByStack(const CGHeroInstance * caster, const CStack * obj) const
  729. {
  730. //by default use general algorithm
  731. return owner->isImmuneBy(obj);
  732. }
  733. void DefaultSpellMechanics::doDispell(BattleInfo * battle, const BattleSpellCast * packet, const CSelector & selector) const
  734. {
  735. for(auto stackID : packet->affectedCres)
  736. {
  737. if(vstd::contains(packet->resisted, stackID))
  738. continue;
  739. CStack *s = battle->getStack(stackID);
  740. s->popBonuses(selector);
  741. }
  742. }