JsonRandom.cpp 16 KB

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