BattleSpellMechanics.cpp 16 KB

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