ISpellMechanics.cpp 17 KB

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