CDefaultSpellMechanics.cpp 24 KB

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