JsonRandom.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. * JsonRandom.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 "JsonRandom.h"
  12. #include <vstd/StringUtils.h>
  13. #include "JsonNode.h"
  14. #include "CRandomGenerator.h"
  15. #include "constants/StringConstants.h"
  16. #include "VCMI_Lib.h"
  17. #include "CArtHandler.h"
  18. #include "CCreatureHandler.h"
  19. #include "CCreatureSet.h"
  20. #include "spells/CSpellHandler.h"
  21. #include "CSkillHandler.h"
  22. #include "CHeroHandler.h"
  23. #include "IGameCallback.h"
  24. #include "mapObjects/IObjectInterface.h"
  25. #include "modding/IdentifierStorage.h"
  26. #include "modding/ModScope.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. namespace JsonRandom
  29. {
  30. si32 loadVariable(std::string variableGroup, const std::string & value, const Variables & variables, si32 defaultValue)
  31. {
  32. if (value.empty() || value[0] != '@')
  33. {
  34. logMod->warn("Invalid syntax in load value! Can not load value from '%s'", value);
  35. return defaultValue;
  36. }
  37. std::string variableID = variableGroup + value;
  38. if (variables.count(variableID) == 0)
  39. {
  40. logMod->warn("Invalid syntax in load value! Unknown variable '%s'", value);
  41. return defaultValue;
  42. }
  43. return variables.at(variableID);
  44. }
  45. si32 loadValue(const JsonNode & value, CRandomGenerator & rng, const Variables & variables, si32 defaultValue)
  46. {
  47. if(value.isNull())
  48. return defaultValue;
  49. if(value.isNumber())
  50. return static_cast<si32>(value.Float());
  51. if (value.isString())
  52. return loadVariable("number", value.String(), variables, defaultValue);
  53. if(value.isVector())
  54. {
  55. const auto & vector = value.Vector();
  56. size_t index= rng.getIntRange(0, vector.size()-1)();
  57. return loadValue(vector[index], rng, variables, 0);
  58. }
  59. if(value.isStruct())
  60. {
  61. if (!value["amount"].isNull())
  62. return static_cast<si32>(loadValue(value["amount"], rng, variables, defaultValue));
  63. si32 min = static_cast<si32>(loadValue(value["min"], rng, variables, 0));
  64. si32 max = static_cast<si32>(loadValue(value["max"], rng, variables, 0));
  65. return rng.getIntRange(min, max)();
  66. }
  67. return defaultValue;
  68. }
  69. template<typename IdentifierType>
  70. IdentifierType decodeKey(const std::string & modScope, const std::string & value, const Variables & variables)
  71. {
  72. if (value.empty() || value[0] != '@')
  73. return IdentifierType(*VLC->identifiers()->getIdentifier(modScope, IdentifierType::entityType(), value));
  74. else
  75. return loadVariable(IdentifierType::entityType(), value, variables, IdentifierType::NONE);
  76. }
  77. template<typename IdentifierType>
  78. IdentifierType decodeKey(const JsonNode & value, const Variables & variables)
  79. {
  80. if (value.String().empty() || value.String()[0] != '@')
  81. return IdentifierType(*VLC->identifiers()->getIdentifier(IdentifierType::entityType(), value));
  82. else
  83. return loadVariable(IdentifierType::entityType(), value.String(), variables, IdentifierType::NONE);
  84. }
  85. template<>
  86. PrimarySkill decodeKey(const JsonNode & value, const Variables & variables)
  87. {
  88. return PrimarySkill(*VLC->identifiers()->getIdentifier("primarySkill", value));
  89. }
  90. /// Method that allows type-specific object filtering
  91. /// Default implementation is to accept all input objects
  92. template<typename IdentifierType>
  93. std::set<IdentifierType> filterKeysTyped(const JsonNode & value, const std::set<IdentifierType> & valuesSet)
  94. {
  95. return valuesSet;
  96. }
  97. template<>
  98. std::set<ArtifactID> filterKeysTyped(const JsonNode & value, const std::set<ArtifactID> & valuesSet)
  99. {
  100. assert(value.isStruct());
  101. std::set<CArtifact::EartClass> allowedClasses;
  102. std::set<ArtifactPosition> allowedPositions;
  103. ui32 minValue = 0;
  104. ui32 maxValue = std::numeric_limits<ui32>::max();
  105. if (value["class"].getType() == JsonNode::JsonType::DATA_STRING)
  106. allowedClasses.insert(CArtHandler::stringToClass(value["class"].String()));
  107. else
  108. for(const auto & entry : value["class"].Vector())
  109. allowedClasses.insert(CArtHandler::stringToClass(entry.String()));
  110. if (value["slot"].getType() == JsonNode::JsonType::DATA_STRING)
  111. allowedPositions.insert(ArtifactPosition::decode(value["class"].String()));
  112. else
  113. for(const auto & entry : value["slot"].Vector())
  114. allowedPositions.insert(ArtifactPosition::decode(entry.String()));
  115. if (!value["minValue"].isNull())
  116. minValue = static_cast<ui32>(value["minValue"].Float());
  117. if (!value["maxValue"].isNull())
  118. maxValue = static_cast<ui32>(value["maxValue"].Float());
  119. std::set<ArtifactID> result;
  120. for (auto const & artID : valuesSet)
  121. {
  122. CArtifact * art = VLC->arth->objects[artID];
  123. if(!vstd::iswithin(art->getPrice(), minValue, maxValue))
  124. continue;
  125. if(!allowedClasses.empty() && !allowedClasses.count(art->aClass))
  126. continue;
  127. if(!IObjectInterface::cb->isAllowed(1, art->getIndex()))
  128. continue;
  129. if(!allowedPositions.empty())
  130. {
  131. bool positionAllowed = false;
  132. for(const auto & pos : art->getPossibleSlots().at(ArtBearer::HERO))
  133. {
  134. if(allowedPositions.count(pos))
  135. positionAllowed = true;
  136. }
  137. if (!positionAllowed)
  138. continue;
  139. }
  140. result.insert(artID);
  141. }
  142. return result;
  143. }
  144. template<>
  145. std::set<SpellID> filterKeysTyped(const JsonNode & value, const std::set<SpellID> & valuesSet)
  146. {
  147. std::set<SpellID> result = valuesSet;
  148. if (!value["level"].isNull())
  149. {
  150. int32_t spellLevel = value["level"].Integer();
  151. vstd::erase_if(result, [=](const SpellID & spell)
  152. {
  153. return VLC->spellh->getById(spell)->getLevel() != spellLevel;
  154. });
  155. }
  156. if (!value["school"].isNull())
  157. {
  158. int32_t schoolID = VLC->identifiers()->getIdentifier("spellSchool", value["school"]).value();
  159. vstd::erase_if(result, [=](const SpellID & spell)
  160. {
  161. return !VLC->spellh->getById(spell)->hasSchool(SpellSchool(schoolID));
  162. });
  163. }
  164. return result;
  165. }
  166. template<typename IdentifierType>
  167. std::set<IdentifierType> filterKeys(const JsonNode & value, const std::set<IdentifierType> & valuesSet, const Variables & variables)
  168. {
  169. if(value.isString())
  170. return { decodeKey<IdentifierType>(value, variables) };
  171. assert(value.isStruct());
  172. if(value.isStruct())
  173. {
  174. if(!value["type"].isNull())
  175. return filterKeys(value["type"], valuesSet, variables);
  176. std::set<IdentifierType> filteredTypes = filterKeysTyped(value, valuesSet);
  177. if(!value["anyOf"].isNull())
  178. {
  179. std::set<IdentifierType> filteredAnyOf;
  180. for (auto const & entry : value["anyOf"].Vector())
  181. {
  182. std::set<IdentifierType> subset = filterKeys(entry, valuesSet, variables);
  183. filteredAnyOf.insert(subset.begin(), subset.end());
  184. }
  185. vstd::erase_if(filteredTypes, [&](const IdentifierType & value)
  186. {
  187. return filteredAnyOf.count(value) == 0;
  188. });
  189. }
  190. if(!value["noneOf"].isNull())
  191. {
  192. for (auto const & entry : value["noneOf"].Vector())
  193. {
  194. std::set<IdentifierType> subset = filterKeys(entry, valuesSet, variables);
  195. for (auto bannedEntry : subset )
  196. filteredTypes.erase(bannedEntry);
  197. }
  198. }
  199. return filteredTypes;
  200. }
  201. return valuesSet;
  202. }
  203. TResources loadResources(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  204. {
  205. TResources ret;
  206. if (value.isVector())
  207. {
  208. for (const auto & entry : value.Vector())
  209. ret += loadResource(entry, rng, variables);
  210. return ret;
  211. }
  212. for (size_t i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  213. {
  214. ret[i] = loadValue(value[GameConstants::RESOURCE_NAMES[i]], rng, variables);
  215. }
  216. return ret;
  217. }
  218. TResources loadResource(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  219. {
  220. std::set<GameResID> defaultResources{
  221. GameResID::WOOD,
  222. GameResID::MERCURY,
  223. GameResID::ORE,
  224. GameResID::SULFUR,
  225. GameResID::CRYSTAL,
  226. GameResID::GEMS,
  227. GameResID::GOLD
  228. };
  229. std::set<GameResID> potentialPicks = filterKeys(value, defaultResources, variables);
  230. GameResID resourceID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  231. si32 resourceAmount = loadValue(value, rng, variables, 0);
  232. TResources ret;
  233. ret[resourceID] = resourceAmount;
  234. return ret;
  235. }
  236. PrimarySkill loadPrimary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  237. {
  238. std::set<PrimarySkill> defaultSkills{
  239. PrimarySkill::ATTACK,
  240. PrimarySkill::DEFENSE,
  241. PrimarySkill::SPELL_POWER,
  242. PrimarySkill::KNOWLEDGE
  243. };
  244. std::set<PrimarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  245. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  246. }
  247. std::vector<si32> loadPrimaries(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  248. {
  249. std::vector<si32> ret;
  250. if(value.isStruct())
  251. {
  252. for(const auto & name : NPrimarySkill::names)
  253. {
  254. ret.push_back(loadValue(value[name], rng, variables));
  255. }
  256. }
  257. if(value.isVector())
  258. {
  259. std::set<PrimarySkill> defaultSkills{
  260. PrimarySkill::ATTACK,
  261. PrimarySkill::DEFENSE,
  262. PrimarySkill::SPELL_POWER,
  263. PrimarySkill::KNOWLEDGE
  264. };
  265. ret.resize(GameConstants::PRIMARY_SKILLS, 0);
  266. for(const auto & element : value.Vector())
  267. {
  268. std::set<PrimarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  269. PrimarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  270. defaultSkills.erase(skillID);
  271. ret[static_cast<int>(skillID)] += loadValue(element, rng, variables);
  272. }
  273. }
  274. return ret;
  275. }
  276. SecondarySkill loadSecondary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  277. {
  278. std::set<SecondarySkill> defaultSkills;
  279. for(const auto & skill : VLC->skillh->objects)
  280. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  281. defaultSkills.insert(skill->getId());
  282. std::set<SecondarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  283. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  284. }
  285. std::map<SecondarySkill, si32> loadSecondaries(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  286. {
  287. std::map<SecondarySkill, si32> ret;
  288. if(value.isStruct())
  289. {
  290. for(const auto & pair : value.Struct())
  291. {
  292. SecondarySkill id = decodeKey<SecondarySkill>(pair.second.meta, pair.first, variables);
  293. ret[id] = loadValue(pair.second, rng, variables);
  294. }
  295. }
  296. if(value.isVector())
  297. {
  298. std::set<SecondarySkill> defaultSkills;
  299. for(const auto & skill : VLC->skillh->objects)
  300. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  301. defaultSkills.insert(skill->getId());
  302. for(const auto & element : value.Vector())
  303. {
  304. std::set<SecondarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  305. SecondarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  306. defaultSkills.erase(skillID); //avoid dupicates
  307. ret[skillID] = loadValue(element, rng, variables);
  308. }
  309. }
  310. return ret;
  311. }
  312. ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  313. {
  314. std::set<ArtifactID> allowedArts;
  315. for (auto const * artifact : VLC->arth->allowedArtifacts)
  316. allowedArts.insert(artifact->getId());
  317. std::set<ArtifactID> potentialPicks = filterKeys(value, allowedArts, variables);
  318. return VLC->arth->pickRandomArtifact(rng, potentialPicks);
  319. }
  320. std::vector<ArtifactID> loadArtifacts(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  321. {
  322. std::vector<ArtifactID> ret;
  323. for (const JsonNode & entry : value.Vector())
  324. {
  325. ret.push_back(loadArtifact(entry, rng, variables));
  326. }
  327. return ret;
  328. }
  329. SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  330. {
  331. std::set<SpellID> defaultSpells;
  332. for(const auto & spell : VLC->spellh->objects)
  333. if (IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  334. defaultSpells.insert(spell->getId());
  335. std::set<SpellID> potentialPicks = filterKeys(value, defaultSpells, variables);
  336. if (potentialPicks.empty())
  337. {
  338. logMod->warn("Failed to select suitable random spell!");
  339. return SpellID::NONE;
  340. }
  341. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  342. }
  343. std::vector<SpellID> loadSpells(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  344. {
  345. std::vector<SpellID> ret;
  346. for (const JsonNode & entry : value.Vector())
  347. {
  348. ret.push_back(loadSpell(entry, rng, variables));
  349. }
  350. return ret;
  351. }
  352. std::vector<PlayerColor> loadColors(const JsonNode & value, CRandomGenerator & rng)
  353. {
  354. std::vector<PlayerColor> ret;
  355. std::set<std::string> def;
  356. for(auto & color : GameConstants::PLAYER_COLOR_NAMES)
  357. def.insert(color);
  358. for(auto & entry : value.Vector())
  359. {
  360. auto key = loadKey(entry, rng, def);
  361. auto pos = vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, key);
  362. if(pos < 0)
  363. logMod->warn("Unable to determine player color %s", key);
  364. else
  365. ret.emplace_back(pos);
  366. }
  367. return ret;
  368. }
  369. std::vector<HeroTypeID> loadHeroes(const JsonNode & value, CRandomGenerator & rng)
  370. {
  371. std::vector<HeroTypeID> ret;
  372. for(auto & entry : value.Vector())
  373. {
  374. ret.push_back(VLC->heroTypes()->getByIndex(VLC->identifiers()->getIdentifier("hero", entry.String()).value())->getId());
  375. }
  376. return ret;
  377. }
  378. std::vector<HeroClassID> loadHeroClasses(const JsonNode & value, CRandomGenerator & rng)
  379. {
  380. std::vector<HeroClassID> ret;
  381. for(auto & entry : value.Vector())
  382. {
  383. ret.push_back(VLC->heroClasses()->getByIndex(VLC->identifiers()->getIdentifier("heroClass", entry.String()).value())->getId());
  384. }
  385. return ret;
  386. }
  387. CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  388. {
  389. CStackBasicDescriptor stack;
  390. std::set<CreatureID> defaultCreatures;
  391. for(const auto & creature : VLC->creh->objects)
  392. if (!creature->special)
  393. defaultCreatures.insert(creature->getId());
  394. std::set<CreatureID> potentialPicks = filterKeys(value, defaultCreatures, variables);
  395. CreatureID pickedCreature;
  396. if (!potentialPicks.empty())
  397. pickedCreature = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  398. else
  399. logMod->warn("Failed to select suitable random creature!");
  400. stack.type = VLC->creh->objects[pickedCreature];
  401. stack.count = loadValue(value, rng, variables);
  402. if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty())
  403. {
  404. if (int(value["upgradeChance"].Float()) > rng.nextInt(99)) // select random upgrade
  405. {
  406. stack.type = VLC->creh->objects[*RandomGeneratorUtil::nextItem(stack.type->upgrades, rng)];
  407. }
  408. }
  409. return stack;
  410. }
  411. std::vector<CStackBasicDescriptor> loadCreatures(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  412. {
  413. std::vector<CStackBasicDescriptor> ret;
  414. for (const JsonNode & node : value.Vector())
  415. {
  416. ret.push_back(loadCreature(node, rng, variables));
  417. }
  418. return ret;
  419. }
  420. std::vector<RandomStackInfo> evaluateCreatures(const JsonNode & value, const Variables & variables)
  421. {
  422. std::vector<RandomStackInfo> ret;
  423. for (const JsonNode & node : value.Vector())
  424. {
  425. RandomStackInfo info;
  426. if (!node["amount"].isNull())
  427. info.minAmount = info.maxAmount = static_cast<si32>(node["amount"].Float());
  428. else
  429. {
  430. info.minAmount = static_cast<si32>(node["min"].Float());
  431. info.maxAmount = static_cast<si32>(node["max"].Float());
  432. }
  433. const CCreature * crea = VLC->creh->objects[VLC->identifiers()->getIdentifier("creature", node["type"]).value()];
  434. info.allowedCreatures.push_back(crea);
  435. if (node["upgradeChance"].Float() > 0)
  436. {
  437. for(const auto & creaID : crea->upgrades)
  438. info.allowedCreatures.push_back(VLC->creh->objects[creaID]);
  439. }
  440. ret.push_back(info);
  441. }
  442. return ret;
  443. }
  444. std::vector<Bonus> DLL_LINKAGE loadBonuses(const JsonNode & value)
  445. {
  446. std::vector<Bonus> ret;
  447. for (const JsonNode & entry : value.Vector())
  448. {
  449. if(auto bonus = JsonUtils::parseBonus(entry))
  450. ret.push_back(*bonus);
  451. }
  452. return ret;
  453. }
  454. }
  455. VCMI_LIB_NAMESPACE_END