JsonRandom.cpp 18 KB

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