ISpellMechanics.cpp 15 KB

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