JsonBonus.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /*
  2. * JsonUtils.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 "JsonBonus.h"
  12. #include "JsonValidator.h"
  13. #include "../texts/CGeneralTextHandler.h"
  14. #include "../GameLibrary.h"
  15. #include "../bonuses/BonusParams.h"
  16. #include "../bonuses/Limiters.h"
  17. #include "../bonuses/Propagators.h"
  18. #include "../bonuses/Updaters.h"
  19. #include "../constants/StringConstants.h"
  20. #include "../modding/IdentifierStorage.h"
  21. VCMI_LIB_USING_NAMESPACE
  22. template <typename T>
  23. const T parseByMap(const std::map<std::string, T> & map, const JsonNode * val, const std::string & err)
  24. {
  25. if (!val->isNull())
  26. {
  27. const std::string & type = val->String();
  28. auto it = map.find(type);
  29. if (it == map.end())
  30. {
  31. logMod->error("Error: invalid %s%s.", err, type);
  32. return {};
  33. }
  34. else
  35. {
  36. return it->second;
  37. }
  38. }
  39. else
  40. return {};
  41. }
  42. template <typename T>
  43. const T parseByMapN(const std::map<std::string, T> & map, const JsonNode * val, const std::string & err)
  44. {
  45. if(val->isNumber())
  46. return static_cast<T>(val->Integer());
  47. else
  48. return parseByMap<T>(map, val, err);
  49. }
  50. static void loadBonusSubtype(BonusSubtypeID & subtype, BonusType type, const JsonNode & node)
  51. {
  52. if (node.isNull())
  53. {
  54. subtype = BonusSubtypeID();
  55. return;
  56. }
  57. if (node.isNumber()) // Compatibility code for 1.3 or older
  58. {
  59. logMod->warn("Bonus subtype must be string! (%s)", node.getModScope());
  60. subtype = BonusCustomSubtype(node.Integer());
  61. return;
  62. }
  63. if (!node.isString())
  64. {
  65. logMod->warn("Bonus subtype must be string! (%s)", node.getModScope());
  66. subtype = BonusSubtypeID();
  67. return;
  68. }
  69. switch (type)
  70. {
  71. case BonusType::MAGIC_SCHOOL_SKILL:
  72. case BonusType::SPELL_DAMAGE:
  73. case BonusType::SPELLS_OF_SCHOOL:
  74. case BonusType::SPELL_DAMAGE_REDUCTION:
  75. case BonusType::SPELL_SCHOOL_IMMUNITY:
  76. case BonusType::NEGATIVE_EFFECTS_IMMUNITY:
  77. {
  78. LIBRARY->identifiers()->requestIdentifier( "spellSchool", node, [&subtype](int32_t identifier)
  79. {
  80. subtype = SpellSchool(identifier);
  81. });
  82. break;
  83. }
  84. case BonusType::NO_TERRAIN_PENALTY:
  85. {
  86. LIBRARY->identifiers()->requestIdentifier( "terrain", node, [&subtype](int32_t identifier)
  87. {
  88. subtype = TerrainId(identifier);
  89. });
  90. break;
  91. }
  92. case BonusType::PRIMARY_SKILL:
  93. {
  94. LIBRARY->identifiers()->requestIdentifier( "primarySkill", node, [&subtype](int32_t identifier)
  95. {
  96. subtype = PrimarySkill(identifier);
  97. });
  98. break;
  99. }
  100. case BonusType::IMPROVED_NECROMANCY:
  101. case BonusType::HERO_GRANTS_ATTACKS:
  102. case BonusType::BONUS_DAMAGE_CHANCE:
  103. case BonusType::BONUS_DAMAGE_PERCENTAGE:
  104. case BonusType::SPECIAL_UPGRADE:
  105. case BonusType::HATE:
  106. case BonusType::SUMMON_GUARDIANS:
  107. case BonusType::MANUAL_CONTROL:
  108. {
  109. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&subtype](int32_t identifier)
  110. {
  111. subtype = CreatureID(identifier);
  112. });
  113. break;
  114. }
  115. case BonusType::SPELL_IMMUNITY:
  116. case BonusType::SPELL_DURATION:
  117. case BonusType::SPECIAL_ADD_VALUE_ENCHANT:
  118. case BonusType::SPECIAL_FIXED_VALUE_ENCHANT:
  119. case BonusType::SPECIAL_PECULIAR_ENCHANT:
  120. case BonusType::SPECIAL_SPELL_LEV:
  121. case BonusType::SPECIFIC_SPELL_DAMAGE:
  122. case BonusType::SPELL:
  123. case BonusType::OPENING_BATTLE_SPELL:
  124. case BonusType::SPELL_LIKE_ATTACK:
  125. case BonusType::CATAPULT:
  126. case BonusType::CATAPULT_EXTRA_SHOTS:
  127. case BonusType::HEALER:
  128. case BonusType::SPELLCASTER:
  129. case BonusType::ENCHANTER:
  130. case BonusType::SPELL_AFTER_ATTACK:
  131. case BonusType::SPELL_BEFORE_ATTACK:
  132. case BonusType::SPECIFIC_SPELL_POWER:
  133. case BonusType::ENCHANTED:
  134. case BonusType::MORE_DAMAGE_FROM_SPELL:
  135. case BonusType::NOT_ACTIVE:
  136. {
  137. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&subtype](int32_t identifier)
  138. {
  139. subtype = SpellID(identifier);
  140. });
  141. break;
  142. }
  143. case BonusType::GENERATE_RESOURCE:
  144. case BonusType::RESOURCES_CONSTANT_BOOST:
  145. case BonusType::RESOURCES_TOWN_MULTIPLYING_BOOST:
  146. {
  147. LIBRARY->identifiers()->requestIdentifier( "resource", node, [&subtype](int32_t identifier)
  148. {
  149. subtype = GameResID(identifier);
  150. });
  151. break;
  152. }
  153. case BonusType::MOVEMENT:
  154. case BonusType::WATER_WALKING:
  155. case BonusType::FLYING_MOVEMENT:
  156. case BonusType::NEGATE_ALL_NATURAL_IMMUNITIES:
  157. case BonusType::CREATURE_DAMAGE:
  158. case BonusType::FLYING:
  159. case BonusType::FIRST_STRIKE:
  160. case BonusType::GENERAL_DAMAGE_REDUCTION:
  161. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  162. case BonusType::SOUL_STEAL:
  163. case BonusType::TRANSMUTATION:
  164. case BonusType::DESTRUCTION:
  165. case BonusType::DEATH_STARE:
  166. case BonusType::REBIRTH:
  167. case BonusType::VISIONS:
  168. case BonusType::SPELLS_OF_LEVEL: // spell level
  169. case BonusType::CREATURE_GROWTH: // creature level
  170. {
  171. LIBRARY->identifiers()->requestIdentifier( "bonusSubtype", node, [&subtype](int32_t identifier)
  172. {
  173. subtype = BonusCustomSubtype(identifier);
  174. });
  175. break;
  176. }
  177. default:
  178. for(const auto & i : bonusNameMap)
  179. if(i.second == type)
  180. logMod->warn("Bonus type %s does not supports subtypes!", i.first );
  181. subtype = BonusSubtypeID();
  182. }
  183. }
  184. static void loadBonusAddInfo(CAddInfo & var, BonusType type, const JsonNode & node)
  185. {
  186. const auto & getFirstValue = [](const JsonNode & jsonNode) -> const JsonNode &
  187. {
  188. if (jsonNode.isVector())
  189. return jsonNode[0];
  190. else
  191. return jsonNode;
  192. };
  193. const JsonNode & value = node["addInfo"];
  194. if (value.isNull())
  195. return;
  196. switch (type)
  197. {
  198. case BonusType::IMPROVED_NECROMANCY:
  199. case BonusType::SPECIAL_ADD_VALUE_ENCHANT:
  200. case BonusType::SPECIAL_FIXED_VALUE_ENCHANT:
  201. case BonusType::DESTRUCTION:
  202. case BonusType::LIMITED_SHOOTING_RANGE:
  203. case BonusType::ACID_BREATH:
  204. case BonusType::BIND_EFFECT:
  205. case BonusType::SPELLCASTER:
  206. case BonusType::FEROCITY:
  207. case BonusType::PRIMARY_SKILL:
  208. case BonusType::ENCHANTER:
  209. case BonusType::SPECIAL_PECULIAR_ENCHANT:
  210. // 1 number
  211. var = getFirstValue(value).Integer();
  212. break;
  213. case BonusType::SPECIAL_UPGRADE:
  214. case BonusType::TRANSMUTATION:
  215. // 1 creature ID
  216. LIBRARY->identifiers()->requestIdentifier("creature", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  217. break;
  218. case BonusType::DEATH_STARE:
  219. // 1 spell ID
  220. LIBRARY->identifiers()->requestIdentifier("spell", getFirstValue(value), [&](si32 identifier) { var = identifier; });
  221. break;
  222. case BonusType::SPELL_BEFORE_ATTACK:
  223. case BonusType::SPELL_AFTER_ATTACK:
  224. // 3 numbers
  225. var.resize(3);
  226. var[0] = value[0].Integer();
  227. var[1] = value[1].Integer();
  228. var[2] = value[2].Integer();
  229. break;
  230. case BonusType::MULTIHEX_UNIT_ATTACK:
  231. case BonusType::MULTIHEX_ENEMY_ATTACK:
  232. case BonusType::MULTIHEX_ANIMATION:
  233. for (const auto & sequence : value.Vector())
  234. {
  235. static const std::map<char, int> charToDirection = {
  236. { 'f', 1 }, { 'l', 6}, {'r', 2}, {'b', 4}
  237. };
  238. int converted = 0;
  239. for (const auto & ch : boost::adaptors::reverse(sequence.String()))
  240. {
  241. char chLower = std::tolower(ch);
  242. if (charToDirection.count(chLower))
  243. converted = 10 * converted + charToDirection.at(chLower);
  244. }
  245. var.push_back(converted);
  246. }
  247. break;
  248. default:
  249. for(const auto & i : bonusNameMap)
  250. if(i.second == type)
  251. logMod->warn("Bonus type %s does not supports addInfo!", i.first );
  252. }
  253. }
  254. static void loadBonusSourceInstance(BonusSourceID & sourceInstance, BonusSource sourceType, const JsonNode & node)
  255. {
  256. if (node.isNull())
  257. {
  258. sourceInstance = BonusCustomSource();
  259. return;
  260. }
  261. if (node.isNumber()) // Compatibility code for 1.3 or older
  262. {
  263. logMod->warn("Bonus source must be string!");
  264. sourceInstance = BonusCustomSource(node.Integer());
  265. return;
  266. }
  267. if (!node.isString())
  268. {
  269. logMod->warn("Bonus source must be string!");
  270. sourceInstance = BonusCustomSource();
  271. return;
  272. }
  273. switch (sourceType)
  274. {
  275. case BonusSource::ARTIFACT:
  276. case BonusSource::ARTIFACT_INSTANCE:
  277. {
  278. LIBRARY->identifiers()->requestIdentifier( "artifact", node, [&sourceInstance](int32_t identifier)
  279. {
  280. sourceInstance = ArtifactID(identifier);
  281. });
  282. break;
  283. }
  284. case BonusSource::OBJECT_TYPE:
  285. {
  286. LIBRARY->identifiers()->requestIdentifier( "object", node, [&sourceInstance](int32_t identifier)
  287. {
  288. sourceInstance = Obj(identifier);
  289. });
  290. break;
  291. }
  292. case BonusSource::OBJECT_INSTANCE:
  293. case BonusSource::HERO_BASE_SKILL:
  294. sourceInstance = ObjectInstanceID(ObjectInstanceID::decode(node.String()));
  295. break;
  296. case BonusSource::CREATURE_ABILITY:
  297. {
  298. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&sourceInstance](int32_t identifier)
  299. {
  300. sourceInstance = CreatureID(identifier);
  301. });
  302. break;
  303. }
  304. case BonusSource::TERRAIN_OVERLAY:
  305. {
  306. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  307. {
  308. sourceInstance = BattleField(identifier);
  309. });
  310. break;
  311. }
  312. case BonusSource::SPELL_EFFECT:
  313. {
  314. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  315. {
  316. sourceInstance = SpellID(identifier);
  317. });
  318. break;
  319. }
  320. case BonusSource::TOWN_STRUCTURE:
  321. assert(0); // TODO
  322. sourceInstance = BuildingTypeUniqueID();
  323. break;
  324. case BonusSource::SECONDARY_SKILL:
  325. {
  326. LIBRARY->identifiers()->requestIdentifier( "secondarySkill", node, [&sourceInstance](int32_t identifier)
  327. {
  328. sourceInstance = SecondarySkill(identifier);
  329. });
  330. break;
  331. }
  332. case BonusSource::HERO_SPECIAL:
  333. {
  334. LIBRARY->identifiers()->requestIdentifier( "hero", node, [&sourceInstance](int32_t identifier)
  335. {
  336. sourceInstance = HeroTypeID(identifier);
  337. });
  338. break;
  339. }
  340. case BonusSource::CAMPAIGN_BONUS:
  341. sourceInstance = CampaignScenarioID(CampaignScenarioID::decode(node.String()));
  342. break;
  343. case BonusSource::ARMY:
  344. case BonusSource::STACK_EXPERIENCE:
  345. case BonusSource::COMMANDER:
  346. case BonusSource::GLOBAL:
  347. case BonusSource::TERRAIN_NATIVE:
  348. case BonusSource::OTHER:
  349. default:
  350. sourceInstance = BonusSourceID();
  351. break;
  352. }
  353. }
  354. static BonusParams convertDeprecatedBonus(const JsonNode &ability)
  355. {
  356. if(vstd::contains(deprecatedBonusSet, ability["type"].String()))
  357. {
  358. logMod->warn("There is deprecated bonus found:\n%s\nTrying to convert...", ability.toString());
  359. auto params = BonusParams(ability["type"].String(),
  360. ability["subtype"].isString() ? ability["subtype"].String() : "",
  361. ability["subtype"].isNumber() ? ability["subtype"].Integer() : -1);
  362. if(params.isConverted)
  363. {
  364. if(ability["type"].String() == "SECONDARY_SKILL_PREMY" && bonusValueMap.find(ability["valueType"].String())->second == BonusValueType::PERCENT_TO_BASE) //assume secondary skill special
  365. {
  366. params.valueType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  367. params.targetType = BonusSource::SECONDARY_SKILL;
  368. }
  369. logMod->warn("Please, use this bonus:\n%s\nConverted successfully!", params.toJson().toString());
  370. return params;
  371. }
  372. else
  373. logMod->error("Cannot convert bonus!\n%s", ability.toString());
  374. }
  375. BonusParams ret;
  376. ret.isConverted = false;
  377. return ret;
  378. }
  379. static TUpdaterPtr parseUpdater(const JsonNode & updaterJson)
  380. {
  381. const std::map<std::string, std::shared_ptr<IUpdater>> bonusUpdaterMap =
  382. {
  383. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  384. {"TIMES_HERO_LEVEL_DIVIDE_STACK_LEVEL", std::make_shared<TimesHeroLevelDivideStackLevelUpdater>()},
  385. {"DIVIDE_STACK_LEVEL", std::make_shared<DivideStackLevelUpdater>()},
  386. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()},
  387. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>()}
  388. };
  389. switch(updaterJson.getType())
  390. {
  391. case JsonNode::JsonType::DATA_STRING:
  392. {
  393. auto it = bonusUpdaterMap.find(updaterJson.String());
  394. if (it != bonusUpdaterMap.end())
  395. return it->second;
  396. logGlobal->error("Unknown bonus updater type '%s'", updaterJson.String());
  397. return nullptr;
  398. }
  399. case JsonNode::JsonType::DATA_STRUCT:
  400. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  401. {
  402. auto updater = std::make_shared<GrowsWithLevelUpdater>();
  403. const JsonVector param = updaterJson["parameters"].Vector();
  404. updater->valPer20 = static_cast<int>(param[0].Integer());
  405. if(param.size() > 1)
  406. updater->stepSize = static_cast<int>(param[1].Integer());
  407. return updater;
  408. }
  409. else
  410. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  411. break;
  412. }
  413. return nullptr;
  414. }
  415. VCMI_LIB_NAMESPACE_BEGIN
  416. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  417. {
  418. auto b = std::make_shared<Bonus>();
  419. std::string type = ability_vec[0].String();
  420. auto it = bonusNameMap.find(type);
  421. if (it == bonusNameMap.end())
  422. {
  423. logMod->error("Error: invalid ability type %s.", type);
  424. return b;
  425. }
  426. b->type = it->second;
  427. b->val = static_cast<si32>(ability_vec[1].Float());
  428. loadBonusSubtype(b->subtype, b->type, ability_vec[2]);
  429. b->additionalInfo = static_cast<si32>(ability_vec[3].Float());
  430. b->duration = BonusDuration::PERMANENT; //TODO: handle flags (as integer)
  431. b->turnsRemain = 0;
  432. return b;
  433. }
  434. std::shared_ptr<const ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  435. {
  436. switch(limiter.getType())
  437. {
  438. case JsonNode::JsonType::DATA_VECTOR:
  439. {
  440. const JsonVector & subLimiters = limiter.Vector();
  441. if(subLimiters.empty())
  442. {
  443. logMod->warn("Warning: empty limiter list");
  444. return std::make_shared<AllOfLimiter>();
  445. }
  446. std::shared_ptr<AggregateLimiter> result;
  447. int offset = 1;
  448. // determine limiter type and offset for sub-limiters
  449. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  450. {
  451. const std::string & aggregator = subLimiters[0].String();
  452. if(aggregator == AllOfLimiter::aggregator)
  453. result = std::make_shared<AllOfLimiter>();
  454. else if(aggregator == AnyOfLimiter::aggregator)
  455. result = std::make_shared<AnyOfLimiter>();
  456. else if(aggregator == NoneOfLimiter::aggregator)
  457. result = std::make_shared<NoneOfLimiter>();
  458. }
  459. if(!result)
  460. {
  461. // collapse for single limiter without explicit aggregate operator
  462. if(subLimiters.size() == 1)
  463. return parseLimiter(subLimiters[0]);
  464. // implicit aggregator must be allOf
  465. result = std::make_shared<AllOfLimiter>();
  466. offset = 0;
  467. }
  468. if(subLimiters.size() == offset)
  469. logMod->warn("Warning: empty sub-limiter list");
  470. for(int sl = offset; sl < subLimiters.size(); ++sl)
  471. result->add(parseLimiter(subLimiters[sl]));
  472. return result;
  473. }
  474. break;
  475. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  476. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  477. break;
  478. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  479. {
  480. std::string limiterType = limiter["type"].String();
  481. const JsonVector & parameters = limiter["parameters"].Vector();
  482. if(limiterType == "CREATURE_TYPE_LIMITER")
  483. {
  484. auto creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  485. LIBRARY->identifiers()->requestIdentifier("creature", parameters[0], [=](si32 creature)
  486. {
  487. creatureLimiter->setCreature(CreatureID(creature));
  488. });
  489. auto includeUpgrades = false;
  490. if(parameters.size() > 1)
  491. {
  492. bool success = true;
  493. includeUpgrades = parameters[1].TryBoolFromString(success);
  494. if(!success)
  495. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  496. }
  497. creatureLimiter->includeUpgrades = includeUpgrades;
  498. return creatureLimiter;
  499. }
  500. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  501. {
  502. auto bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  503. if (!parameters[0].isNull())
  504. {
  505. std::string anotherBonusType = parameters[0].String();
  506. auto it = bonusNameMap.find(anotherBonusType);
  507. if(it != bonusNameMap.end())
  508. {
  509. bonusLimiter->type = it->second;
  510. }
  511. else
  512. {
  513. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  514. }
  515. }
  516. auto findSource = [&](const JsonNode & parameter)
  517. {
  518. if(parameter.getType() == JsonNode::JsonType::DATA_STRUCT)
  519. {
  520. auto sourceIt = bonusSourceMap.find(parameter["type"].String());
  521. if(sourceIt != bonusSourceMap.end())
  522. {
  523. bonusLimiter->source = sourceIt->second;
  524. bonusLimiter->isSourceRelevant = true;
  525. if(!parameter["id"].isNull()) {
  526. loadBonusSourceInstance(bonusLimiter->sid, bonusLimiter->source, parameter["id"]);
  527. bonusLimiter->isSourceIDRelevant = true;
  528. }
  529. }
  530. }
  531. return false;
  532. };
  533. if(parameters.size() > 1)
  534. {
  535. if(findSource(parameters[1]) && parameters.size() == 2)
  536. return bonusLimiter;
  537. else
  538. {
  539. loadBonusSubtype(bonusLimiter->subtype, bonusLimiter->type, parameters[1]);
  540. bonusLimiter->isSubtypeRelevant = true;
  541. if(parameters.size() > 2)
  542. findSource(parameters[2]);
  543. }
  544. }
  545. return bonusLimiter;
  546. }
  547. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  548. {
  549. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, parameters[0].String());
  550. if(alignment == -1)
  551. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  552. else
  553. return std::make_shared<CreatureAlignmentLimiter>(static_cast<EAlignment>(alignment));
  554. }
  555. else if(limiterType == "FACTION_LIMITER" || limiterType == "CREATURE_FACTION_LIMITER") //Second name is deprecated, 1.2 compat
  556. {
  557. auto factionLimiter = std::make_shared<FactionLimiter>();
  558. LIBRARY->identifiers()->requestIdentifier("faction", parameters[0], [=](si32 faction)
  559. {
  560. factionLimiter->faction = FactionID(faction);
  561. });
  562. return factionLimiter;
  563. }
  564. else if(limiterType == "CREATURE_LEVEL_LIMITER")
  565. {
  566. auto levelLimiter = std::make_shared<CreatureLevelLimiter>();
  567. if(!parameters.empty()) //If parameters is empty, level limiter works as CREATURES_ONLY limiter
  568. {
  569. levelLimiter->minLevel = parameters[0].Integer();
  570. if(parameters[1].isNumber())
  571. levelLimiter->maxLevel = parameters[1].Integer();
  572. }
  573. return levelLimiter;
  574. }
  575. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  576. {
  577. auto terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  578. if(!parameters.empty())
  579. {
  580. LIBRARY->identifiers()->requestIdentifier("terrain", parameters[0], [terrainLimiter](si32 terrain)
  581. {
  582. terrainLimiter->terrainType = terrain;
  583. });
  584. }
  585. return terrainLimiter;
  586. }
  587. else if(limiterType == "UNIT_ON_HEXES") {
  588. auto hexLimiter = std::make_shared<UnitOnHexLimiter>();
  589. if(!parameters.empty())
  590. {
  591. for (const auto & parameter: parameters){
  592. if(parameter.isNumber())
  593. hexLimiter->applicableHexes.insert(BattleHex(parameter.Integer()));
  594. }
  595. }
  596. return hexLimiter;
  597. }
  598. else
  599. {
  600. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  601. }
  602. }
  603. break;
  604. default:
  605. break;
  606. }
  607. return nullptr;
  608. }
  609. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability, const TextIdentifier & descriptionID)
  610. {
  611. auto b = std::make_shared<Bonus>();
  612. if (!parseBonus(ability, b.get(), descriptionID))
  613. {
  614. // caller code can not handle this case and presumes that returned bonus is always valid
  615. logGlobal->error("Failed to parse bonus! Json config was %S ", ability.toString());
  616. b->type = BonusType::NONE;
  617. return b;
  618. }
  619. return b;
  620. }
  621. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b, const TextIdentifier & descriptionID)
  622. {
  623. const JsonNode * value = nullptr;
  624. std::string type = ability["type"].String();
  625. auto it = bonusNameMap.find(type);
  626. auto params = std::make_unique<BonusParams>(false);
  627. if (it == bonusNameMap.end())
  628. {
  629. params = std::make_unique<BonusParams>(convertDeprecatedBonus(ability));
  630. if(!params->isConverted)
  631. {
  632. logMod->error("Error: invalid ability type %s.", type);
  633. return false;
  634. }
  635. b->type = params->type;
  636. b->val = params->val.value_or(0);
  637. b->valType = params->valueType.value_or(BonusValueType::ADDITIVE_VALUE);
  638. if(params->targetType)
  639. b->targetSourceType = params->targetType.value();
  640. }
  641. else
  642. b->type = it->second;
  643. loadBonusSubtype(b->subtype, b->type, params->isConverted ? params->toJson()["subtype"] : ability["subtype"]);
  644. if(!params->isConverted)
  645. {
  646. b->val = static_cast<si32>(ability["val"].Float());
  647. value = &ability["valueType"];
  648. if (!value->isNull())
  649. b->valType = static_cast<BonusValueType>(parseByMapN(bonusValueMap, value, "value type "));
  650. }
  651. b->stacking = ability["stacking"].String();
  652. loadBonusAddInfo(b->additionalInfo, b->type, ability);
  653. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  654. if(!ability["description"].isNull())
  655. {
  656. if (ability["description"].isString() && !ability["description"].String().empty())
  657. {
  658. if (ability["description"].String()[0] == '@')
  659. b->description.appendTextID(ability["description"].String().substr(1));
  660. else if (!descriptionID.get().empty())
  661. {
  662. LIBRARY->generaltexth->registerString(ability.getModScope(), descriptionID, ability["description"]);
  663. b->description.appendTextID(descriptionID.get());
  664. }
  665. }
  666. if (ability["description"].isNumber())
  667. b->description.appendTextID("core.arraytxt." + std::to_string(ability["description"].Integer()));
  668. }
  669. if(!ability["icon"].isNull())
  670. b->customIconPath = ImagePath::fromJson(ability["icon"]);
  671. value = &ability["effectRange"];
  672. if (!value->isNull())
  673. b->effectRange = static_cast<BonusLimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  674. value = &ability["duration"];
  675. if (!value->isNull())
  676. {
  677. switch (value->getType())
  678. {
  679. case JsonNode::JsonType::DATA_STRING:
  680. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  681. break;
  682. case JsonNode::JsonType::DATA_VECTOR:
  683. {
  684. BonusDuration::Type dur = 0;
  685. for (const JsonNode & d : value->Vector())
  686. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  687. b->duration = dur;
  688. }
  689. break;
  690. default:
  691. logMod->error("Error! Wrong bonus duration format.");
  692. }
  693. }
  694. value = &ability["sourceType"];
  695. if (!value->isNull())
  696. b->source = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  697. if (!ability["sourceID"].isNull())
  698. loadBonusSourceInstance(b->sid, b->source, ability["sourceID"]);
  699. value = &ability["targetSourceType"];
  700. if (!value->isNull())
  701. b->targetSourceType = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  702. value = &ability["limiters"];
  703. if (!value->isNull())
  704. b->limiter = parseLimiter(*value);
  705. value = &ability["propagator"];
  706. if (!value->isNull())
  707. {
  708. //ALL_CREATURES old propagator compatibility
  709. if(value->String() == "ALL_CREATURES")
  710. {
  711. logMod->warn("ALL_CREATURES propagator is deprecated. Use GLOBAL_EFFECT propagator with CREATURES_ONLY limiter");
  712. b->addLimiter(std::make_shared<CreatureLevelLimiter>());
  713. b->propagator = bonusPropagatorMap.at("GLOBAL_EFFECT");
  714. }
  715. else
  716. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  717. }
  718. value = &ability["updater"];
  719. if(!value->isNull())
  720. b->addUpdater(parseUpdater(*value));
  721. value = &ability["propagationUpdater"];
  722. if(!value->isNull())
  723. b->propagationUpdater = parseUpdater(*value);
  724. return true;
  725. }
  726. CSelector JsonUtils::parseSelector(const JsonNode & ability)
  727. {
  728. CSelector ret = Selector::all;
  729. // Recursive parsers for anyOf, allOf, noneOf
  730. const auto * value = &ability["allOf"];
  731. if(value->isVector())
  732. {
  733. for(const auto & andN : value->Vector())
  734. ret = ret.And(parseSelector(andN));
  735. }
  736. value = &ability["anyOf"];
  737. if(value->isVector())
  738. {
  739. CSelector base = Selector::none;
  740. for(const auto & andN : value->Vector())
  741. base = base.Or(parseSelector(andN));
  742. ret = ret.And(base);
  743. }
  744. value = &ability["noneOf"];
  745. if(value->isVector())
  746. {
  747. CSelector base = Selector::none;
  748. for(const auto & andN : value->Vector())
  749. base = base.Or(parseSelector(andN));
  750. ret = ret.And(base.Not());
  751. }
  752. BonusType type = BonusType::NONE;
  753. // Actual selector parser
  754. value = &ability["type"];
  755. if(value->isString())
  756. {
  757. auto it = bonusNameMap.find(value->String());
  758. if(it != bonusNameMap.end())
  759. {
  760. type = it->second;
  761. ret = ret.And(Selector::type()(it->second));
  762. }
  763. }
  764. value = &ability["subtype"];
  765. if(!value->isNull() && type != BonusType::NONE)
  766. {
  767. BonusSubtypeID subtype;
  768. loadBonusSubtype(subtype, type, ability);
  769. ret = ret.And(Selector::subtype()(subtype));
  770. }
  771. value = &ability["sourceType"];
  772. std::optional<BonusSource> src = std::nullopt; //Fixes for GCC false maybe-uninitialized
  773. std::optional<BonusSourceID> id = std::nullopt;
  774. if(value->isString())
  775. {
  776. auto it = bonusSourceMap.find(value->String());
  777. if(it != bonusSourceMap.end())
  778. src = it->second;
  779. }
  780. value = &ability["sourceID"];
  781. if(!value->isNull() && src.has_value())
  782. {
  783. loadBonusSourceInstance(*id, *src, ability);
  784. }
  785. if(src && id)
  786. ret = ret.And(Selector::source(*src, *id));
  787. else if(src)
  788. ret = ret.And(Selector::sourceTypeSel(*src));
  789. value = &ability["targetSourceType"];
  790. if(value->isString())
  791. {
  792. auto it = bonusSourceMap.find(value->String());
  793. if(it != bonusSourceMap.end())
  794. ret = ret.And(Selector::targetSourceType()(it->second));
  795. }
  796. value = &ability["valueType"];
  797. if(value->isString())
  798. {
  799. auto it = bonusValueMap.find(value->String());
  800. if(it != bonusValueMap.end())
  801. ret = ret.And(Selector::valueType(it->second));
  802. }
  803. CAddInfo info;
  804. value = &ability["addInfo"];
  805. if(!value->isNull())
  806. {
  807. loadBonusAddInfo(info, type, ability["addInfo"]);
  808. ret = ret.And(Selector::info()(info));
  809. }
  810. value = &ability["effectRange"];
  811. if(value->isString())
  812. {
  813. auto it = bonusLimitEffect.find(value->String());
  814. if(it != bonusLimitEffect.end())
  815. ret = ret.And(Selector::effectRange()(it->second));
  816. }
  817. value = &ability["lastsTurns"];
  818. if(value->isNumber())
  819. ret = ret.And(Selector::turns(value->Integer()));
  820. value = &ability["lastsDays"];
  821. if(value->isNumber())
  822. ret = ret.And(Selector::days(value->Integer()));
  823. return ret;
  824. }
  825. VCMI_LIB_NAMESPACE_END