JsonRandom.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. std::set<GameResID> defaultResources{
  260. GameResID::WOOD,
  261. GameResID::MERCURY,
  262. GameResID::ORE,
  263. GameResID::SULFUR,
  264. GameResID::CRYSTAL,
  265. GameResID::GEMS,
  266. GameResID::GOLD
  267. }; //todo: configurable resource support
  268. std::set<GameResID> potentialPicks = filterKeys(value, defaultResources, variables);
  269. GameResID resourceID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  270. si32 resourceAmount = loadValue(value, variables, 0);
  271. TResources ret;
  272. ret[resourceID] = resourceAmount;
  273. return ret;
  274. }
  275. PrimarySkill JsonRandom::loadPrimary(const JsonNode & value, const Variables & variables)
  276. {
  277. std::set<PrimarySkill> defaultSkills{
  278. PrimarySkill::ATTACK,
  279. PrimarySkill::DEFENSE,
  280. PrimarySkill::SPELL_POWER,
  281. PrimarySkill::KNOWLEDGE
  282. };
  283. std::set<PrimarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  284. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  285. }
  286. std::vector<si32> JsonRandom::loadPrimaries(const JsonNode & value, const Variables & variables)
  287. {
  288. std::vector<si32> ret(GameConstants::PRIMARY_SKILLS, 0);
  289. std::set<PrimarySkill> defaultSkills{
  290. PrimarySkill::ATTACK,
  291. PrimarySkill::DEFENSE,
  292. PrimarySkill::SPELL_POWER,
  293. PrimarySkill::KNOWLEDGE
  294. };
  295. if(value.isStruct())
  296. {
  297. for(const auto & pair : value.Struct())
  298. {
  299. PrimarySkill id = decodeKey<PrimarySkill>(pair.second.getModScope(), pair.first, variables);
  300. ret[id.getNum()] += loadValue(pair.second, variables);
  301. }
  302. }
  303. if(value.isVector())
  304. {
  305. for(const auto & element : value.Vector())
  306. {
  307. std::set<PrimarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  308. PrimarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  309. defaultSkills.erase(skillID);
  310. ret[skillID.getNum()] += loadValue(element, variables);
  311. }
  312. }
  313. return ret;
  314. }
  315. SecondarySkill JsonRandom::loadSecondary(const JsonNode & value, const Variables & variables)
  316. {
  317. std::set<SecondarySkill> defaultSkills;
  318. for(const auto & skill : LIBRARY->skillh->objects)
  319. if (cb->isAllowed(skill->getId()))
  320. defaultSkills.insert(skill->getId());
  321. std::set<SecondarySkill> potentialPicks = filterKeys(value, defaultSkills, variables);
  322. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  323. }
  324. std::map<SecondarySkill, si32> JsonRandom::loadSecondaries(const JsonNode & value, const Variables & variables)
  325. {
  326. std::map<SecondarySkill, si32> ret;
  327. if(value.isStruct())
  328. {
  329. for(const auto & pair : value.Struct())
  330. {
  331. SecondarySkill id = decodeKey<SecondarySkill>(pair.second.getModScope(), pair.first, variables);
  332. ret[id] = loadValue(pair.second, variables);
  333. }
  334. }
  335. if(value.isVector())
  336. {
  337. std::set<SecondarySkill> defaultSkills;
  338. for(const auto & skill : LIBRARY->skillh->objects)
  339. if (cb->isAllowed(skill->getId()))
  340. defaultSkills.insert(skill->getId());
  341. for(const auto & element : value.Vector())
  342. {
  343. std::set<SecondarySkill> potentialPicks = filterKeys(element, defaultSkills, variables);
  344. SecondarySkill skillID = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  345. defaultSkills.erase(skillID); //avoid dupicates
  346. ret[skillID] = loadValue(element, variables);
  347. }
  348. }
  349. return ret;
  350. }
  351. ArtifactID JsonRandom::loadArtifact(const JsonNode & value, const Variables & variables)
  352. {
  353. std::set<ArtifactID> allowedArts;
  354. for(const auto & artifact : LIBRARY->arth->objects)
  355. if (cb->isAllowed(artifact->getId()) && LIBRARY->arth->legalArtifact(artifact->getId()))
  356. allowedArts.insert(artifact->getId());
  357. std::set<ArtifactID> potentialPicks = filterKeys(value, allowedArts, variables);
  358. return gameRandomizer.rollArtifact(potentialPicks);
  359. }
  360. std::vector<ArtifactID> JsonRandom::loadArtifacts(const JsonNode & value, const Variables & variables)
  361. {
  362. std::vector<ArtifactID> ret;
  363. for (const JsonNode & entry : value.Vector())
  364. {
  365. ret.push_back(loadArtifact(entry, variables));
  366. }
  367. return ret;
  368. }
  369. std::vector<ArtifactPosition> JsonRandom::loadArtifactSlots(const JsonNode & value, const Variables & variables)
  370. {
  371. std::set<ArtifactPosition> allowedSlots;
  372. for(ArtifactPosition pos(0); pos < ArtifactPosition::BACKPACK_START; ++pos)
  373. allowedSlots.insert(pos);
  374. std::vector<ArtifactPosition> ret;
  375. for (const JsonNode & entry : value.Vector())
  376. {
  377. std::set<ArtifactPosition> potentialPicks = filterKeys(entry, allowedSlots, variables);
  378. ret.push_back(*RandomGeneratorUtil::nextItem(potentialPicks, rng));
  379. }
  380. return ret;
  381. }
  382. SpellID JsonRandom::loadSpell(const JsonNode & value, const Variables & variables)
  383. {
  384. std::set<SpellID> defaultSpells;
  385. for(const auto & spell : LIBRARY->spellh->objects)
  386. if (cb->isAllowed(spell->getId()) && !spell->isSpecial())
  387. defaultSpells.insert(spell->getId());
  388. std::set<SpellID> potentialPicks = filterKeys(value, defaultSpells, variables);
  389. if (potentialPicks.empty())
  390. {
  391. logMod->warn("Failed to select suitable random spell!");
  392. return SpellID::NONE;
  393. }
  394. return *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  395. }
  396. std::vector<SpellID> JsonRandom::loadSpells(const JsonNode & value, const Variables & variables)
  397. {
  398. std::vector<SpellID> ret;
  399. for (const JsonNode & entry : value.Vector())
  400. {
  401. ret.push_back(loadSpell(entry, variables));
  402. }
  403. return ret;
  404. }
  405. std::vector<PlayerColor> JsonRandom::loadColors(const JsonNode & value, const Variables & variables)
  406. {
  407. std::vector<PlayerColor> ret;
  408. std::set<PlayerColor> defaultPlayers;
  409. for(size_t i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  410. defaultPlayers.insert(PlayerColor(i));
  411. for(auto & entry : value.Vector())
  412. {
  413. std::set<PlayerColor> potentialPicks = filterKeys(entry, defaultPlayers, variables);
  414. ret.push_back(*RandomGeneratorUtil::nextItem(potentialPicks, rng));
  415. }
  416. return ret;
  417. }
  418. std::vector<HeroTypeID> JsonRandom::loadHeroes(const JsonNode & value)
  419. {
  420. std::vector<HeroTypeID> ret;
  421. for(auto & entry : value.Vector())
  422. {
  423. ret.push_back(LIBRARY->heroTypes()->getByIndex(LIBRARY->identifiers()->getIdentifier("hero", entry.String()).value())->getId());
  424. }
  425. return ret;
  426. }
  427. std::vector<HeroClassID> JsonRandom::loadHeroClasses(const JsonNode & value)
  428. {
  429. std::vector<HeroClassID> ret;
  430. for(auto & entry : value.Vector())
  431. {
  432. ret.push_back(LIBRARY->heroClasses()->getByIndex(LIBRARY->identifiers()->getIdentifier("heroClass", entry.String()).value())->getId());
  433. }
  434. return ret;
  435. }
  436. CStackBasicDescriptor JsonRandom::loadCreature(const JsonNode & value, const Variables & variables)
  437. {
  438. CStackBasicDescriptor stack;
  439. std::set<CreatureID> defaultCreatures;
  440. for(const auto & creature : LIBRARY->creh->objects)
  441. if (!creature->special)
  442. defaultCreatures.insert(creature->getId());
  443. std::set<CreatureID> potentialPicks = filterKeys(value, defaultCreatures, variables);
  444. CreatureID pickedCreature;
  445. if (!potentialPicks.empty())
  446. pickedCreature = *RandomGeneratorUtil::nextItem(potentialPicks, rng);
  447. else
  448. throw JsonRandomizationException("No potential creatures to pick!", value);
  449. if (!pickedCreature.hasValue())
  450. throw JsonRandomizationException("Invalid creature picked!", value);
  451. stack.setType(pickedCreature.toCreature());
  452. stack.setCount(loadValue(value, variables));
  453. if (!value["upgradeChance"].isNull() && !stack.getCreature()->upgrades.empty())
  454. {
  455. if (int(value["upgradeChance"].Float()) > rng.nextInt(99)) // select random upgrade
  456. {
  457. stack.setType(RandomGeneratorUtil::nextItem(stack.getCreature()->upgrades, rng)->toCreature());
  458. }
  459. }
  460. return stack;
  461. }
  462. std::vector<CStackBasicDescriptor> JsonRandom::loadCreatures(const JsonNode & value, const Variables & variables)
  463. {
  464. std::vector<CStackBasicDescriptor> ret;
  465. for (const JsonNode & node : value.Vector())
  466. {
  467. ret.push_back(loadCreature(node, variables));
  468. }
  469. return ret;
  470. }
  471. std::vector<JsonRandom::RandomStackInfo> JsonRandom::evaluateCreatures(const JsonNode & value, const Variables & variables)
  472. {
  473. std::vector<RandomStackInfo> ret;
  474. for (const JsonNode & node : value.Vector())
  475. {
  476. RandomStackInfo info;
  477. if (!node["amount"].isNull())
  478. info.minAmount = info.maxAmount = static_cast<si32>(node["amount"].Float());
  479. else
  480. {
  481. info.minAmount = static_cast<si32>(node["min"].Float());
  482. info.maxAmount = static_cast<si32>(node["max"].Float());
  483. }
  484. CreatureID creatureID(LIBRARY->identifiers()->getIdentifier("creature", node["type"]).value());
  485. const CCreature * crea = creatureID.toCreature();
  486. info.allowedCreatures.push_back(crea);
  487. if (node["upgradeChance"].Float() > 0)
  488. {
  489. for(const auto & creaID : crea->upgrades)
  490. info.allowedCreatures.push_back(creaID.toCreature());
  491. }
  492. ret.push_back(info);
  493. }
  494. return ret;
  495. }
  496. std::vector<std::shared_ptr<Bonus>> JsonRandom::loadBonuses(const JsonNode & value)
  497. {
  498. std::vector<std::shared_ptr<Bonus>> ret;
  499. for (const JsonNode & entry : value.Vector())
  500. {
  501. if(auto bonus = JsonUtils::parseBonus(entry))
  502. ret.push_back(bonus);
  503. }
  504. return ret;
  505. }
  506. VCMI_LIB_NAMESPACE_END