TargetCondition.cpp 13 KB

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