ISpellMechanics.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. /*
  2. * ISpellMechanics.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 "ISpellMechanics.h"
  12. #include "../VCMI_Lib.h"
  13. #include "../bonuses/Bonus.h"
  14. #include "../battle/CBattleInfoCallback.h"
  15. #include "../battle/IBattleState.h"
  16. #include "../battle/Unit.h"
  17. #include "../mapObjects/CGHeroInstance.h"
  18. #include "../serializer/JsonDeserializer.h"
  19. #include "../serializer/JsonSerializer.h"
  20. #include "TargetCondition.h"
  21. #include "Problem.h"
  22. #include "AdventureSpellMechanics.h"
  23. #include "BattleSpellMechanics.h"
  24. #include "effects/Effects.h"
  25. #include "effects/Registry.h"
  26. #include "effects/Damage.h"
  27. #include "effects/Timed.h"
  28. #include "CSpellHandler.h"
  29. #include "../IGameCallback.h"//todo: remove
  30. #include "../BattleFieldHandler.h"
  31. #include <vstd/RNG.h>
  32. VCMI_LIB_NAMESPACE_BEGIN
  33. namespace spells
  34. {
  35. static std::shared_ptr<TargetCondition> makeCondition(const CSpell * s)
  36. {
  37. auto res = std::make_shared<TargetCondition>();
  38. JsonDeserializer deser(nullptr, s->targetCondition);
  39. res->serializeJson(deser, TargetConditionItemFactory::getDefault());
  40. return res;
  41. }
  42. class CustomMechanicsFactory : public ISpellMechanicsFactory
  43. {
  44. public:
  45. std::unique_ptr<Mechanics> create(const IBattleCast * event) const override
  46. {
  47. auto * ret = new BattleSpellMechanics(event, effects, targetCondition);
  48. return std::unique_ptr<Mechanics>(ret);
  49. }
  50. protected:
  51. std::shared_ptr<effects::Effects> effects;
  52. CustomMechanicsFactory(const CSpell * s)
  53. : ISpellMechanicsFactory(s), effects(new effects::Effects)
  54. {
  55. targetCondition = makeCondition(s);
  56. }
  57. void loadEffects(const JsonNode & config, const int level)
  58. {
  59. JsonDeserializer deser(nullptr, config);
  60. effects->serializeJson(VLC->spellEffects(), deser, level);
  61. }
  62. private:
  63. std::shared_ptr<IReceptiveCheck> targetCondition;
  64. };
  65. class ConfigurableMechanicsFactory : public CustomMechanicsFactory
  66. {
  67. public:
  68. ConfigurableMechanicsFactory(const CSpell * s)
  69. : CustomMechanicsFactory(s)
  70. {
  71. for(int level = 0; level < GameConstants::SPELL_SCHOOL_LEVELS; level++)
  72. loadEffects(s->getLevelInfo(level).battleEffects, level);
  73. }
  74. };
  75. //to be used for spells configured with old format
  76. class FallbackMechanicsFactory : public CustomMechanicsFactory
  77. {
  78. public:
  79. FallbackMechanicsFactory(const CSpell * s)
  80. : CustomMechanicsFactory(s)
  81. {
  82. for(int level = 0; level < GameConstants::SPELL_SCHOOL_LEVELS; level++)
  83. {
  84. const CSpell::LevelInfo & levelInfo = s->getLevelInfo(level);
  85. assert(levelInfo.battleEffects.isNull());
  86. if(s->isOffensive())
  87. {
  88. //default constructed object should be enough
  89. effects->add("directDamage", std::make_shared<effects::Damage>(), level);
  90. }
  91. std::shared_ptr<effects::Effect> effect;
  92. if(!levelInfo.effects.empty())
  93. {
  94. auto * timed = new effects::Timed();
  95. timed->cumulative = false;
  96. timed->bonus = levelInfo.effects;
  97. effect.reset(timed);
  98. }
  99. if(!levelInfo.cumulativeEffects.empty())
  100. {
  101. auto * timed = new effects::Timed();
  102. timed->cumulative = true;
  103. timed->bonus = levelInfo.cumulativeEffects;
  104. effect.reset(timed);
  105. }
  106. if(effect)
  107. effects->add("timed", effect, level);
  108. }
  109. }
  110. };
  111. BattleCast::BattleCast(const CBattleInfoCallback * cb_, const Caster * caster_, const Mode mode_, const CSpell * spell_):
  112. spell(spell_),
  113. cb(cb_),
  114. caster(caster_),
  115. mode(mode_),
  116. smart(boost::logic::indeterminate),
  117. massive(boost::logic::indeterminate)
  118. {
  119. }
  120. BattleCast::BattleCast(const BattleCast & orig, const Caster * caster_)
  121. : spell(orig.spell),
  122. cb(orig.cb),
  123. caster(caster_),
  124. mode(Mode::MAGIC_MIRROR),
  125. magicSkillLevel(orig.magicSkillLevel),
  126. effectPower(orig.effectPower),
  127. effectDuration(orig.effectDuration),
  128. effectValue(orig.effectValue),
  129. smart(true),
  130. massive(false)
  131. {
  132. }
  133. BattleCast::~BattleCast() = default;
  134. const CSpell * BattleCast::getSpell() const
  135. {
  136. return spell;
  137. }
  138. Mode BattleCast::getMode() const
  139. {
  140. return mode;
  141. }
  142. const Caster * BattleCast::getCaster() const
  143. {
  144. return caster;
  145. }
  146. const CBattleInfoCallback * BattleCast::getBattle() const
  147. {
  148. return cb;
  149. }
  150. BattleCast::OptionalValue BattleCast::getSpellLevel() const
  151. {
  152. return magicSkillLevel;
  153. }
  154. BattleCast::OptionalValue BattleCast::getEffectPower() const
  155. {
  156. return effectPower;
  157. }
  158. BattleCast::OptionalValue BattleCast::getEffectDuration() const
  159. {
  160. return effectDuration;
  161. }
  162. BattleCast::OptionalValue64 BattleCast::getEffectValue() const
  163. {
  164. return effectValue;
  165. }
  166. boost::logic::tribool BattleCast::isSmart() const
  167. {
  168. return smart;
  169. }
  170. boost::logic::tribool BattleCast::isMassive() const
  171. {
  172. return massive;
  173. }
  174. void BattleCast::setSpellLevel(BattleCast::Value value)
  175. {
  176. magicSkillLevel = std::make_optional(value);
  177. }
  178. void BattleCast::setEffectPower(BattleCast::Value value)
  179. {
  180. effectPower = std::make_optional(value);
  181. }
  182. void BattleCast::setEffectDuration(BattleCast::Value value)
  183. {
  184. effectDuration = std::make_optional(value);
  185. }
  186. void BattleCast::setEffectValue(BattleCast::Value64 value)
  187. {
  188. effectValue = std::make_optional(value);
  189. }
  190. void BattleCast::applyEffects(ServerCallback * server, const Target & target, bool indirect, bool ignoreImmunity) const
  191. {
  192. auto m = spell->battleMechanics(this);
  193. m->applyEffects(server, target, indirect, ignoreImmunity);
  194. }
  195. void BattleCast::cast(ServerCallback * server, Target target)
  196. {
  197. if(target.empty())
  198. target.emplace_back();
  199. auto m = spell->battleMechanics(this);
  200. const battle::Unit * mainTarget = nullptr;
  201. if(target.front().unitValue)
  202. {
  203. mainTarget = target.front().unitValue;
  204. }
  205. else if(target.front().hexValue.isValid())
  206. {
  207. mainTarget = cb->battleGetUnitByPos(target.front().hexValue, true);
  208. }
  209. bool tryMagicMirror = (mainTarget != nullptr) && (mode == Mode::HERO || mode == Mode::CREATURE_ACTIVE);//TODO: recheck
  210. tryMagicMirror = tryMagicMirror && (mainTarget->unitOwner() != caster->getCasterOwner()) && !spell->isPositive();//TODO: recheck
  211. m->cast(server, target);
  212. //Magic Mirror effect
  213. if(tryMagicMirror)
  214. {
  215. const std::string magicMirrorCacheStr = "type_MAGIC_MIRROR";
  216. static const auto magicMirrorSelector = Selector::type()(BonusType::MAGIC_MIRROR);
  217. const int mirrorChance = mainTarget->valOfBonuses(magicMirrorSelector, magicMirrorCacheStr);
  218. if(server->getRNG()->nextInt(0, 99) < mirrorChance)
  219. {
  220. auto mirrorTargets = cb->battleGetUnitsIf([this](const battle::Unit * unit)
  221. {
  222. //Get all caster stacks. Magic mirror can reflect to immune creature (with no effect)
  223. return unit->unitOwner() == caster->getCasterOwner() && unit->isValidTarget(true);
  224. });
  225. if(!mirrorTargets.empty())
  226. {
  227. const auto * mirrorDestination = (*RandomGeneratorUtil::nextItem(mirrorTargets, *server->getRNG()));
  228. Target mirrorTarget;
  229. mirrorTarget.emplace_back(mirrorDestination);
  230. BattleCast mirror(*this, mainTarget);
  231. mirror.cast(server, mirrorTarget);
  232. }
  233. }
  234. }
  235. }
  236. void BattleCast::castEval(ServerCallback * server, Target target)
  237. {
  238. //TODO: make equivalent to normal cast
  239. if(target.empty())
  240. target.emplace_back();
  241. auto m = spell->battleMechanics(this);
  242. //TODO: reflection
  243. //TODO: random effects evaluation
  244. m->castEval(server, target);
  245. }
  246. bool BattleCast::castIfPossible(ServerCallback * server, Target target)
  247. {
  248. if(spell->canBeCast(cb, mode, caster))
  249. {
  250. cast(server, std::move(target));
  251. return true;
  252. }
  253. return false;
  254. }
  255. std::vector<Target> BattleCast::findPotentialTargets(bool fast) const
  256. {
  257. //TODO: for more than 2 destinations per target much more efficient algorithm is required
  258. auto m = spell->battleMechanics(this);
  259. auto targetTypes = m->getTargetTypes();
  260. if(targetTypes.empty() || targetTypes.size() > 2)
  261. {
  262. return std::vector<Target>();
  263. }
  264. else
  265. {
  266. std::vector<Target> previous;
  267. std::vector<Target> next;
  268. for(size_t index = 0; index < targetTypes.size(); index++)
  269. {
  270. std::swap(previous, next);
  271. next.clear();
  272. std::vector<Destination> destinations;
  273. if(previous.empty())
  274. {
  275. Target empty;
  276. destinations = m->getPossibleDestinations(index, targetTypes.at(index), empty, fast);
  277. for(auto & destination : destinations)
  278. {
  279. Target target;
  280. target.emplace_back(destination);
  281. next.push_back(target);
  282. }
  283. }
  284. else
  285. {
  286. for(const Target & current : previous)
  287. {
  288. destinations = m->getPossibleDestinations(index, targetTypes.at(index), current, fast);
  289. for(auto & destination : destinations)
  290. {
  291. Target target = current;
  292. target.emplace_back(destination);
  293. next.push_back(target);
  294. }
  295. }
  296. }
  297. if(next.empty())
  298. break;
  299. }
  300. return next;
  301. }
  302. }
  303. ///ISpellMechanicsFactory
  304. ISpellMechanicsFactory::ISpellMechanicsFactory(const CSpell * s)
  305. : spell(s)
  306. {
  307. }
  308. //must be instantiated in .cpp file for access to complete types of all member fields
  309. ISpellMechanicsFactory::~ISpellMechanicsFactory() = default;
  310. std::unique_ptr<ISpellMechanicsFactory> ISpellMechanicsFactory::get(const CSpell * s)
  311. {
  312. if(s->hasBattleEffects())
  313. return std::make_unique<ConfigurableMechanicsFactory>(s);
  314. else
  315. return std::make_unique<FallbackMechanicsFactory>(s);
  316. }
  317. ///Mechanics
  318. Mechanics::Mechanics()
  319. : caster(nullptr),
  320. casterSide(BattleSide::NONE)
  321. {
  322. }
  323. Mechanics::~Mechanics() = default;
  324. BaseMechanics::BaseMechanics(const IBattleCast * event):
  325. owner(event->getSpell()),
  326. mode(event->getMode()),
  327. smart(event->isSmart()),
  328. massive(event->isMassive()),
  329. cb(event->getBattle())
  330. {
  331. caster = event->getCaster();
  332. casterSide = cb->playerToSide(caster->getCasterOwner());
  333. {
  334. auto value = event->getSpellLevel();
  335. rangeLevel = value.value_or(caster->getSpellSchoolLevel(owner));
  336. vstd::abetween(rangeLevel, 0, 3);
  337. }
  338. {
  339. auto value = event->getSpellLevel();
  340. effectLevel = value.value_or(caster->getEffectLevel(owner));
  341. vstd::abetween(effectLevel, 0, 3);
  342. }
  343. {
  344. auto value = event->getEffectPower();
  345. effectPower = value.value_or(caster->getEffectPower(owner));
  346. vstd::amax(effectPower, 0);
  347. }
  348. {
  349. auto value = event->getEffectDuration();
  350. effectDuration = value.value_or(caster->getEnchantPower(owner));
  351. vstd::amax(effectDuration, 0); //???
  352. }
  353. {
  354. auto value = event->getEffectValue();
  355. auto casterValue = caster->getEffectValue(owner) ? caster->getEffectValue(owner) : owner->calculateRawEffectValue(effectLevel, effectPower, 1);
  356. effectValue = value.value_or(casterValue);
  357. vstd::amax(effectValue, 0);
  358. }
  359. }
  360. BaseMechanics::~BaseMechanics() = default;
  361. bool BaseMechanics::adaptGenericProblem(Problem & target) const
  362. {
  363. MetaString text;
  364. // %s recites the incantations but they seem to have no effect.
  365. text.appendLocalString(EMetaText::GENERAL_TXT, 541);
  366. assert(caster);
  367. caster->getCasterName(text);
  368. target.add(std::move(text), spells::Problem::NORMAL);
  369. return false;
  370. }
  371. bool BaseMechanics::adaptProblem(ESpellCastProblem source, Problem & target) const
  372. {
  373. if(source == ESpellCastProblem::OK)
  374. return true;
  375. switch(source)
  376. {
  377. case ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED:
  378. {
  379. MetaString text;
  380. //TODO: refactor
  381. const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
  382. if(!hero)
  383. return adaptGenericProblem(target);
  384. //Recanter's Cloak or similar effect. Try to retrieve bonus
  385. const auto b = hero->getFirstBonus(Selector::type()(BonusType::BLOCK_MAGIC_ABOVE));
  386. //TODO what about other values and non-artifact sources?
  387. if(b && b->val == 2 && b->source == BonusSource::ARTIFACT)
  388. {
  389. //The %s prevents %s from casting 3rd level or higher spells.
  390. text.appendLocalString(EMetaText::GENERAL_TXT, 536);
  391. text.replaceName(b->sid.as<ArtifactID>());
  392. caster->getCasterName(text);
  393. target.add(std::move(text), spells::Problem::NORMAL);
  394. }
  395. else if(b && b->source == BonusSource::TERRAIN_OVERLAY && VLC->battlefields()->getById(b->sid.as<BattleField>())->identifier == "cursed_ground")
  396. {
  397. text.appendLocalString(EMetaText::GENERAL_TXT, 537);
  398. target.add(std::move(text), spells::Problem::NORMAL);
  399. }
  400. else
  401. {
  402. return adaptGenericProblem(target);
  403. }
  404. }
  405. break;
  406. case ESpellCastProblem::WRONG_SPELL_TARGET:
  407. case ESpellCastProblem::STACK_IMMUNE_TO_SPELL:
  408. case ESpellCastProblem::NO_APPROPRIATE_TARGET:
  409. {
  410. MetaString text;
  411. text.appendLocalString(EMetaText::GENERAL_TXT, 185);
  412. target.add(std::move(text), spells::Problem::NORMAL);
  413. }
  414. break;
  415. case ESpellCastProblem::INVALID:
  416. {
  417. MetaString text;
  418. text.appendRawString("Internal error during check of spell cast.");
  419. target.add(std::move(text), spells::Problem::CRITICAL);
  420. }
  421. break;
  422. default:
  423. return adaptGenericProblem(target);
  424. }
  425. return false;
  426. }
  427. int32_t BaseMechanics::getSpellIndex() const
  428. {
  429. return getSpellId().toEnum();
  430. }
  431. SpellID BaseMechanics::getSpellId() const
  432. {
  433. return owner->getId();
  434. }
  435. std::string BaseMechanics::getSpellName() const
  436. {
  437. return owner->getNameTranslated();
  438. }
  439. int32_t BaseMechanics::getSpellLevel() const
  440. {
  441. return owner->getLevel();
  442. }
  443. bool BaseMechanics::isSmart() const
  444. {
  445. if(boost::logic::indeterminate(smart))
  446. {
  447. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  448. return targetInfo.smart;
  449. }
  450. else
  451. {
  452. return (bool)smart;
  453. }
  454. }
  455. bool BaseMechanics::isMassive() const
  456. {
  457. if(boost::logic::indeterminate(massive))
  458. {
  459. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  460. return targetInfo.massive;
  461. }
  462. else
  463. {
  464. return (bool)massive;
  465. }
  466. }
  467. bool BaseMechanics::requiresClearTiles() const
  468. {
  469. const CSpell::TargetInfo targetInfo(owner, getRangeLevel(), mode);
  470. return targetInfo.clearAffected;
  471. }
  472. bool BaseMechanics::alwaysHitFirstTarget() const
  473. {
  474. return mode == Mode::SPELL_LIKE_ATTACK;
  475. }
  476. bool BaseMechanics::isNegativeSpell() const
  477. {
  478. return owner->isNegative();
  479. }
  480. bool BaseMechanics::isPositiveSpell() const
  481. {
  482. return owner->isPositive();
  483. }
  484. bool BaseMechanics::isMagicalEffect() const
  485. {
  486. return owner->isMagical();
  487. }
  488. int64_t BaseMechanics::adjustEffectValue(const battle::Unit * target) const
  489. {
  490. return owner->adjustRawDamage(caster, target, getEffectValue());
  491. }
  492. int64_t BaseMechanics::applySpellBonus(int64_t value, const battle::Unit * target) const
  493. {
  494. return caster->getSpellBonus(owner, value, target);
  495. }
  496. int64_t BaseMechanics::applySpecificSpellBonus(int64_t value) const
  497. {
  498. return caster->getSpecificSpellBonus(owner, value);
  499. }
  500. int64_t BaseMechanics::calculateRawEffectValue(int32_t basePowerMultiplier, int32_t levelPowerMultiplier) const
  501. {
  502. return owner->calculateRawEffectValue(getEffectLevel(), basePowerMultiplier, levelPowerMultiplier);
  503. }
  504. bool BaseMechanics::ownerMatches(const battle::Unit * unit) const
  505. {
  506. return ownerMatches(unit, owner->getPositiveness());
  507. }
  508. bool BaseMechanics::ownerMatches(const battle::Unit * unit, const boost::logic::tribool positivness) const
  509. {
  510. return cb->battleMatchOwner(caster->getCasterOwner(), unit, positivness);
  511. }
  512. IBattleCast::Value BaseMechanics::getEffectLevel() const
  513. {
  514. return effectLevel;
  515. }
  516. IBattleCast::Value BaseMechanics::getRangeLevel() const
  517. {
  518. return rangeLevel;
  519. }
  520. IBattleCast::Value BaseMechanics::getEffectPower() const
  521. {
  522. return effectPower;
  523. }
  524. IBattleCast::Value BaseMechanics::getEffectDuration() const
  525. {
  526. return effectDuration;
  527. }
  528. IBattleCast::Value64 BaseMechanics::getEffectValue() const
  529. {
  530. return effectValue;
  531. }
  532. PlayerColor BaseMechanics::getCasterColor() const
  533. {
  534. return caster->getCasterOwner();
  535. }
  536. std::vector<AimType> BaseMechanics::getTargetTypes() const
  537. {
  538. std::vector<AimType> ret;
  539. detail::ProblemImpl ignored;
  540. if(canBeCast(ignored))
  541. {
  542. auto spellTargetType = owner->getTargetType();
  543. if(isMassive())
  544. spellTargetType = AimType::NO_TARGET;
  545. else if(spellTargetType == AimType::OBSTACLE)
  546. spellTargetType = AimType::LOCATION;
  547. ret.push_back(spellTargetType);
  548. }
  549. return ret;
  550. }
  551. const CreatureService * BaseMechanics::creatures() const
  552. {
  553. return VLC->creatures(); //todo: redirect
  554. }
  555. #if SCRIPTING_ENABLED
  556. const scripting::Service * BaseMechanics::scripts() const
  557. {
  558. return VLC->scripts(); //todo: redirect
  559. }
  560. #endif
  561. const Service * BaseMechanics::spells() const
  562. {
  563. return VLC->spells(); //todo: redirect
  564. }
  565. const CBattleInfoCallback * BaseMechanics::battle() const
  566. {
  567. return cb;
  568. }
  569. } //namespace spells
  570. ///IAdventureSpellMechanics
  571. IAdventureSpellMechanics::IAdventureSpellMechanics(const CSpell * s)
  572. : owner(s)
  573. {
  574. }
  575. std::unique_ptr<IAdventureSpellMechanics> IAdventureSpellMechanics::createMechanics(const CSpell * s)
  576. {
  577. switch(s->id.toEnum())
  578. {
  579. case SpellID::SUMMON_BOAT:
  580. return std::make_unique<SummonBoatMechanics>(s);
  581. case SpellID::SCUTTLE_BOAT:
  582. return std::make_unique<ScuttleBoatMechanics>(s);
  583. case SpellID::DIMENSION_DOOR:
  584. return std::make_unique<DimensionDoorMechanics>(s);
  585. case SpellID::FLY:
  586. case SpellID::WATER_WALK:
  587. case SpellID::VISIONS:
  588. case SpellID::DISGUISE:
  589. return std::make_unique<AdventureSpellMechanics>(s); //implemented using bonus system
  590. case SpellID::TOWN_PORTAL:
  591. return std::make_unique<TownPortalMechanics>(s);
  592. case SpellID::VIEW_EARTH:
  593. return std::make_unique<ViewEarthMechanics>(s);
  594. case SpellID::VIEW_AIR:
  595. return std::make_unique<ViewAirMechanics>(s);
  596. default:
  597. return s->isCombat() ? std::unique_ptr<IAdventureSpellMechanics>() : std::make_unique<AdventureSpellMechanics>(s);
  598. }
  599. }
  600. VCMI_LIB_NAMESPACE_END