JsonRandom.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. std::vector<si32> loadPrimary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  237. {
  238. std::vector<si32> ret;
  239. if(value.isStruct())
  240. {
  241. for(const auto & name : NPrimarySkill::names)
  242. {
  243. ret.push_back(loadValue(value[name], rng, variables));
  244. }
  245. }
  246. if(value.isVector())
  247. {
  248. std::set<PrimarySkill> defaultSkills{
  249. PrimarySkill::ATTACK,
  250. PrimarySkill::DEFENSE,
  251. PrimarySkill::SPELL_POWER,
  252. PrimarySkill::KNOWLEDGE
  253. };
  254. ret.resize(GameConstants::PRIMARY_SKILLS, 0);
  255. for(const auto & element : value.Vector())
  256. {
  257. std::set<PrimarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  258. PrimarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  259. defaultSkills.erase(skillID);
  260. ret[static_cast<int>(skillID)] += loadValue(element, rng, variables);
  261. }
  262. }
  263. return ret;
  264. }
  265. SecondarySkill loadSecondary(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  266. {
  267. std::set<SecondarySkill> defaultSkills;
  268. for(const auto & skill : VLC->skillh->objects)
  269. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  270. defaultSkills.insert(skill->getId());
  271. std::set<SecondarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  272. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  273. }
  274. std::map<SecondarySkill, si32> loadSecondaries(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  275. {
  276. std::map<SecondarySkill, si32> ret;
  277. if(value.isStruct())
  278. {
  279. for(const auto & pair : value.Struct())
  280. {
  281. SecondarySkill id = decodeKey<SecondarySkill>(pair.second.meta, pair.first, variables);
  282. ret[id] = loadValue(pair.second, rng, variables);
  283. }
  284. }
  285. if(value.isVector())
  286. {
  287. std::set<SecondarySkill> defaultSkills;
  288. for(const auto & skill : VLC->skillh->objects)
  289. if (IObjectInterface::cb->isAllowed(2, skill->getIndex()))
  290. defaultSkills.insert(skill->getId());
  291. for(const auto & element : value.Vector())
  292. {
  293. std::set<SecondarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  294. SecondarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  295. defaultSkills.erase(skillID); //avoid dupicates
  296. ret[skillID] = loadValue(element, rng, variables);
  297. }
  298. }
  299. return ret;
  300. }
  301. ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  302. {
  303. std::set<ArtifactID> allowedArts;
  304. for (auto const * artifact : VLC->arth->allowedArtifacts)
  305. allowedArts.insert(artifact->getId());
  306. std::set<ArtifactID> potentialPicks = filterKeys(value, allowedArts, variables);
  307. return VLC->arth->pickRandomArtifact(rng, potentialPicks);
  308. }
  309. std::vector<ArtifactID> loadArtifacts(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  310. {
  311. std::vector<ArtifactID> ret;
  312. for (const JsonNode & entry : value.Vector())
  313. {
  314. ret.push_back(loadArtifact(entry, rng, variables));
  315. }
  316. return ret;
  317. }
  318. SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  319. {
  320. std::set<SpellID> defaultSpells;
  321. for(const auto & spell : VLC->spellh->objects)
  322. if (IObjectInterface::cb->isAllowed(0, spell->getIndex()))
  323. defaultSpells.insert(spell->getId());
  324. std::set<SpellID> potentialPicks = filterKeys(value, defaultSpells, variables);
  325. if (potentialPicks.empty())
  326. {
  327. logMod->warn("Failed to select suitable random spell!");
  328. return SpellID::NONE;
  329. }
  330. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  331. }
  332. std::vector<SpellID> loadSpells(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  333. {
  334. std::vector<SpellID> ret;
  335. for (const JsonNode & entry : value.Vector())
  336. {
  337. ret.push_back(loadSpell(entry, rng, variables));
  338. }
  339. return ret;
  340. }
  341. std::vector<PlayerColor> loadColors(const JsonNode & value, CRandomGenerator & rng)
  342. {
  343. std::vector<PlayerColor> ret;
  344. std::set<std::string> def;
  345. for(auto & color : GameConstants::PLAYER_COLOR_NAMES)
  346. def.insert(color);
  347. for(auto & entry : value.Vector())
  348. {
  349. auto key = loadKey(entry, rng, def);
  350. auto pos = vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, key);
  351. if(pos < 0)
  352. logMod->warn("Unable to determine player color %s", key);
  353. else
  354. ret.emplace_back(pos);
  355. }
  356. return ret;
  357. }
  358. std::vector<HeroTypeID> loadHeroes(const JsonNode & value, CRandomGenerator & rng)
  359. {
  360. std::vector<HeroTypeID> ret;
  361. for(auto & entry : value.Vector())
  362. {
  363. ret.push_back(VLC->heroTypes()->getByIndex(VLC->identifiers()->getIdentifier("hero", entry.String()).value())->getId());
  364. }
  365. return ret;
  366. }
  367. std::vector<HeroClassID> loadHeroClasses(const JsonNode & value, CRandomGenerator & rng)
  368. {
  369. std::vector<HeroClassID> ret;
  370. for(auto & entry : value.Vector())
  371. {
  372. ret.push_back(VLC->heroClasses()->getByIndex(VLC->identifiers()->getIdentifier("heroClass", entry.String()).value())->getId());
  373. }
  374. return ret;
  375. }
  376. CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  377. {
  378. CStackBasicDescriptor stack;
  379. std::set<CreatureID> defaultCreatures;
  380. for(const auto & creature : VLC->creh->objects)
  381. if (!creature->special)
  382. defaultCreatures.insert(creature->getId());
  383. std::set<CreatureID> potentialPicks = filterKeys(value, defaultCreatures, variables);
  384. CreatureID pickedCreature;
  385. if (!potentialPicks.empty())
  386. pickedCreature = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  387. else
  388. logMod->warn("Failed to select suitable random creature!");
  389. stack.type = VLC->creh->objects[pickedCreature];
  390. stack.count = loadValue(value, rng, variables);
  391. if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty())
  392. {
  393. if (int(value["upgradeChance"].Float()) > rng.nextInt(99)) // select random upgrade
  394. {
  395. stack.type = VLC->creh->objects[*RandomGeneratorUtil::nextItem(stack.type->upgrades, rng)];
  396. }
  397. }
  398. return stack;
  399. }
  400. std::vector<CStackBasicDescriptor> loadCreatures(const JsonNode & value, CRandomGenerator & rng, const Variables & variables)
  401. {
  402. std::vector<CStackBasicDescriptor> ret;
  403. for (const JsonNode & node : value.Vector())
  404. {
  405. ret.push_back(loadCreature(node, rng, variables));
  406. }
  407. return ret;
  408. }
  409. std::vector<RandomStackInfo> evaluateCreatures(const JsonNode & value, const Variables & variables)
  410. {
  411. std::vector<RandomStackInfo> ret;
  412. for (const JsonNode & node : value.Vector())
  413. {
  414. RandomStackInfo info;
  415. if (!node["amount"].isNull())
  416. info.minAmount = info.maxAmount = static_cast<si32>(node["amount"].Float());
  417. else
  418. {
  419. info.minAmount = static_cast<si32>(node["min"].Float());
  420. info.maxAmount = static_cast<si32>(node["max"].Float());
  421. }
  422. const CCreature * crea = VLC->creh->objects[VLC->identifiers()->getIdentifier("creature", node["type"]).value()];
  423. info.allowedCreatures.push_back(crea);
  424. if (node["upgradeChance"].Float() > 0)
  425. {
  426. for(const auto & creaID : crea->upgrades)
  427. info.allowedCreatures.push_back(VLC->creh->objects[creaID]);
  428. }
  429. ret.push_back(info);
  430. }
  431. return ret;
  432. }
  433. std::vector<Bonus> DLL_LINKAGE loadBonuses(const JsonNode & value)
  434. {
  435. std::vector<Bonus> ret;
  436. for (const JsonNode & entry : value.Vector())
  437. {
  438. if(auto bonus = JsonUtils::parseBonus(entry))
  439. ret.push_back(*bonus);
  440. }
  441. return ret;
  442. }
  443. }
  444. VCMI_LIB_NAMESPACE_END