JsonBonus.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 loadBonusSourceInstance(BonusSourceID & sourceInstance, BonusSource sourceType, const JsonNode & node)
  185. {
  186. if (node.isNull())
  187. {
  188. sourceInstance = BonusCustomSource();
  189. return;
  190. }
  191. if (node.isNumber()) // Compatibility code for 1.3 or older
  192. {
  193. logMod->warn("Bonus source must be string!");
  194. sourceInstance = BonusCustomSource(node.Integer());
  195. return;
  196. }
  197. if (!node.isString())
  198. {
  199. logMod->warn("Bonus source must be string!");
  200. sourceInstance = BonusCustomSource();
  201. return;
  202. }
  203. switch (sourceType)
  204. {
  205. case BonusSource::ARTIFACT:
  206. case BonusSource::ARTIFACT_INSTANCE:
  207. {
  208. LIBRARY->identifiers()->requestIdentifier( "artifact", node, [&sourceInstance](int32_t identifier)
  209. {
  210. sourceInstance = ArtifactID(identifier);
  211. });
  212. break;
  213. }
  214. case BonusSource::OBJECT_TYPE:
  215. {
  216. LIBRARY->identifiers()->requestIdentifier( "object", node, [&sourceInstance](int32_t identifier)
  217. {
  218. sourceInstance = Obj(identifier);
  219. });
  220. break;
  221. }
  222. case BonusSource::OBJECT_INSTANCE:
  223. case BonusSource::HERO_BASE_SKILL:
  224. sourceInstance = ObjectInstanceID(ObjectInstanceID::decode(node.String()));
  225. break;
  226. case BonusSource::CREATURE_ABILITY:
  227. {
  228. LIBRARY->identifiers()->requestIdentifier( "creature", node, [&sourceInstance](int32_t identifier)
  229. {
  230. sourceInstance = CreatureID(identifier);
  231. });
  232. break;
  233. }
  234. case BonusSource::TERRAIN_OVERLAY:
  235. {
  236. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  237. {
  238. sourceInstance = BattleField(identifier);
  239. });
  240. break;
  241. }
  242. case BonusSource::SPELL_EFFECT:
  243. {
  244. LIBRARY->identifiers()->requestIdentifier( "spell", node, [&sourceInstance](int32_t identifier)
  245. {
  246. sourceInstance = SpellID(identifier);
  247. });
  248. break;
  249. }
  250. case BonusSource::TOWN_STRUCTURE:
  251. assert(0); // TODO
  252. sourceInstance = BuildingTypeUniqueID();
  253. break;
  254. case BonusSource::SECONDARY_SKILL:
  255. {
  256. LIBRARY->identifiers()->requestIdentifier( "secondarySkill", node, [&sourceInstance](int32_t identifier)
  257. {
  258. sourceInstance = SecondarySkill(identifier);
  259. });
  260. break;
  261. }
  262. case BonusSource::HERO_SPECIAL:
  263. {
  264. LIBRARY->identifiers()->requestIdentifier( "hero", node, [&sourceInstance](int32_t identifier)
  265. {
  266. sourceInstance = HeroTypeID(identifier);
  267. });
  268. break;
  269. }
  270. case BonusSource::CAMPAIGN_BONUS:
  271. sourceInstance = CampaignScenarioID(CampaignScenarioID::decode(node.String()));
  272. break;
  273. case BonusSource::ARMY:
  274. case BonusSource::STACK_EXPERIENCE:
  275. case BonusSource::COMMANDER:
  276. case BonusSource::GLOBAL:
  277. case BonusSource::TERRAIN_NATIVE:
  278. case BonusSource::OTHER:
  279. default:
  280. sourceInstance = BonusSourceID();
  281. break;
  282. }
  283. }
  284. static BonusParams convertDeprecatedBonus(const JsonNode &ability)
  285. {
  286. if(vstd::contains(deprecatedBonusSet, ability["type"].String()))
  287. {
  288. logMod->warn("There is deprecated bonus found:\n%s\nTrying to convert...", ability.toString());
  289. auto params = BonusParams(ability["type"].String(),
  290. ability["subtype"].isString() ? ability["subtype"].String() : "",
  291. ability["subtype"].isNumber() ? ability["subtype"].Integer() : -1);
  292. if(params.isConverted)
  293. {
  294. if(ability["type"].String() == "SECONDARY_SKILL_PREMY" && bonusValueMap.find(ability["valueType"].String())->second == BonusValueType::PERCENT_TO_BASE) //assume secondary skill special
  295. {
  296. params.valueType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  297. params.targetType = BonusSource::SECONDARY_SKILL;
  298. }
  299. logMod->warn("Please, use this bonus:\n%s\nConverted successfully!", params.toJson().toString());
  300. return params;
  301. }
  302. else
  303. logMod->error("Cannot convert bonus!\n%s", ability.toString());
  304. }
  305. BonusParams ret;
  306. ret.isConverted = false;
  307. return ret;
  308. }
  309. static TUpdaterPtr parseUpdater(const JsonNode & updaterJson)
  310. {
  311. const std::map<std::string, std::function<TUpdaterPtr()>> bonusUpdaterMap =
  312. {
  313. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>},
  314. {"TIMES_HERO_LEVEL_DIVIDE_STACK_LEVEL", std::make_shared<TimesHeroLevelDivideStackLevelUpdater>},
  315. {"DIVIDE_STACK_LEVEL", std::make_shared<DivideStackLevelUpdater>},
  316. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>},
  317. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>}
  318. };
  319. switch(updaterJson.getType())
  320. {
  321. case JsonNode::JsonType::DATA_STRING:
  322. {
  323. auto it = bonusUpdaterMap.find(updaterJson.String());
  324. if (it != bonusUpdaterMap.end())
  325. return it->second();
  326. logGlobal->error("Unknown bonus updater type '%s'", updaterJson.String());
  327. return nullptr;
  328. }
  329. case JsonNode::JsonType::DATA_STRUCT:
  330. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  331. {
  332. auto updater = std::make_shared<GrowsWithLevelUpdater>();
  333. const JsonVector param = updaterJson["parameters"].Vector();
  334. updater->valPer20 = static_cast<int>(param[0].Integer());
  335. if(param.size() > 1)
  336. updater->stepSize = static_cast<int>(param[1].Integer());
  337. return updater;
  338. }
  339. else
  340. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  341. break;
  342. }
  343. return nullptr;
  344. }
  345. VCMI_LIB_NAMESPACE_BEGIN
  346. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  347. {
  348. auto b = std::make_shared<Bonus>();
  349. std::string type = ability_vec[0].String();
  350. auto it = bonusNameMap.find(type);
  351. if (it == bonusNameMap.end())
  352. {
  353. logMod->error("Error: invalid ability type %s.", type);
  354. return b;
  355. }
  356. b->type = it->second;
  357. b->val = static_cast<si32>(ability_vec[1].Float());
  358. loadBonusSubtype(b->subtype, b->type, ability_vec[2]);
  359. b->additionalInfo = static_cast<si32>(ability_vec[3].Float());
  360. b->duration = BonusDuration::PERMANENT; //TODO: handle flags (as integer)
  361. b->turnsRemain = 0;
  362. return b;
  363. }
  364. void JsonUtils::resolveAddInfo(CAddInfo & var, const JsonNode & node)
  365. {
  366. const JsonNode & value = node["addInfo"];
  367. if (!value.isNull())
  368. {
  369. switch (value.getType())
  370. {
  371. case JsonNode::JsonType::DATA_INTEGER:
  372. var = static_cast<si32>(value.Integer());
  373. break;
  374. case JsonNode::JsonType::DATA_FLOAT:
  375. var = static_cast<si32>(value.Float());
  376. break;
  377. case JsonNode::JsonType::DATA_STRING:
  378. LIBRARY->identifiers()->requestIdentifier(value, [&](si32 identifier)
  379. {
  380. var = identifier;
  381. });
  382. break;
  383. case JsonNode::JsonType::DATA_VECTOR:
  384. {
  385. const JsonVector & vec = value.Vector();
  386. var.resize(vec.size());
  387. for(int i = 0; i < vec.size(); i++)
  388. {
  389. switch(vec[i].getType())
  390. {
  391. case JsonNode::JsonType::DATA_INTEGER:
  392. var[i] = static_cast<si32>(vec[i].Integer());
  393. break;
  394. case JsonNode::JsonType::DATA_FLOAT:
  395. var[i] = static_cast<si32>(vec[i].Float());
  396. break;
  397. case JsonNode::JsonType::DATA_STRING:
  398. LIBRARY->identifiers()->requestIdentifier(vec[i], [&var,i](si32 identifier)
  399. {
  400. var[i] = identifier;
  401. });
  402. break;
  403. default:
  404. logMod->error("Error! Wrong identifier used for value of addInfo[%d].", i);
  405. }
  406. }
  407. break;
  408. }
  409. default:
  410. logMod->error("Error! Wrong identifier used for value of addInfo.");
  411. }
  412. }
  413. }
  414. std::shared_ptr<ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  415. {
  416. switch(limiter.getType())
  417. {
  418. case JsonNode::JsonType::DATA_VECTOR:
  419. {
  420. const JsonVector & subLimiters = limiter.Vector();
  421. if(subLimiters.empty())
  422. {
  423. logMod->warn("Warning: empty limiter list");
  424. return std::make_shared<AllOfLimiter>();
  425. }
  426. std::shared_ptr<AggregateLimiter> result;
  427. int offset = 1;
  428. // determine limiter type and offset for sub-limiters
  429. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  430. {
  431. const std::string & aggregator = subLimiters[0].String();
  432. if(aggregator == AllOfLimiter::aggregator)
  433. result = std::make_shared<AllOfLimiter>();
  434. else if(aggregator == AnyOfLimiter::aggregator)
  435. result = std::make_shared<AnyOfLimiter>();
  436. else if(aggregator == NoneOfLimiter::aggregator)
  437. result = std::make_shared<NoneOfLimiter>();
  438. }
  439. if(!result)
  440. {
  441. // collapse for single limiter without explicit aggregate operator
  442. if(subLimiters.size() == 1)
  443. return parseLimiter(subLimiters[0]);
  444. // implicit aggregator must be allOf
  445. result = std::make_shared<AllOfLimiter>();
  446. offset = 0;
  447. }
  448. if(subLimiters.size() == offset)
  449. logMod->warn("Warning: empty sub-limiter list");
  450. for(int sl = offset; sl < subLimiters.size(); ++sl)
  451. result->add(parseLimiter(subLimiters[sl]));
  452. return result;
  453. }
  454. break;
  455. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  456. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  457. break;
  458. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  459. {
  460. std::string limiterType = limiter["type"].String();
  461. const JsonVector & parameters = limiter["parameters"].Vector();
  462. if(limiterType == "CREATURE_TYPE_LIMITER")
  463. {
  464. auto creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  465. LIBRARY->identifiers()->requestIdentifier("creature", parameters[0], [=](si32 creature)
  466. {
  467. creatureLimiter->setCreature(CreatureID(creature));
  468. });
  469. auto includeUpgrades = false;
  470. if(parameters.size() > 1)
  471. {
  472. bool success = true;
  473. includeUpgrades = parameters[1].TryBoolFromString(success);
  474. if(!success)
  475. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  476. }
  477. creatureLimiter->includeUpgrades = includeUpgrades;
  478. return creatureLimiter;
  479. }
  480. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  481. {
  482. auto bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  483. if (!parameters[0].isNull())
  484. {
  485. std::string anotherBonusType = parameters[0].String();
  486. auto it = bonusNameMap.find(anotherBonusType);
  487. if(it != bonusNameMap.end())
  488. {
  489. bonusLimiter->type = it->second;
  490. }
  491. else
  492. {
  493. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  494. }
  495. }
  496. auto findSource = [&](const JsonNode & parameter)
  497. {
  498. if(parameter.getType() == JsonNode::JsonType::DATA_STRUCT)
  499. {
  500. auto sourceIt = bonusSourceMap.find(parameter["type"].String());
  501. if(sourceIt != bonusSourceMap.end())
  502. {
  503. bonusLimiter->source = sourceIt->second;
  504. bonusLimiter->isSourceRelevant = true;
  505. if(!parameter["id"].isNull()) {
  506. loadBonusSourceInstance(bonusLimiter->sid, bonusLimiter->source, parameter["id"]);
  507. bonusLimiter->isSourceIDRelevant = true;
  508. }
  509. }
  510. }
  511. return false;
  512. };
  513. if(parameters.size() > 1)
  514. {
  515. if(findSource(parameters[1]) && parameters.size() == 2)
  516. return bonusLimiter;
  517. else
  518. {
  519. loadBonusSubtype(bonusLimiter->subtype, bonusLimiter->type, parameters[1]);
  520. bonusLimiter->isSubtypeRelevant = true;
  521. if(parameters.size() > 2)
  522. findSource(parameters[2]);
  523. }
  524. }
  525. return bonusLimiter;
  526. }
  527. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  528. {
  529. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, parameters[0].String());
  530. if(alignment == -1)
  531. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  532. else
  533. return std::make_shared<CreatureAlignmentLimiter>(static_cast<EAlignment>(alignment));
  534. }
  535. else if(limiterType == "FACTION_LIMITER" || limiterType == "CREATURE_FACTION_LIMITER") //Second name is deprecated, 1.2 compat
  536. {
  537. auto factionLimiter = std::make_shared<FactionLimiter>();
  538. LIBRARY->identifiers()->requestIdentifier("faction", parameters[0], [=](si32 faction)
  539. {
  540. factionLimiter->faction = FactionID(faction);
  541. });
  542. return factionLimiter;
  543. }
  544. else if(limiterType == "CREATURE_LEVEL_LIMITER")
  545. {
  546. auto levelLimiter = std::make_shared<CreatureLevelLimiter>();
  547. if(!parameters.empty()) //If parameters is empty, level limiter works as CREATURES_ONLY limiter
  548. {
  549. levelLimiter->minLevel = parameters[0].Integer();
  550. if(parameters[1].isNumber())
  551. levelLimiter->maxLevel = parameters[1].Integer();
  552. }
  553. return levelLimiter;
  554. }
  555. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  556. {
  557. auto terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  558. if(!parameters.empty())
  559. {
  560. LIBRARY->identifiers()->requestIdentifier("terrain", parameters[0], [terrainLimiter](si32 terrain)
  561. {
  562. terrainLimiter->terrainType = terrain;
  563. });
  564. }
  565. return terrainLimiter;
  566. }
  567. else if(limiterType == "UNIT_ON_HEXES") {
  568. auto hexLimiter = std::make_shared<UnitOnHexLimiter>();
  569. if(!parameters.empty())
  570. {
  571. for (const auto & parameter: parameters){
  572. if(parameter.isNumber())
  573. hexLimiter->applicableHexes.insert(BattleHex(parameter.Integer()));
  574. }
  575. }
  576. return hexLimiter;
  577. }
  578. else
  579. {
  580. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  581. }
  582. }
  583. break;
  584. default:
  585. break;
  586. }
  587. return nullptr;
  588. }
  589. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability, const TextIdentifier & descriptionID)
  590. {
  591. auto b = std::make_shared<Bonus>();
  592. if (!parseBonus(ability, b.get(), descriptionID))
  593. {
  594. // caller code can not handle this case and presumes that returned bonus is always valid
  595. logGlobal->error("Failed to parse bonus! Json config was %S ", ability.toString());
  596. b->type = BonusType::NONE;
  597. return b;
  598. }
  599. return b;
  600. }
  601. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b, const TextIdentifier & descriptionID)
  602. {
  603. const JsonNode * value = nullptr;
  604. std::string type = ability["type"].String();
  605. auto it = bonusNameMap.find(type);
  606. auto params = std::make_unique<BonusParams>(false);
  607. if (it == bonusNameMap.end())
  608. {
  609. params = std::make_unique<BonusParams>(convertDeprecatedBonus(ability));
  610. if(!params->isConverted)
  611. {
  612. logMod->error("Error: invalid ability type %s.", type);
  613. return false;
  614. }
  615. b->type = params->type;
  616. b->val = params->val.value_or(0);
  617. b->valType = params->valueType.value_or(BonusValueType::ADDITIVE_VALUE);
  618. if(params->targetType)
  619. b->targetSourceType = params->targetType.value();
  620. }
  621. else
  622. b->type = it->second;
  623. loadBonusSubtype(b->subtype, b->type, params->isConverted ? params->toJson()["subtype"] : ability["subtype"]);
  624. if(!params->isConverted)
  625. {
  626. b->val = static_cast<si32>(ability["val"].Float());
  627. value = &ability["valueType"];
  628. if (!value->isNull())
  629. b->valType = static_cast<BonusValueType>(parseByMapN(bonusValueMap, value, "value type "));
  630. }
  631. b->stacking = ability["stacking"].String();
  632. resolveAddInfo(b->additionalInfo, ability);
  633. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  634. if(!ability["description"].isNull())
  635. {
  636. if (ability["description"].isString() && !ability["description"].String().empty())
  637. {
  638. if (ability["description"].String()[0] == '@')
  639. b->description.appendTextID(ability["description"].String());
  640. else if (!descriptionID.get().empty())
  641. {
  642. LIBRARY->generaltexth->registerString(ability.getModScope(), descriptionID, ability["description"]);
  643. b->description.appendTextID(descriptionID.get());
  644. }
  645. }
  646. if (ability["description"].isNumber())
  647. b->description.appendTextID("core.arraytxt." + std::to_string(ability["description"].Integer()));
  648. }
  649. if(!ability["icon"].isNull())
  650. b->customIconPath = ImagePath::fromJson(ability["icon"]);
  651. value = &ability["effectRange"];
  652. if (!value->isNull())
  653. b->effectRange = static_cast<BonusLimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  654. value = &ability["duration"];
  655. if (!value->isNull())
  656. {
  657. switch (value->getType())
  658. {
  659. case JsonNode::JsonType::DATA_STRING:
  660. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  661. break;
  662. case JsonNode::JsonType::DATA_VECTOR:
  663. {
  664. BonusDuration::Type dur = 0;
  665. for (const JsonNode & d : value->Vector())
  666. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  667. b->duration = dur;
  668. }
  669. break;
  670. default:
  671. logMod->error("Error! Wrong bonus duration format.");
  672. }
  673. }
  674. value = &ability["sourceType"];
  675. if (!value->isNull())
  676. b->source = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  677. if (!ability["sourceID"].isNull())
  678. loadBonusSourceInstance(b->sid, b->source, ability["sourceID"]);
  679. value = &ability["targetSourceType"];
  680. if (!value->isNull())
  681. b->targetSourceType = static_cast<BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  682. value = &ability["limiters"];
  683. if (!value->isNull())
  684. b->limiter = parseLimiter(*value);
  685. value = &ability["propagator"];
  686. if (!value->isNull())
  687. {
  688. //ALL_CREATURES old propagator compatibility
  689. if(value->String() == "ALL_CREATURES")
  690. {
  691. logMod->warn("ALL_CREATURES propagator is deprecated. Use GLOBAL_EFFECT propagator with CREATURES_ONLY limiter");
  692. b->addLimiter(std::make_shared<CreatureLevelLimiter>());
  693. b->propagator = bonusPropagatorMap.at("GLOBAL_EFFECT");
  694. }
  695. else
  696. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  697. }
  698. value = &ability["updater"];
  699. if(!value->isNull())
  700. b->addUpdater(parseUpdater(*value));
  701. value = &ability["propagationUpdater"];
  702. if(!value->isNull())
  703. b->propagationUpdater = parseUpdater(*value);
  704. return true;
  705. }
  706. CSelector JsonUtils::parseSelector(const JsonNode & ability)
  707. {
  708. CSelector ret = Selector::all;
  709. // Recursive parsers for anyOf, allOf, noneOf
  710. const auto * value = &ability["allOf"];
  711. if(value->isVector())
  712. {
  713. for(const auto & andN : value->Vector())
  714. ret = ret.And(parseSelector(andN));
  715. }
  716. value = &ability["anyOf"];
  717. if(value->isVector())
  718. {
  719. CSelector base = Selector::none;
  720. for(const auto & andN : value->Vector())
  721. base = base.Or(parseSelector(andN));
  722. ret = ret.And(base);
  723. }
  724. value = &ability["noneOf"];
  725. if(value->isVector())
  726. {
  727. CSelector base = Selector::none;
  728. for(const auto & andN : value->Vector())
  729. base = base.Or(parseSelector(andN));
  730. ret = ret.And(base.Not());
  731. }
  732. BonusType type = BonusType::NONE;
  733. // Actual selector parser
  734. value = &ability["type"];
  735. if(value->isString())
  736. {
  737. auto it = bonusNameMap.find(value->String());
  738. if(it != bonusNameMap.end())
  739. {
  740. type = it->second;
  741. ret = ret.And(Selector::type()(it->second));
  742. }
  743. }
  744. value = &ability["subtype"];
  745. if(!value->isNull() && type != BonusType::NONE)
  746. {
  747. BonusSubtypeID subtype;
  748. loadBonusSubtype(subtype, type, ability);
  749. ret = ret.And(Selector::subtype()(subtype));
  750. }
  751. value = &ability["sourceType"];
  752. std::optional<BonusSource> src = std::nullopt; //Fixes for GCC false maybe-uninitialized
  753. std::optional<BonusSourceID> id = std::nullopt;
  754. if(value->isString())
  755. {
  756. auto it = bonusSourceMap.find(value->String());
  757. if(it != bonusSourceMap.end())
  758. src = it->second;
  759. }
  760. value = &ability["sourceID"];
  761. if(!value->isNull() && src.has_value())
  762. {
  763. loadBonusSourceInstance(*id, *src, ability);
  764. }
  765. if(src && id)
  766. ret = ret.And(Selector::source(*src, *id));
  767. else if(src)
  768. ret = ret.And(Selector::sourceTypeSel(*src));
  769. value = &ability["targetSourceType"];
  770. if(value->isString())
  771. {
  772. auto it = bonusSourceMap.find(value->String());
  773. if(it != bonusSourceMap.end())
  774. ret = ret.And(Selector::targetSourceType()(it->second));
  775. }
  776. value = &ability["valueType"];
  777. if(value->isString())
  778. {
  779. auto it = bonusValueMap.find(value->String());
  780. if(it != bonusValueMap.end())
  781. ret = ret.And(Selector::valueType(it->second));
  782. }
  783. CAddInfo info;
  784. value = &ability["addInfo"];
  785. if(!value->isNull())
  786. {
  787. resolveAddInfo(info, ability["addInfo"]);
  788. ret = ret.And(Selector::info()(info));
  789. }
  790. value = &ability["effectRange"];
  791. if(value->isString())
  792. {
  793. auto it = bonusLimitEffect.find(value->String());
  794. if(it != bonusLimitEffect.end())
  795. ret = ret.And(Selector::effectRange()(it->second));
  796. }
  797. value = &ability["lastsTurns"];
  798. if(value->isNumber())
  799. ret = ret.And(Selector::turns(value->Integer()));
  800. value = &ability["lastsDays"];
  801. if(value->isNumber())
  802. ret = ret.And(Selector::days(value->Integer()));
  803. return ret;
  804. }
  805. VCMI_LIB_NAMESPACE_END