JsonBonus.cpp 24 KB

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