BattleSpellMechanics.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. /*
  2. * BattleSpellMechanics.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 "BattleSpellMechanics.h"
  12. #include "Problem.h"
  13. #include "CSpellHandler.h"
  14. #include "../battle/IBattleState.h"
  15. #include "../battle/CBattleInfoCallback.h"
  16. #include "../CStack.h"
  17. #include "../NetPacks.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. namespace spells
  20. {
  21. namespace SRSLPraserHelpers
  22. {
  23. static int XYToHex(int x, int y)
  24. {
  25. return x + GameConstants::BFIELD_WIDTH * y;
  26. }
  27. static int XYToHex(std::pair<int, int> xy)
  28. {
  29. return XYToHex(xy.first, xy.second);
  30. }
  31. static int hexToY(int battleFieldPosition)
  32. {
  33. return battleFieldPosition/GameConstants::BFIELD_WIDTH;
  34. }
  35. static int hexToX(int battleFieldPosition)
  36. {
  37. int pos = battleFieldPosition - hexToY(battleFieldPosition) * GameConstants::BFIELD_WIDTH;
  38. return pos;
  39. }
  40. static std::pair<int, int> hexToPair(int battleFieldPosition)
  41. {
  42. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  43. }
  44. //moves hex by one hex in given direction
  45. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  46. static std::pair<int, int> gotoDir(int x, int y, int direction)
  47. {
  48. switch(direction)
  49. {
  50. case 0: //top left
  51. return std::make_pair((y%2) ? x-1 : x, y-1);
  52. case 1: //top right
  53. return std::make_pair((y%2) ? x : x+1, y-1);
  54. case 2: //right
  55. return std::make_pair(x+1, y);
  56. case 3: //right bottom
  57. return std::make_pair((y%2) ? x : x+1, y+1);
  58. case 4: //left bottom
  59. return std::make_pair((y%2) ? x-1 : x, y+1);
  60. case 5: //left
  61. return std::make_pair(x-1, y);
  62. default:
  63. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  64. }
  65. }
  66. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  67. {
  68. return gotoDir(xy.first, xy.second, direction);
  69. }
  70. static bool isGoodHex(std::pair<int, int> xy)
  71. {
  72. return xy.first >=0 && xy.first < GameConstants::BFIELD_WIDTH && xy.second >= 0 && xy.second < GameConstants::BFIELD_HEIGHT;
  73. }
  74. //helper function for rangeInHexes
  75. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  76. {
  77. std::set<ui16> ret;
  78. if(low == 0)
  79. {
  80. ret.insert(center);
  81. }
  82. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  83. for(auto & elem : mainPointForLayer)
  84. elem = hexToPair(center);
  85. for(int it=1; it<=high; ++it) //it - distance to the center
  86. {
  87. for(int b=0; b<6; ++b)
  88. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  89. if(it>=low)
  90. {
  91. std::pair<int, int> curHex;
  92. //adding lines (A-b, B-c, C-d, etc)
  93. for(int v=0; v<6; ++v)
  94. {
  95. curHex = mainPointForLayer[v];
  96. for(int h=0; h<it; ++h)
  97. {
  98. if(isGoodHex(curHex))
  99. ret.insert(XYToHex(curHex));
  100. curHex = gotoDir(curHex, (v+2)%6);
  101. }
  102. }
  103. } //if(it>=low)
  104. }
  105. return ret;
  106. }
  107. }
  108. BattleSpellMechanics::BattleSpellMechanics(const IBattleCast * event, std::shared_ptr<effects::Effects> effects_, std::shared_ptr<IReceptiveCheck> targetCondition_)
  109. : BaseMechanics(event),
  110. effects(effects_),
  111. targetCondition(targetCondition_)
  112. {}
  113. BattleSpellMechanics::~BattleSpellMechanics() = default;
  114. void BattleSpellMechanics::applyEffects(ServerCallback * server, const Target & targets, bool indirect, bool ignoreImmunity) const
  115. {
  116. auto callback = [&](const effects::Effect * effect, bool & stop)
  117. {
  118. if(indirect == effect->indirect)
  119. {
  120. if(ignoreImmunity)
  121. {
  122. effect->apply(server, this, targets);
  123. }
  124. else
  125. {
  126. EffectTarget filtered = effect->filterTarget(this, targets);
  127. effect->apply(server, this, filtered);
  128. }
  129. }
  130. };
  131. effects->forEachEffect(getEffectLevel(), callback);
  132. }
  133. bool BattleSpellMechanics::canBeCast(Problem & problem) const
  134. {
  135. auto genProblem = battle()->battleCanCastSpell(caster, mode);
  136. if(genProblem != ESpellCastProblem::OK)
  137. return adaptProblem(genProblem, problem);
  138. switch(mode)
  139. {
  140. case Mode::HERO:
  141. {
  142. const CGHeroInstance * castingHero = dynamic_cast<const CGHeroInstance *>(caster);//todo: unify hero|creature spell cost
  143. if(!castingHero)
  144. {
  145. logGlobal->debug("CSpell::canBeCast: invalid caster");
  146. genProblem = ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  147. }
  148. else if(!castingHero->getArt(ArtifactPosition::SPELLBOOK))
  149. genProblem = ESpellCastProblem::NO_SPELLBOOK;
  150. else if(!castingHero->canCastThisSpell(owner))
  151. genProblem = ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  152. else if(castingHero->mana < battle()->battleGetSpellCost(owner, castingHero)) //not enough mana
  153. genProblem = ESpellCastProblem::NOT_ENOUGH_MANA;
  154. }
  155. break;
  156. }
  157. if(genProblem != ESpellCastProblem::OK)
  158. return adaptProblem(genProblem, problem);
  159. if(!owner->isCombat())
  160. return adaptProblem(ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL, problem);
  161. const PlayerColor player = caster->getCasterOwner();
  162. const auto side = battle()->playerToSide(player);
  163. if(!side)
  164. return adaptProblem(ESpellCastProblem::INVALID, problem);
  165. //effect like Recanter's Cloak. Blocks also passive casting.
  166. //TODO: check creature abilities to block
  167. //TODO: check any possible caster
  168. if(battle()->battleMaxSpellLevel(side.get()) < getSpellLevel() || battle()->battleMinSpellLevel(side.get()) > getSpellLevel())
  169. return adaptProblem(ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED, problem);
  170. return effects->applicable(problem, this);
  171. }
  172. bool BattleSpellMechanics::canBeCastAt(const Target & target, Problem & problem) const
  173. {
  174. if(!canBeCast(problem))
  175. return false;
  176. Target spellTarget = transformSpellTarget(target);
  177. return effects->applicable(problem, this, target, spellTarget);
  178. }
  179. std::vector<const CStack *> BattleSpellMechanics::getAffectedStacks(const Target & target) const
  180. {
  181. Target spellTarget = transformSpellTarget(target);
  182. EffectTarget all;
  183. effects->forEachEffect(getEffectLevel(), [&all, &target, &spellTarget, this](const effects::Effect * e, bool & stop)
  184. {
  185. EffectTarget one = e->transformTarget(this, target, spellTarget);
  186. vstd::concatenate(all, one);
  187. });
  188. std::set<const CStack *> stacks;
  189. for(const Destination & dest : all)
  190. {
  191. if(dest.unitValue)
  192. {
  193. //FIXME: remove and return battle::Unit
  194. stacks.insert(battle()->battleGetStackByID(dest.unitValue->unitId(), false));
  195. }
  196. }
  197. std::vector<const CStack *> res;
  198. std::copy(stacks.begin(), stacks.end(), std::back_inserter(res));
  199. return res;
  200. }
  201. void BattleSpellMechanics::cast(ServerCallback * server, const Target & target)
  202. {
  203. BattleSpellCast sc;
  204. int spellCost = 0;
  205. sc.side = casterSide;
  206. sc.spellID = getSpellId();
  207. sc.tile = target.at(0).hexValue;
  208. sc.castByHero = mode == Mode::HERO;
  209. sc.casterStack = caster->getCasterUnitId();
  210. sc.manaGained = 0;
  211. sc.activeCast = false;
  212. affectedUnits.clear();
  213. const CGHeroInstance * otherHero = nullptr;
  214. {
  215. //check it there is opponent hero
  216. const ui8 otherSide = battle()->otherSide(casterSide);
  217. if(battle()->battleHasHero(otherSide))
  218. otherHero = battle()->battleGetFightingHero(otherSide);
  219. }
  220. //calculate spell cost
  221. if(mode == Mode::HERO)
  222. {
  223. auto casterHero = dynamic_cast<const CGHeroInstance *>(caster);
  224. spellCost = battle()->battleGetSpellCost(owner, casterHero);
  225. if(nullptr != otherHero) //handle mana channel
  226. {
  227. int manaChannel = 0;
  228. for(const CStack * stack : battle()->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  229. {
  230. if(stack->owner == otherHero->tempOwner)
  231. {
  232. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  233. }
  234. }
  235. sc.manaGained = (manaChannel * spellCost) / 100;
  236. }
  237. sc.activeCast = true;
  238. }
  239. else if(mode == Mode::CREATURE_ACTIVE || mode == Mode::ENCHANTER)
  240. {
  241. spellCost = 1;
  242. sc.activeCast = true;
  243. }
  244. beforeCast(sc, *server->getRNG(), target);
  245. BattleLogMessage castDescription;
  246. switch (mode)
  247. {
  248. case Mode::CREATURE_ACTIVE:
  249. case Mode::ENCHANTER:
  250. case Mode::HERO:
  251. case Mode::PASSIVE:
  252. {
  253. MetaString line;
  254. caster->getCastDescription(owner, affectedUnits, line);
  255. if(!line.message.empty())
  256. castDescription.lines.push_back(line);
  257. }
  258. break;
  259. default:
  260. break;
  261. }
  262. doRemoveEffects(server, affectedUnits, std::bind(&BattleSpellMechanics::counteringSelector, this, _1));
  263. for(auto & unit : affectedUnits)
  264. sc.affectedCres.insert(unit->unitId());
  265. if(!castDescription.lines.empty())
  266. server->apply(&castDescription);
  267. server->apply(&sc);
  268. for(auto & p : effectsToApply)
  269. p.first->apply(server, this, p.second);
  270. // afterCast();
  271. if(sc.activeCast)
  272. {
  273. caster->spendMana(server, spellCost);
  274. if(sc.manaGained > 0)
  275. {
  276. assert(otherHero);
  277. otherHero->spendMana(server, -sc.manaGained);
  278. }
  279. }
  280. }
  281. void BattleSpellMechanics::beforeCast(BattleSpellCast & sc, vstd::RNG & rng, const Target & target)
  282. {
  283. affectedUnits.clear();
  284. Target spellTarget = transformSpellTarget(target);
  285. std::vector <const battle::Unit *> resisted;
  286. auto rangeGen = rng.getInt64Range(0, 99);
  287. auto filterResisted = [&, this](const battle::Unit * unit) -> bool
  288. {
  289. if(isNegativeSpell())
  290. {
  291. //magic resistance
  292. const int prob = std::min(unit->magicResistance(), 100); //probability of resistance in %
  293. if(rangeGen() < prob)
  294. return true;
  295. }
  296. return false;
  297. };
  298. auto filterUnit = [&](const battle::Unit * unit)
  299. {
  300. if(filterResisted(unit))
  301. resisted.push_back(unit);
  302. else
  303. affectedUnits.push_back(unit);
  304. };
  305. //prepare targets
  306. effectsToApply = effects->prepare(this, target, spellTarget);
  307. std::set<const battle::Unit *> unitTargets = collectTargets();
  308. //process them
  309. for(auto unit : unitTargets)
  310. filterUnit(unit);
  311. //and update targets
  312. for(auto & p : effectsToApply)
  313. {
  314. vstd::erase_if(p.second, [&](const Destination & d)
  315. {
  316. if(!d.unitValue)
  317. return false;
  318. return vstd::contains(resisted, d.unitValue);
  319. });
  320. }
  321. if(mode == Mode::MAGIC_MIRROR)
  322. {
  323. if(caster->getCasterUnitId() >= 0)
  324. {
  325. addCustomEffect(sc, caster->getCasterUnitId(), 3);
  326. }
  327. }
  328. for(auto unit : resisted)
  329. addCustomEffect(sc, unit, 78);
  330. }
  331. void BattleSpellMechanics::castEval(ServerCallback * server, const Target & target)
  332. {
  333. affectedUnits.clear();
  334. //TODO: evaluate caster updates (mana usage etc.)
  335. //TODO: evaluate random values
  336. Target spellTarget = transformSpellTarget(target);
  337. effectsToApply = effects->prepare(this, target, spellTarget);
  338. std::set<const battle::Unit *> unitTargets = collectTargets();
  339. auto selector = std::bind(&BattleSpellMechanics::counteringSelector, this, _1);
  340. std::copy(std::begin(unitTargets), std::end(unitTargets), std::back_inserter(affectedUnits));
  341. doRemoveEffects(server, affectedUnits, selector);
  342. for(auto & p : effectsToApply)
  343. p.first->apply(server, this, p.second);
  344. }
  345. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, const battle::Unit * target, ui32 effect)
  346. {
  347. addCustomEffect(sc, target->unitId(), effect);
  348. }
  349. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, ui32 targetId, ui32 effect)
  350. {
  351. CustomEffectInfo customEffect;
  352. customEffect.effect = effect;
  353. customEffect.stack = targetId;
  354. sc.customEffects.push_back(customEffect);
  355. }
  356. std::set<const battle::Unit *> BattleSpellMechanics::collectTargets() const
  357. {
  358. std::set<const battle::Unit *> result;
  359. for(const auto & p : effectsToApply)
  360. {
  361. for(const Destination & d : p.second)
  362. if(d.unitValue)
  363. result.insert(d.unitValue);
  364. }
  365. return result;
  366. }
  367. void BattleSpellMechanics::doRemoveEffects(ServerCallback * server, const std::vector<const battle::Unit *> & targets, const CSelector & selector)
  368. {
  369. SetStackEffect sse;
  370. for(auto unit : targets)
  371. {
  372. std::vector<Bonus> buffer;
  373. auto bl = unit->getBonuses(selector);
  374. for(auto item : *bl)
  375. buffer.emplace_back(*item);
  376. if(!buffer.empty())
  377. sse.toRemove.push_back(std::make_pair(unit->unitId(), buffer));
  378. }
  379. if(!sse.toRemove.empty())
  380. server->apply(&sse);
  381. }
  382. bool BattleSpellMechanics::counteringSelector(const Bonus * bonus) const
  383. {
  384. if(bonus->source != Bonus::SPELL_EFFECT)
  385. return false;
  386. for(const SpellID & id : owner->counteredSpells)
  387. {
  388. if(bonus->sid == id.toEnum())
  389. return true;
  390. }
  391. return false;
  392. }
  393. std::set<BattleHex> BattleSpellMechanics::spellRangeInHexes(BattleHex centralHex) const
  394. {
  395. using namespace SRSLPraserHelpers;
  396. std::set<BattleHex> ret;
  397. std::string rng = owner->getLevelInfo(getRangeLevel()).range + ','; //copy + artificial comma for easier handling
  398. if(rng.size() >= 2 && rng[0] != 'X') //there is at least one hex in range (+artificial comma)
  399. {
  400. std::string number1, number2;
  401. int beg, end;
  402. bool readingFirst = true;
  403. for(auto & elem : rng)
  404. {
  405. if(std::isdigit(elem) ) //reading number
  406. {
  407. if(readingFirst)
  408. number1 += elem;
  409. else
  410. number2 += elem;
  411. }
  412. else if(elem == ',') //comma
  413. {
  414. //calculating variables
  415. if(readingFirst)
  416. {
  417. beg = atoi(number1.c_str());
  418. number1 = "";
  419. }
  420. else
  421. {
  422. end = atoi(number2.c_str());
  423. number2 = "";
  424. }
  425. //obtaining new hexes
  426. std::set<ui16> curLayer;
  427. if(readingFirst)
  428. {
  429. curLayer = getInRange(centralHex, beg, beg);
  430. }
  431. else
  432. {
  433. curLayer = getInRange(centralHex, beg, end);
  434. readingFirst = true;
  435. }
  436. //adding obtained hexes
  437. for(auto & curLayer_it : curLayer)
  438. {
  439. ret.insert(curLayer_it);
  440. }
  441. }
  442. else if(elem == '-') //dash
  443. {
  444. beg = atoi(number1.c_str());
  445. number1 = "";
  446. readingFirst = false;
  447. }
  448. }
  449. }
  450. return ret;
  451. }
  452. Target BattleSpellMechanics::transformSpellTarget(const Target & aimPoint) const
  453. {
  454. Target spellTarget;
  455. if(aimPoint.size() < 1)
  456. {
  457. logGlobal->error("Aimed spell cast with no destination.");
  458. }
  459. else
  460. {
  461. const Destination & primary = aimPoint.at(0);
  462. BattleHex aimPointHex = primary.hexValue;
  463. //transform primary spell target with spell range (if it`s valid), leave anything else to effects
  464. if(aimPointHex.isValid())
  465. {
  466. auto spellRange = spellRangeInHexes(aimPointHex);
  467. for(auto & hex : spellRange)
  468. spellTarget.push_back(Destination(hex));
  469. }
  470. }
  471. if(spellTarget.empty())
  472. spellTarget.push_back(Destination(BattleHex::INVALID));
  473. return spellTarget;
  474. }
  475. std::vector<AimType> BattleSpellMechanics::getTargetTypes() const
  476. {
  477. auto ret = BaseMechanics::getTargetTypes();
  478. if(!ret.empty())
  479. {
  480. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * e, bool & stop)
  481. {
  482. e->adjustTargetTypes(ret);
  483. stop = ret.empty();
  484. });
  485. }
  486. return ret;
  487. }
  488. std::vector<Destination> BattleSpellMechanics::getPossibleDestinations(size_t index, AimType aimType, const Target & current) const
  489. {
  490. //TODO: BattleSpellMechanics::getPossibleDestinations
  491. if(index != 0)
  492. return std::vector<Destination>();
  493. std::vector<Destination> ret;
  494. switch(aimType)
  495. {
  496. case AimType::CREATURE:
  497. case AimType::LOCATION:
  498. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  499. {
  500. BattleHex dest(i);
  501. if(dest.isAvailable())
  502. {
  503. Target tmp = current;
  504. tmp.emplace_back(dest);
  505. detail::ProblemImpl ingored;
  506. if(canBeCastAt(tmp, ingored))
  507. ret.emplace_back(dest);
  508. }
  509. }
  510. break;
  511. case AimType::NO_TARGET:
  512. ret.emplace_back();
  513. break;
  514. default:
  515. break;
  516. }
  517. return ret;
  518. }
  519. bool BattleSpellMechanics::isReceptive(const battle::Unit * target) const
  520. {
  521. return targetCondition->isReceptive(this, target);
  522. }
  523. std::vector<BattleHex> BattleSpellMechanics::rangeInHexes(BattleHex centralHex, bool * outDroppedHexes) const
  524. {
  525. if(isMassive() || !centralHex.isValid())
  526. return std::vector<BattleHex>(1, BattleHex::INVALID);
  527. Target aimPoint;
  528. aimPoint.push_back(Destination(centralHex));
  529. Target spellTarget = transformSpellTarget(aimPoint);
  530. std::set<BattleHex> effectRange;
  531. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * effect, bool & stop)
  532. {
  533. if(!effect->indirect)
  534. {
  535. effect->adjustAffectedHexes(effectRange, this, spellTarget);
  536. }
  537. });
  538. std::vector<BattleHex> ret;
  539. ret.reserve(effectRange.size());
  540. std::copy(effectRange.begin(), effectRange.end(), std::back_inserter(ret));
  541. return ret;
  542. }
  543. const Spell * BattleSpellMechanics::getSpell() const
  544. {
  545. return owner;
  546. }
  547. }
  548. VCMI_LIB_NAMESPACE_END