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