TargetCondition.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * TargetCondition.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 "TargetCondition.h"
  12. #include "../GameConstants.h"
  13. #include "../CBonusTypeHandler.h"
  14. #include "../battle/CBattleInfoCallback.h"
  15. #include "../battle/Unit.h"
  16. #include "../bonuses/BonusParams.h"
  17. #include "../bonuses/BonusList.h"
  18. #include "../modding/IdentifierStorage.h"
  19. #include "../modding/ModUtility.h"
  20. #include "../serializer/JsonSerializeFormat.h"
  21. #include "../VCMI_Lib.h"
  22. #include <vcmi/spells/Spell.h>
  23. VCMI_LIB_NAMESPACE_BEGIN
  24. namespace spells
  25. {
  26. class TargetConditionItemBase : public TargetConditionItem
  27. {
  28. public:
  29. bool inverted = false;
  30. bool exclusive = false;
  31. void setInverted(bool value) override
  32. {
  33. inverted = value;
  34. }
  35. void setExclusive(bool value) override
  36. {
  37. exclusive = value;
  38. }
  39. bool isExclusive() const override
  40. {
  41. return exclusive;
  42. }
  43. bool isReceptive(const Mechanics * m, const battle::Unit * target) const override
  44. {
  45. bool result = check(m, target);
  46. return inverted != result;
  47. }
  48. protected:
  49. virtual bool check(const Mechanics * m, const battle::Unit * target) const = 0;
  50. };
  51. class SelectorCondition : public TargetConditionItemBase
  52. {
  53. public:
  54. SelectorCondition(const CSelector & csel):
  55. sel(csel)
  56. {
  57. }
  58. SelectorCondition(const CSelector & csel, si32 minVal, si32 maxVal):
  59. sel(csel),
  60. minVal(minVal),
  61. maxVal(maxVal)
  62. {
  63. }
  64. protected:
  65. bool check(const Mechanics * m, const battle::Unit * target) const override
  66. {
  67. if(target->hasBonus(sel)) {
  68. auto b = target->valOfBonuses(sel,"");
  69. return b >= minVal && b <= maxVal;
  70. }
  71. return false;
  72. }
  73. private:
  74. CSelector sel;
  75. si32 minVal = std::numeric_limits<si32>::min();
  76. si32 maxVal = std::numeric_limits<si32>::max();
  77. };
  78. class ResistanceCondition : public TargetConditionItemBase
  79. {
  80. protected:
  81. bool check(const Mechanics * m, const battle::Unit * target) const override
  82. {
  83. if(m->isPositiveSpell()) //Always pass on positive
  84. return true;
  85. return target->magicResistance() < 100;
  86. }
  87. };
  88. class CreatureCondition : public TargetConditionItemBase
  89. {
  90. public:
  91. CreatureCondition(const CreatureID & type_): type(type_) {}
  92. protected:
  93. bool check(const Mechanics * m, const battle::Unit * target) const override
  94. {
  95. return target->creatureId() == type;
  96. }
  97. private:
  98. CreatureID type;
  99. };
  100. class AbsoluteLevelCondition : public TargetConditionItemBase
  101. {
  102. public:
  103. AbsoluteLevelCondition()
  104. {
  105. inverted = false;
  106. exclusive = true;
  107. }
  108. protected:
  109. bool check(const Mechanics * m, const battle::Unit * target) const override
  110. {
  111. if(!m->isMagicalEffect()) //Always pass on non-magical
  112. return true;
  113. std::stringstream cachingStr;
  114. cachingStr << "type_" << vstd::to_underlying(BonusType::LEVEL_SPELL_IMMUNITY) << "addInfo_1";
  115. TConstBonusListPtr levelImmunities = target->getBonuses(Selector::type()(BonusType::LEVEL_SPELL_IMMUNITY).And(Selector::info()(1)), cachingStr.str());
  116. return (levelImmunities->size() == 0 || levelImmunities->totalValue() < m->getSpellLevel() || m->getSpellLevel() <= 0);
  117. }
  118. };
  119. class AbsoluteSpellCondition : public TargetConditionItemBase
  120. {
  121. public:
  122. AbsoluteSpellCondition()
  123. {
  124. inverted = false;
  125. exclusive = true;
  126. }
  127. protected:
  128. bool check(const Mechanics * m, const battle::Unit * target) const override
  129. {
  130. std::stringstream cachingStr;
  131. cachingStr << "type_" << vstd::to_underlying(BonusType::SPELL_IMMUNITY) << "subtype_" << m->getSpellIndex() << "addInfo_1";
  132. return !target->hasBonus(Selector::typeSubtypeInfo(BonusType::SPELL_IMMUNITY, m->getSpellIndex(), 1), cachingStr.str());
  133. }
  134. };
  135. class ElementalCondition : public TargetConditionItemBase
  136. {
  137. public:
  138. ElementalCondition()
  139. {
  140. inverted = true;
  141. exclusive = true;
  142. }
  143. protected:
  144. bool check(const Mechanics * m, const battle::Unit * target) const override
  145. {
  146. bool elementalImmune = false;
  147. auto bearer = target->getBonusBearer();
  148. m->getSpell()->forEachSchool([&](const SpellSchool & cnf, bool & stop)
  149. {
  150. if (bearer->hasBonusOfType(BonusType::SPELL_SCHOOL_IMMUNITY, cnf))
  151. {
  152. elementalImmune = true;
  153. stop = true; //only bonus from one school is used
  154. }
  155. else if(!m->isPositiveSpell()) //negative or indifferent
  156. {
  157. if (bearer->hasBonusOfType(BonusType::NEGATIVE_EFFECTS_IMMUNITY, cnf))
  158. {
  159. elementalImmune = true;
  160. stop = true; //only bonus from one school is used
  161. }
  162. }
  163. });
  164. return elementalImmune;
  165. }
  166. };
  167. class NormalLevelCondition : public TargetConditionItemBase
  168. {
  169. public:
  170. NormalLevelCondition()
  171. {
  172. inverted = false;
  173. exclusive = true;
  174. }
  175. protected:
  176. bool check(const Mechanics * m, const battle::Unit * target) const override
  177. {
  178. if(!m->isMagicalEffect()) //Always pass on non-magical
  179. return true;
  180. TConstBonusListPtr levelImmunities = target->getBonuses(Selector::type()(BonusType::LEVEL_SPELL_IMMUNITY));
  181. return levelImmunities->size() == 0 ||
  182. levelImmunities->totalValue() < m->getSpellLevel() ||
  183. m->getSpellLevel() <= 0;
  184. }
  185. };
  186. class NormalSpellCondition : public TargetConditionItemBase
  187. {
  188. public:
  189. NormalSpellCondition()
  190. {
  191. inverted = false;
  192. exclusive = true;
  193. }
  194. protected:
  195. bool check(const Mechanics * m, const battle::Unit * target) const override
  196. {
  197. return !target->hasBonusOfType(BonusType::SPELL_IMMUNITY, m->getSpellIndex());
  198. }
  199. };
  200. //for Hypnotize
  201. class HealthValueCondition : public TargetConditionItemBase
  202. {
  203. protected:
  204. bool check(const Mechanics * m, const battle::Unit * target) const override
  205. {
  206. //todo: maybe do not resist on passive cast
  207. //TODO: what with other creatures casting hypnotize, Faerie Dragons style?
  208. int64_t subjectHealth = target->getAvailableHealth();
  209. //apply 'damage' bonus for hypnotize, including hero specialty
  210. auto maxHealth = m->applySpellBonus(m->getEffectValue(), target);
  211. return subjectHealth <= maxHealth;
  212. }
  213. };
  214. class SpellEffectCondition : public TargetConditionItemBase
  215. {
  216. public:
  217. SpellEffectCondition(const SpellID & spellID_): spellID(spellID_)
  218. {
  219. std::stringstream builder;
  220. builder << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  221. cachingString = builder.str();
  222. selector = Selector::source(BonusSource::SPELL_EFFECT, spellID.num);
  223. }
  224. protected:
  225. bool check(const Mechanics * m, const battle::Unit * target) const override
  226. {
  227. return target->hasBonus(selector, cachingString);
  228. }
  229. private:
  230. CSelector selector;
  231. std::string cachingString;
  232. SpellID spellID;
  233. };
  234. class ReceptiveFeatureCondition : public TargetConditionItemBase
  235. {
  236. protected:
  237. bool check(const Mechanics * m, const battle::Unit * target) const override
  238. {
  239. return m->isPositiveSpell() && target->hasBonus(selector, cachingString);
  240. }
  241. private:
  242. CSelector selector = Selector::type()(BonusType::RECEPTIVE);
  243. std::string cachingString = "type_RECEPTIVE";
  244. };
  245. class ImmunityNegationCondition : public TargetConditionItemBase
  246. {
  247. protected:
  248. bool check(const Mechanics * m, const battle::Unit * target) const override
  249. {
  250. const bool battleWideNegation = target->hasBonusOfType(BonusType::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  251. const bool heroNegation = target->hasBonusOfType(BonusType::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  252. //Non-magical effects is not affected by orb of vulnerability
  253. if(!m->isMagicalEffect())
  254. return false;
  255. //anyone can cast on artifact holder`s stacks
  256. if(heroNegation)
  257. {
  258. return true;
  259. }
  260. //this stack is from other player
  261. else if(battleWideNegation)
  262. {
  263. if(m->ownerMatches(target, false))
  264. return true;
  265. }
  266. return false;
  267. }
  268. };
  269. class DefaultTargetConditionItemFactory : public TargetConditionItemFactory
  270. {
  271. public:
  272. Object createAbsoluteLevel() const override
  273. {
  274. static std::shared_ptr<TargetConditionItem> antimagicCondition = std::make_shared<AbsoluteLevelCondition>();
  275. return antimagicCondition;
  276. }
  277. Object createAbsoluteSpell() const override
  278. {
  279. static std::shared_ptr<TargetConditionItem> alCondition = std::make_shared<AbsoluteSpellCondition>();
  280. return alCondition;
  281. }
  282. Object createElemental() const override
  283. {
  284. static std::shared_ptr<TargetConditionItem> elementalCondition = std::make_shared<ElementalCondition>();
  285. return elementalCondition;
  286. }
  287. Object createResistance() const override
  288. {
  289. static auto elementalCondition = std::make_shared<ResistanceCondition>();
  290. return elementalCondition;
  291. }
  292. Object createNormalLevel() const override
  293. {
  294. static std::shared_ptr<TargetConditionItem> nlCondition = std::make_shared<NormalLevelCondition>();
  295. return nlCondition;
  296. }
  297. Object createNormalSpell() const override
  298. {
  299. static std::shared_ptr<TargetConditionItem> nsCondition = std::make_shared<NormalSpellCondition>();
  300. return nsCondition;
  301. }
  302. Object createConfigurable(std::string scope, std::string type, std::string identifier) const override
  303. {
  304. if(type == "bonus")
  305. {
  306. //TODO: support custom bonus types
  307. auto it = bonusNameMap.find(identifier);
  308. if(it != bonusNameMap.end())
  309. return std::make_shared<SelectorCondition>(Selector::type()(it->second));
  310. auto params = BonusParams(identifier, "", -1);
  311. if(params.isConverted)
  312. {
  313. if(params.val)
  314. return std::make_shared<SelectorCondition>(params.toSelector(), *params.val, *params.val);
  315. return std::make_shared<SelectorCondition>(params.toSelector());
  316. }
  317. logMod->error("Invalid bonus type %s in spell target condition.", identifier);
  318. }
  319. else if(type == "creature")
  320. {
  321. auto rawId = VLC->identifiers()->getIdentifier(scope, type, identifier, true);
  322. if(rawId)
  323. return std::make_shared<CreatureCondition>(CreatureID(rawId.value()));
  324. else
  325. logMod->error("Invalid creature %s type in spell target condition.", identifier);
  326. }
  327. else if(type == "spell")
  328. {
  329. auto rawId = VLC->identifiers()->getIdentifier(scope, type, identifier, true);
  330. if(rawId)
  331. return std::make_shared<SpellEffectCondition>(SpellID(rawId.value()));
  332. else
  333. logMod->error("Invalid spell %s in spell target condition.", identifier);
  334. }
  335. else if(type == "healthValueSpecial")
  336. {
  337. return std::make_shared<HealthValueCondition>();
  338. }
  339. else
  340. {
  341. logMod->error("Invalid type %s in spell target condition.", type);
  342. }
  343. return Object();
  344. }
  345. Object createFromJsonStruct(const JsonNode & jsonStruct) const override
  346. {
  347. auto type = jsonStruct["type"].String();
  348. auto parameters = jsonStruct["parameters"];
  349. if(type == "selector")
  350. {
  351. auto minVal = std::numeric_limits<si32>::min();
  352. auto maxVal = std::numeric_limits<si32>::max();
  353. if(parameters["minVal"].isNumber())
  354. minVal = parameters["minVal"].Integer();
  355. if(parameters["maxVal"].isNumber())
  356. maxVal = parameters["maxVal"].Integer();
  357. auto sel = JsonUtils::parseSelector(parameters);
  358. return std::make_shared<SelectorCondition>(sel, minVal, maxVal);
  359. }
  360. logMod->error("Invalid type %s in spell target condition.", type);
  361. return Object();
  362. }
  363. Object createReceptiveFeature() const override
  364. {
  365. static std::shared_ptr<TargetConditionItem> condition = std::make_shared<ReceptiveFeatureCondition>();
  366. return condition;
  367. }
  368. Object createImmunityNegation() const override
  369. {
  370. static std::shared_ptr<TargetConditionItem> condition = std::make_shared<ImmunityNegationCondition>();
  371. return condition;
  372. }
  373. };
  374. const TargetConditionItemFactory * TargetConditionItemFactory::getDefault()
  375. {
  376. static std::unique_ptr<TargetConditionItemFactory> singleton;
  377. if(!singleton)
  378. singleton = std::make_unique<DefaultTargetConditionItemFactory>();
  379. return singleton.get();
  380. }
  381. bool TargetCondition::isReceptive(const Mechanics * m, const battle::Unit * target) const
  382. {
  383. if(!check(absolute, m, target))
  384. return false;
  385. for(const auto & item : negation)
  386. {
  387. if(item->isReceptive(m, target))
  388. return true;
  389. }
  390. return check(normal, m, target);
  391. }
  392. void TargetCondition::serializeJson(JsonSerializeFormat & handler, const ItemFactory * itemFactory)
  393. {
  394. if(handler.saving)
  395. {
  396. logGlobal->error("Spell target condition saving is not supported");
  397. return;
  398. }
  399. absolute.clear();
  400. normal.clear();
  401. negation.clear();
  402. absolute.push_back(itemFactory->createAbsoluteSpell());
  403. absolute.push_back(itemFactory->createAbsoluteLevel());
  404. normal.push_back(itemFactory->createElemental());
  405. normal.push_back(itemFactory->createResistance());
  406. normal.push_back(itemFactory->createNormalLevel());
  407. normal.push_back(itemFactory->createNormalSpell());
  408. negation.push_back(itemFactory->createReceptiveFeature());
  409. negation.push_back(itemFactory->createImmunityNegation());
  410. {
  411. auto anyOf = handler.enterStruct("anyOf");
  412. loadConditions(anyOf->getCurrent(), false, false, itemFactory);
  413. }
  414. {
  415. auto allOf = handler.enterStruct("allOf");
  416. loadConditions(allOf->getCurrent(), true, false, itemFactory);
  417. }
  418. {
  419. auto noneOf = handler.enterStruct("noneOf");
  420. loadConditions(noneOf->getCurrent(), true, true, itemFactory);
  421. }
  422. }
  423. bool TargetCondition::check(const ItemVector & condition, const Mechanics * m, const battle::Unit * target) const
  424. {
  425. bool nonExclusiveCheck = false;
  426. bool nonExclusiveExits = false;
  427. for(const auto & item : condition)
  428. {
  429. if(item->isExclusive())
  430. {
  431. if(!item->isReceptive(m, target))
  432. return false;
  433. }
  434. else
  435. {
  436. if(item->isReceptive(m, target))
  437. nonExclusiveCheck = true;
  438. nonExclusiveExits = true;
  439. }
  440. }
  441. return !nonExclusiveExits || nonExclusiveCheck;
  442. }
  443. void TargetCondition::loadConditions(const JsonNode & source, bool exclusive, bool inverted, const ItemFactory * itemFactory)
  444. {
  445. for(const auto & keyValue : source.Struct())
  446. {
  447. bool isAbsolute;
  448. const JsonNode & value = keyValue.second;
  449. if(value.String() == "absolute")
  450. isAbsolute = true;
  451. else if(value.String() == "normal")
  452. isAbsolute = false;
  453. else if(value.isStruct()) //assume conditions have a new struct format
  454. isAbsolute = value["absolute"].Bool();
  455. else
  456. continue;
  457. std::shared_ptr<TargetConditionItem> item;
  458. if(value.isStruct())
  459. item = itemFactory->createFromJsonStruct(value);
  460. else
  461. {
  462. std::string scope;
  463. std::string type;
  464. std::string identifier;
  465. ModUtility::parseIdentifier(keyValue.first, scope, type, identifier);
  466. item = itemFactory->createConfigurable(keyValue.second.meta, type, identifier);
  467. }
  468. if(item)
  469. {
  470. item->setExclusive(exclusive);
  471. item->setInverted(inverted);
  472. if(isAbsolute)
  473. absolute.push_back(item);
  474. else
  475. normal.push_back(item);
  476. }
  477. }
  478. }
  479. }
  480. VCMI_LIB_NAMESPACE_END