TargetCondition.cpp 13 KB

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