JsonRandom.cpp 16 KB

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