BattleSpellMechanics.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. if(sc.activeCast)
  271. {
  272. caster->spendMana(server, spellCost);
  273. if(sc.manaGained > 0)
  274. {
  275. assert(otherHero);
  276. otherHero->spendMana(server, -sc.manaGained);
  277. }
  278. }
  279. // send empty event to client
  280. // temporary(?) workaround to force animations to trigger
  281. StacksInjured fake_event;
  282. server->apply(&fake_event);
  283. }
  284. void BattleSpellMechanics::beforeCast(BattleSpellCast & sc, vstd::RNG & rng, const Target & target)
  285. {
  286. affectedUnits.clear();
  287. Target spellTarget = transformSpellTarget(target);
  288. std::vector <const battle::Unit *> resisted;
  289. auto rangeGen = rng.getInt64Range(0, 99);
  290. auto filterResisted = [&, this](const battle::Unit * unit) -> bool
  291. {
  292. if(isNegativeSpell())
  293. {
  294. //magic resistance
  295. const int prob = std::min(unit->magicResistance(), 100); //probability of resistance in %
  296. if(rangeGen() < prob)
  297. return true;
  298. }
  299. return false;
  300. };
  301. auto filterUnit = [&](const battle::Unit * unit)
  302. {
  303. if(filterResisted(unit))
  304. resisted.push_back(unit);
  305. else
  306. affectedUnits.push_back(unit);
  307. };
  308. //prepare targets
  309. effectsToApply = effects->prepare(this, target, spellTarget);
  310. std::set<const battle::Unit *> unitTargets = collectTargets();
  311. //process them
  312. for(auto unit : unitTargets)
  313. filterUnit(unit);
  314. //and update targets
  315. for(auto & p : effectsToApply)
  316. {
  317. vstd::erase_if(p.second, [&](const Destination & d)
  318. {
  319. if(!d.unitValue)
  320. return false;
  321. return vstd::contains(resisted, d.unitValue);
  322. });
  323. }
  324. if(mode == Mode::MAGIC_MIRROR)
  325. {
  326. if(caster->getCasterUnitId() >= 0)
  327. {
  328. addCustomEffect(sc, caster->getCasterUnitId(), 3);
  329. }
  330. }
  331. for(auto unit : resisted)
  332. addCustomEffect(sc, unit, 78);
  333. }
  334. void BattleSpellMechanics::castEval(ServerCallback * server, const Target & target)
  335. {
  336. affectedUnits.clear();
  337. //TODO: evaluate caster updates (mana usage etc.)
  338. //TODO: evaluate random values
  339. Target spellTarget = transformSpellTarget(target);
  340. effectsToApply = effects->prepare(this, target, spellTarget);
  341. std::set<const battle::Unit *> unitTargets = collectTargets();
  342. auto selector = std::bind(&BattleSpellMechanics::counteringSelector, this, _1);
  343. std::copy(std::begin(unitTargets), std::end(unitTargets), std::back_inserter(affectedUnits));
  344. doRemoveEffects(server, affectedUnits, selector);
  345. for(auto & p : effectsToApply)
  346. p.first->apply(server, this, p.second);
  347. }
  348. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, const battle::Unit * target, ui32 effect)
  349. {
  350. addCustomEffect(sc, target->unitId(), effect);
  351. }
  352. void BattleSpellMechanics::addCustomEffect(BattleSpellCast & sc, ui32 targetId, ui32 effect)
  353. {
  354. CustomEffectInfo customEffect;
  355. customEffect.effect = effect;
  356. customEffect.stack = targetId;
  357. sc.customEffects.push_back(customEffect);
  358. }
  359. std::set<const battle::Unit *> BattleSpellMechanics::collectTargets() const
  360. {
  361. std::set<const battle::Unit *> result;
  362. for(const auto & p : effectsToApply)
  363. {
  364. for(const Destination & d : p.second)
  365. if(d.unitValue)
  366. result.insert(d.unitValue);
  367. }
  368. return result;
  369. }
  370. void BattleSpellMechanics::doRemoveEffects(ServerCallback * server, const std::vector<const battle::Unit *> & targets, const CSelector & selector)
  371. {
  372. SetStackEffect sse;
  373. for(auto unit : targets)
  374. {
  375. std::vector<Bonus> buffer;
  376. auto bl = unit->getBonuses(selector);
  377. for(auto item : *bl)
  378. buffer.emplace_back(*item);
  379. if(!buffer.empty())
  380. sse.toRemove.push_back(std::make_pair(unit->unitId(), buffer));
  381. }
  382. if(!sse.toRemove.empty())
  383. server->apply(&sse);
  384. }
  385. bool BattleSpellMechanics::counteringSelector(const Bonus * bonus) const
  386. {
  387. if(bonus->source != Bonus::SPELL_EFFECT)
  388. return false;
  389. for(const SpellID & id : owner->counteredSpells)
  390. {
  391. if(bonus->sid == id.toEnum())
  392. return true;
  393. }
  394. return false;
  395. }
  396. std::set<BattleHex> BattleSpellMechanics::spellRangeInHexes(BattleHex centralHex) const
  397. {
  398. using namespace SRSLPraserHelpers;
  399. std::set<BattleHex> ret;
  400. std::string rng = owner->getLevelInfo(getRangeLevel()).range + ','; //copy + artificial comma for easier handling
  401. if(rng.size() >= 2 && rng[0] != 'X') //there is at least one hex in range (+artificial comma)
  402. {
  403. std::string number1, number2;
  404. int beg, end;
  405. bool readingFirst = true;
  406. for(auto & elem : rng)
  407. {
  408. if(std::isdigit(elem) ) //reading number
  409. {
  410. if(readingFirst)
  411. number1 += elem;
  412. else
  413. number2 += elem;
  414. }
  415. else if(elem == ',') //comma
  416. {
  417. //calculating variables
  418. if(readingFirst)
  419. {
  420. beg = atoi(number1.c_str());
  421. number1 = "";
  422. }
  423. else
  424. {
  425. end = atoi(number2.c_str());
  426. number2 = "";
  427. }
  428. //obtaining new hexes
  429. std::set<ui16> curLayer;
  430. if(readingFirst)
  431. {
  432. curLayer = getInRange(centralHex, beg, beg);
  433. }
  434. else
  435. {
  436. curLayer = getInRange(centralHex, beg, end);
  437. readingFirst = true;
  438. }
  439. //adding obtained hexes
  440. for(auto & curLayer_it : curLayer)
  441. {
  442. ret.insert(curLayer_it);
  443. }
  444. }
  445. else if(elem == '-') //dash
  446. {
  447. beg = atoi(number1.c_str());
  448. number1 = "";
  449. readingFirst = false;
  450. }
  451. }
  452. }
  453. return ret;
  454. }
  455. Target BattleSpellMechanics::transformSpellTarget(const Target & aimPoint) const
  456. {
  457. Target spellTarget;
  458. if(aimPoint.size() < 1)
  459. {
  460. logGlobal->error("Aimed spell cast with no destination.");
  461. }
  462. else
  463. {
  464. const Destination & primary = aimPoint.at(0);
  465. BattleHex aimPointHex = primary.hexValue;
  466. //transform primary spell target with spell range (if it`s valid), leave anything else to effects
  467. if(aimPointHex.isValid())
  468. {
  469. auto spellRange = spellRangeInHexes(aimPointHex);
  470. for(auto & hex : spellRange)
  471. spellTarget.push_back(Destination(hex));
  472. }
  473. }
  474. if(spellTarget.empty())
  475. spellTarget.push_back(Destination(BattleHex::INVALID));
  476. return spellTarget;
  477. }
  478. std::vector<AimType> BattleSpellMechanics::getTargetTypes() const
  479. {
  480. auto ret = BaseMechanics::getTargetTypes();
  481. if(!ret.empty())
  482. {
  483. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * e, bool & stop)
  484. {
  485. e->adjustTargetTypes(ret);
  486. stop = ret.empty();
  487. });
  488. }
  489. return ret;
  490. }
  491. std::vector<Destination> BattleSpellMechanics::getPossibleDestinations(size_t index, AimType aimType, const Target & current) const
  492. {
  493. //TODO: BattleSpellMechanics::getPossibleDestinations
  494. if(index != 0)
  495. return std::vector<Destination>();
  496. std::vector<Destination> ret;
  497. switch(aimType)
  498. {
  499. case AimType::CREATURE:
  500. case AimType::LOCATION:
  501. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  502. {
  503. BattleHex dest(i);
  504. if(dest.isAvailable())
  505. {
  506. Target tmp = current;
  507. tmp.emplace_back(dest);
  508. detail::ProblemImpl ingored;
  509. if(canBeCastAt(tmp, ingored))
  510. ret.emplace_back(dest);
  511. }
  512. }
  513. break;
  514. case AimType::NO_TARGET:
  515. ret.emplace_back();
  516. break;
  517. default:
  518. break;
  519. }
  520. return ret;
  521. }
  522. bool BattleSpellMechanics::isReceptive(const battle::Unit * target) const
  523. {
  524. return targetCondition->isReceptive(this, target);
  525. }
  526. std::vector<BattleHex> BattleSpellMechanics::rangeInHexes(BattleHex centralHex, bool * outDroppedHexes) const
  527. {
  528. if(isMassive() || !centralHex.isValid())
  529. return std::vector<BattleHex>(1, BattleHex::INVALID);
  530. Target aimPoint;
  531. aimPoint.push_back(Destination(centralHex));
  532. Target spellTarget = transformSpellTarget(aimPoint);
  533. std::set<BattleHex> effectRange;
  534. effects->forEachEffect(getEffectLevel(), [&](const effects::Effect * effect, bool & stop)
  535. {
  536. if(!effect->indirect)
  537. {
  538. effect->adjustAffectedHexes(effectRange, this, spellTarget);
  539. }
  540. });
  541. std::vector<BattleHex> ret;
  542. ret.reserve(effectRange.size());
  543. std::copy(effectRange.begin(), effectRange.end(), std::back_inserter(ret));
  544. return ret;
  545. }
  546. const Spell * BattleSpellMechanics::getSpell() const
  547. {
  548. return owner;
  549. }
  550. }
  551. VCMI_LIB_NAMESPACE_END