JsonNode.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /*
  2. * JsonNode.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 "JsonNode.h"
  12. #include "ScopeGuard.h"
  13. #include "HeroBonus.h"
  14. #include "filesystem/Filesystem.h"
  15. #include "VCMI_Lib.h" //for identifier resolution
  16. #include "CModHandler.h"
  17. #include "CGeneralTextHandler.h"
  18. #include "JsonDetail.h"
  19. using namespace JsonDetail;
  20. class LibClasses;
  21. class CModHandler;
  22. static const JsonNode nullNode;
  23. JsonNode::JsonNode(JsonType Type):
  24. type(JsonType::DATA_NULL)
  25. {
  26. setType(Type);
  27. }
  28. JsonNode::JsonNode(const char *data, size_t datasize):
  29. type(JsonType::DATA_NULL)
  30. {
  31. JsonParser parser(data, datasize);
  32. *this = parser.parse("<unknown>");
  33. }
  34. JsonNode::JsonNode(ResourceID && fileURI):
  35. type(JsonType::DATA_NULL)
  36. {
  37. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  38. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  39. *this = parser.parse(fileURI.getName());
  40. }
  41. JsonNode::JsonNode(const ResourceID & fileURI):
  42. type(JsonType::DATA_NULL)
  43. {
  44. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  45. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  46. *this = parser.parse(fileURI.getName());
  47. }
  48. JsonNode::JsonNode(ResourceID && fileURI, bool &isValidSyntax):
  49. type(JsonType::DATA_NULL)
  50. {
  51. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  52. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  53. *this = parser.parse(fileURI.getName());
  54. isValidSyntax = parser.isValid();
  55. }
  56. JsonNode::JsonNode(const JsonNode &copy):
  57. type(JsonType::DATA_NULL),
  58. meta(copy.meta)
  59. {
  60. setType(copy.getType());
  61. switch(type)
  62. {
  63. break; case JsonType::DATA_NULL:
  64. break; case JsonType::DATA_BOOL: Bool() = copy.Bool();
  65. break; case JsonType::DATA_FLOAT: Float() = copy.Float();
  66. break; case JsonType::DATA_STRING: String() = copy.String();
  67. break; case JsonType::DATA_VECTOR: Vector() = copy.Vector();
  68. break; case JsonType::DATA_STRUCT: Struct() = copy.Struct();
  69. break; case JsonType::DATA_INTEGER:Integer() = copy.Integer();
  70. }
  71. }
  72. JsonNode::~JsonNode()
  73. {
  74. setType(JsonType::DATA_NULL);
  75. }
  76. void JsonNode::swap(JsonNode &b)
  77. {
  78. using std::swap;
  79. swap(meta, b.meta);
  80. swap(data, b.data);
  81. swap(type, b.type);
  82. }
  83. JsonNode & JsonNode::operator =(JsonNode node)
  84. {
  85. swap(node);
  86. return *this;
  87. }
  88. bool JsonNode::operator == (const JsonNode &other) const
  89. {
  90. if (getType() == other.getType())
  91. {
  92. switch(type)
  93. {
  94. case JsonType::DATA_NULL: return true;
  95. case JsonType::DATA_BOOL: return Bool() == other.Bool();
  96. case JsonType::DATA_FLOAT: return Float() == other.Float();
  97. case JsonType::DATA_STRING: return String() == other.String();
  98. case JsonType::DATA_VECTOR: return Vector() == other.Vector();
  99. case JsonType::DATA_STRUCT: return Struct() == other.Struct();
  100. case JsonType::DATA_INTEGER:return Integer()== other.Integer();
  101. }
  102. }
  103. return false;
  104. }
  105. bool JsonNode::operator != (const JsonNode &other) const
  106. {
  107. return !(*this == other);
  108. }
  109. JsonNode::JsonType JsonNode::getType() const
  110. {
  111. return type;
  112. }
  113. void JsonNode::setMeta(std::string metadata, bool recursive)
  114. {
  115. meta = metadata;
  116. if (recursive)
  117. {
  118. switch (type)
  119. {
  120. break; case JsonType::DATA_VECTOR:
  121. {
  122. for(auto & node : Vector())
  123. {
  124. node.setMeta(metadata);
  125. }
  126. }
  127. break; case JsonType::DATA_STRUCT:
  128. {
  129. for(auto & node : Struct())
  130. {
  131. node.second.setMeta(metadata);
  132. }
  133. }
  134. }
  135. }
  136. }
  137. void JsonNode::setType(JsonType Type)
  138. {
  139. if (type == Type)
  140. return;
  141. //float<->int conversion
  142. if(type == JsonType::DATA_FLOAT && Type == JsonType::DATA_INTEGER)
  143. {
  144. si64 converted = data.Float;
  145. type = Type;
  146. data.Integer = converted;
  147. return;
  148. }
  149. else if(type == JsonType::DATA_INTEGER && Type == JsonType::DATA_FLOAT)
  150. {
  151. double converted = data.Integer;
  152. type = Type;
  153. data.Float = converted;
  154. return;
  155. }
  156. //Reset node to nullptr
  157. if (Type != JsonType::DATA_NULL)
  158. setType(JsonType::DATA_NULL);
  159. switch (type)
  160. {
  161. break; case JsonType::DATA_STRING: delete data.String;
  162. break; case JsonType::DATA_VECTOR: delete data.Vector;
  163. break; case JsonType::DATA_STRUCT: delete data.Struct;
  164. break; default:
  165. break;
  166. }
  167. //Set new node type
  168. type = Type;
  169. switch(type)
  170. {
  171. break; case JsonType::DATA_NULL:
  172. break; case JsonType::DATA_BOOL: data.Bool = false;
  173. break; case JsonType::DATA_FLOAT: data.Float = 0;
  174. break; case JsonType::DATA_STRING: data.String = new std::string();
  175. break; case JsonType::DATA_VECTOR: data.Vector = new JsonVector();
  176. break; case JsonType::DATA_STRUCT: data.Struct = new JsonMap();
  177. break; case JsonType::DATA_INTEGER: data.Integer = 0;
  178. }
  179. }
  180. bool JsonNode::isNull() const
  181. {
  182. return type == JsonType::DATA_NULL;
  183. }
  184. bool JsonNode::isNumber() const
  185. {
  186. return type == JsonType::DATA_INTEGER || type == JsonType::DATA_FLOAT;
  187. }
  188. bool JsonNode::containsBaseData() const
  189. {
  190. switch(type)
  191. {
  192. case JsonType::DATA_NULL:
  193. return false;
  194. case JsonType::DATA_STRUCT:
  195. for(auto elem : *data.Struct)
  196. {
  197. if(elem.second.containsBaseData())
  198. return true;
  199. }
  200. return false;
  201. default:
  202. //other types (including vector) cannot be extended via merge
  203. return true;
  204. }
  205. }
  206. bool JsonNode::isCompact() const
  207. {
  208. switch(type)
  209. {
  210. case JsonType::DATA_VECTOR:
  211. for(JsonNode & elem : *data.Vector)
  212. {
  213. if(!elem.isCompact())
  214. return false;
  215. }
  216. return true;
  217. case JsonType::DATA_STRUCT:
  218. {
  219. int propertyCount = data.Struct->size();
  220. if(propertyCount == 0)
  221. return true;
  222. else if(propertyCount == 1)
  223. return data.Struct->begin()->second.isCompact();
  224. }
  225. return false;
  226. default:
  227. return true;
  228. }
  229. }
  230. void JsonNode::clear()
  231. {
  232. setType(JsonType::DATA_NULL);
  233. }
  234. bool & JsonNode::Bool()
  235. {
  236. setType(JsonType::DATA_BOOL);
  237. return data.Bool;
  238. }
  239. double & JsonNode::Float()
  240. {
  241. setType(JsonType::DATA_FLOAT);
  242. return data.Float;
  243. }
  244. si64 & JsonNode::Integer()
  245. {
  246. setType(JsonType::DATA_INTEGER);
  247. return data.Integer;
  248. }
  249. std::string & JsonNode::String()
  250. {
  251. setType(JsonType::DATA_STRING);
  252. return *data.String;
  253. }
  254. JsonVector & JsonNode::Vector()
  255. {
  256. setType(JsonType::DATA_VECTOR);
  257. return *data.Vector;
  258. }
  259. JsonMap & JsonNode::Struct()
  260. {
  261. setType(JsonType::DATA_STRUCT);
  262. return *data.Struct;
  263. }
  264. const bool boolDefault = false;
  265. bool JsonNode::Bool() const
  266. {
  267. if (type == JsonType::DATA_NULL)
  268. return boolDefault;
  269. assert(type == JsonType::DATA_BOOL);
  270. return data.Bool;
  271. }
  272. const double floatDefault = 0;
  273. double JsonNode::Float() const
  274. {
  275. if(type == JsonType::DATA_NULL)
  276. return floatDefault;
  277. else if(type == JsonType::DATA_INTEGER)
  278. return data.Integer;
  279. assert(type == JsonType::DATA_FLOAT);
  280. return data.Float;
  281. }
  282. const si64 integetDefault = 0;
  283. si64 JsonNode::Integer() const
  284. {
  285. if(type == JsonType::DATA_NULL)
  286. return integetDefault;
  287. else if(type == JsonType::DATA_FLOAT)
  288. return data.Float;
  289. assert(type == JsonType::DATA_INTEGER);
  290. return data.Integer;
  291. }
  292. const std::string stringDefault = std::string();
  293. const std::string & JsonNode::String() const
  294. {
  295. if (type == JsonType::DATA_NULL)
  296. return stringDefault;
  297. assert(type == JsonType::DATA_STRING);
  298. return *data.String;
  299. }
  300. const JsonVector vectorDefault = JsonVector();
  301. const JsonVector & JsonNode::Vector() const
  302. {
  303. if (type == JsonType::DATA_NULL)
  304. return vectorDefault;
  305. assert(type == JsonType::DATA_VECTOR);
  306. return *data.Vector;
  307. }
  308. const JsonMap mapDefault = JsonMap();
  309. const JsonMap & JsonNode::Struct() const
  310. {
  311. if (type == JsonType::DATA_NULL)
  312. return mapDefault;
  313. assert(type == JsonType::DATA_STRUCT);
  314. return *data.Struct;
  315. }
  316. JsonNode & JsonNode::operator[](std::string child)
  317. {
  318. return Struct()[child];
  319. }
  320. const JsonNode & JsonNode::operator[](std::string child) const
  321. {
  322. auto it = Struct().find(child);
  323. if (it != Struct().end())
  324. return it->second;
  325. return nullNode;
  326. }
  327. // to avoid duplicating const and non-const code
  328. template<typename Node>
  329. Node & resolvePointer(Node & in, const std::string & pointer)
  330. {
  331. if (pointer.empty())
  332. return in;
  333. assert(pointer[0] == '/');
  334. size_t splitPos = pointer.find('/', 1);
  335. std::string entry = pointer.substr(1, splitPos -1);
  336. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  337. if (in.getType() == JsonNode::JsonType::DATA_VECTOR)
  338. {
  339. if (entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  340. throw std::runtime_error("Invalid Json pointer");
  341. if (entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  342. throw std::runtime_error("Invalid Json pointer");
  343. size_t index = boost::lexical_cast<size_t>(entry);
  344. if (in.Vector().size() > index)
  345. return in.Vector()[index].resolvePointer(remainer);
  346. }
  347. return in[entry].resolvePointer(remainer);
  348. }
  349. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  350. {
  351. return ::resolvePointer(*this, jsonPointer);
  352. }
  353. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  354. {
  355. return ::resolvePointer(*this, jsonPointer);
  356. }
  357. std::string JsonNode::toJson(bool compact) const
  358. {
  359. std::ostringstream out;
  360. JsonWriter writer(out, compact);
  361. writer.writeNode(*this);
  362. out << "\n";
  363. return out.str();
  364. }
  365. ///JsonUtils
  366. void JsonUtils::parseTypedBonusShort(const JsonVector& source, std::shared_ptr<Bonus> dest)
  367. {
  368. dest->val = source[1].Float();
  369. resolveIdentifier(source[2],dest->subtype);
  370. dest->additionalInfo = source[3].Float();
  371. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  372. dest->turnsRemain = 0;
  373. }
  374. std::shared_ptr<Bonus> JsonUtils::parseBonus (const JsonVector &ability_vec) //TODO: merge with AddAbility, create universal parser for all bonus properties
  375. {
  376. auto b = std::make_shared<Bonus>();
  377. std::string type = ability_vec[0].String();
  378. auto it = bonusNameMap.find(type);
  379. if (it == bonusNameMap.end())
  380. {
  381. logMod->error("Error: invalid ability type %s.", type);
  382. return b;
  383. }
  384. b->type = it->second;
  385. parseTypedBonusShort(ability_vec, b);
  386. return b;
  387. }
  388. template <typename T>
  389. const T & parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  390. {
  391. static T defaultValue = T();
  392. if (!val->isNull())
  393. {
  394. std::string type = val->String();
  395. auto it = map.find(type);
  396. if (it == map.end())
  397. {
  398. logMod->error("Error: invalid %s%s.", err, type);
  399. return defaultValue;
  400. }
  401. else
  402. {
  403. return it->second;
  404. }
  405. }
  406. else
  407. return defaultValue;
  408. }
  409. void JsonUtils::resolveIdentifier(si32 &var, const JsonNode &node, std::string name)
  410. {
  411. const JsonNode &value = node[name];
  412. if (!value.isNull())
  413. {
  414. switch (value.getType())
  415. {
  416. case JsonNode::JsonType::DATA_INTEGER:
  417. var = value.Integer();
  418. break;
  419. case JsonNode::JsonType::DATA_FLOAT:
  420. var = value.Float();
  421. break;
  422. case JsonNode::JsonType::DATA_STRING:
  423. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  424. {
  425. var = identifier;
  426. });
  427. break;
  428. default:
  429. logMod->error("Error! Wrong identifier used for value of %s.", name);
  430. }
  431. }
  432. }
  433. void JsonUtils::resolveIdentifier(const JsonNode &node, si32 &var)
  434. {
  435. switch (node.getType())
  436. {
  437. case JsonNode::JsonType::DATA_INTEGER:
  438. var = node.Integer();
  439. break;
  440. case JsonNode::JsonType::DATA_FLOAT:
  441. var = node.Float();
  442. break;
  443. case JsonNode::JsonType::DATA_STRING:
  444. VLC->modh->identifiers.requestIdentifier(node, [&](si32 identifier)
  445. {
  446. var = identifier;
  447. });
  448. break;
  449. default:
  450. logMod->error("Error! Wrong identifier used for identifier!");
  451. }
  452. }
  453. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  454. {
  455. auto b = std::make_shared<Bonus>();
  456. if (!parseBonus(ability, b.get()))
  457. {
  458. return nullptr;
  459. }
  460. return b;
  461. }
  462. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  463. {
  464. const JsonNode *value;
  465. std::string type = ability["type"].String();
  466. auto it = bonusNameMap.find(type);
  467. if (it == bonusNameMap.end())
  468. {
  469. logMod->error("Error: invalid ability type %s.", type);
  470. return false;
  471. }
  472. b->type = it->second;
  473. resolveIdentifier(b->subtype, ability, "subtype");
  474. b->val = ability["val"].Float();
  475. value = &ability["valueType"];
  476. if (!value->isNull())
  477. b->valType = static_cast<Bonus::ValueType>(parseByMap(bonusValueMap, value, "value type "));
  478. resolveIdentifier(b->additionalInfo, ability, "addInfo");
  479. b->turnsRemain = ability["turns"].Float();
  480. b->sid = ability["sourceID"].Float();
  481. b->description = ability["description"].String();
  482. value = &ability["effectRange"];
  483. if (!value->isNull())
  484. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMap(bonusLimitEffect, value, "effect range "));
  485. value = &ability["duration"];
  486. if (!value->isNull())
  487. {
  488. switch (value->getType())
  489. {
  490. case JsonNode::JsonType::DATA_STRING:
  491. b->duration = parseByMap(bonusDurationMap, value, "duration type ");
  492. break;
  493. case JsonNode::JsonType::DATA_VECTOR:
  494. {
  495. ui16 dur = 0;
  496. for (const JsonNode & d : value->Vector())
  497. {
  498. dur |= parseByMap(bonusDurationMap, &d, "duration type ");
  499. }
  500. b->duration = dur;
  501. }
  502. break;
  503. default:
  504. logMod->error("Error! Wrong bonus duration format.");
  505. }
  506. }
  507. value = &ability["source"];
  508. if (!value->isNull())
  509. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  510. value = &ability["limiters"];
  511. if (!value->isNull())
  512. {
  513. for (const JsonNode & limiter : value->Vector())
  514. {
  515. switch (limiter.getType())
  516. {
  517. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  518. b->limiter = parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  519. break;
  520. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  521. {
  522. std::shared_ptr<ILimiter> l;
  523. if (limiter["type"].String() == "CREATURE_TYPE_LIMITER")
  524. {
  525. std::shared_ptr<CCreatureTypeLimiter> l2 = std::make_shared<CCreatureTypeLimiter>(); //TODO: How the hell resolve pointer to creature?
  526. const JsonVector vec = limiter["parameters"].Vector();
  527. VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature)
  528. {
  529. l2->setCreature(CreatureID(creature));
  530. });
  531. if (vec.size() > 1)
  532. {
  533. l2->includeUpgrades = vec[1].Bool();
  534. }
  535. else
  536. l2->includeUpgrades = false;
  537. l = l2;
  538. }
  539. if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER")
  540. {
  541. std::shared_ptr<HasAnotherBonusLimiter> l2 = std::make_shared<HasAnotherBonusLimiter>();
  542. const JsonVector vec = limiter["parameters"].Vector();
  543. std::string anotherBonusType = vec[0].String();
  544. auto it = bonusNameMap.find(anotherBonusType);
  545. if (it == bonusNameMap.end())
  546. {
  547. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  548. continue;
  549. }
  550. l2->type = it->second;
  551. if (vec.size() > 1 )
  552. {
  553. resolveIdentifier(vec[1], l2->subtype);
  554. l2->isSubtypeRelevant = true;
  555. }
  556. l = l2;
  557. }
  558. b->addLimiter(l);
  559. }
  560. break;
  561. }
  562. }
  563. }
  564. value = &ability["propagator"];
  565. if (!value->isNull())
  566. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  567. value = &ability["updater"];
  568. if(!value->isNull())
  569. {
  570. const JsonNode & updaterJson = *value;
  571. switch(updaterJson.getType())
  572. {
  573. case JsonNode::JsonType::DATA_STRING:
  574. b->addUpdater(parseByMap(bonusUpdaterMap, &updaterJson, "updater type "));
  575. break;
  576. case JsonNode::JsonType::DATA_STRUCT:
  577. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  578. {
  579. std::shared_ptr<GrowsWithLevelUpdater> updater = std::make_shared<GrowsWithLevelUpdater>();
  580. const JsonVector param = updaterJson["parameters"].Vector();
  581. updater->valPer20 = param[0].Integer();
  582. if(param.size() > 1)
  583. updater->stepSize = param[1].Integer();
  584. b->addUpdater(updater);
  585. }
  586. else
  587. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  588. break;
  589. }
  590. }
  591. return true;
  592. }
  593. //returns first Key with value equal to given one
  594. template<class Key, class Val>
  595. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  596. {
  597. for(auto it : map)
  598. {
  599. if(it.second == val)
  600. {
  601. return it.first;
  602. }
  603. }
  604. assert(0);
  605. return "";
  606. }
  607. void JsonUtils::unparseBonus( JsonNode &node, const std::shared_ptr<Bonus>& bonus )
  608. {
  609. node["type"].String() = reverseMapFirst<std::string, Bonus::BonusType>(bonus->type, bonusNameMap);
  610. node["subtype"].Float() = bonus->subtype;
  611. node["val"].Float() = bonus->val;
  612. node["valueType"].String() = reverseMapFirst<std::string, Bonus::ValueType>(bonus->valType, bonusValueMap);
  613. node["additionalInfo"].Float() = bonus->additionalInfo;
  614. node["turns"].Float() = bonus->turnsRemain;
  615. node["sourceID"].Float() = bonus->source;
  616. node["description"].String() = bonus->description;
  617. node["effectRange"].String() = reverseMapFirst<std::string, Bonus::LimitEffect>(bonus->effectRange, bonusLimitEffect);
  618. node["duration"].String() = reverseMapFirst<std::string, ui16>(bonus->duration, bonusDurationMap);
  619. node["source"].String() = reverseMapFirst<std::string, Bonus::BonusSource>(bonus->source, bonusSourceMap);
  620. if(bonus->limiter)
  621. {
  622. node["limiter"].String() = reverseMapFirst<std::string, TLimiterPtr>(bonus->limiter, bonusLimiterMap);
  623. }
  624. if(bonus->propagator)
  625. {
  626. node["propagator"].String() = reverseMapFirst<std::string, TPropagatorPtr>(bonus->propagator, bonusPropagatorMap);
  627. }
  628. }
  629. void minimizeNode(JsonNode & node, const JsonNode & schema)
  630. {
  631. if (schema["type"].String() == "object")
  632. {
  633. std::set<std::string> foundEntries;
  634. for(auto & entry : schema["required"].Vector())
  635. {
  636. std::string name = entry.String();
  637. foundEntries.insert(name);
  638. minimizeNode(node[name], schema["properties"][name]);
  639. if (vstd::contains(node.Struct(), name) &&
  640. node[name] == schema["properties"][name]["default"])
  641. {
  642. node.Struct().erase(name);
  643. }
  644. }
  645. // erase all unhandled entries
  646. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  647. {
  648. if (!vstd::contains(foundEntries, it->first))
  649. it = node.Struct().erase(it);
  650. else
  651. it++;
  652. }
  653. }
  654. }
  655. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  656. {
  657. minimizeNode(node, getSchema(schemaName));
  658. }
  659. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  660. void maximizeNode(JsonNode & node, const JsonNode & schema)
  661. {
  662. // "required" entry can only be found in object/struct
  663. if (schema["type"].String() == "object")
  664. {
  665. std::set<std::string> foundEntries;
  666. // check all required entries that have default version
  667. for(auto & entry : schema["required"].Vector())
  668. {
  669. std::string name = entry.String();
  670. foundEntries.insert(name);
  671. if (node[name].isNull() &&
  672. !schema["properties"][name]["default"].isNull())
  673. {
  674. node[name] = schema["properties"][name]["default"];
  675. }
  676. maximizeNode(node[name], schema["properties"][name]);
  677. }
  678. // erase all unhandled entries
  679. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  680. {
  681. if (!vstd::contains(foundEntries, it->first))
  682. it = node.Struct().erase(it);
  683. else
  684. it++;
  685. }
  686. }
  687. }
  688. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  689. {
  690. maximizeNode(node, getSchema(schemaName));
  691. }
  692. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  693. {
  694. std::string log = Validation::check(schemaName, node);
  695. if (!log.empty())
  696. {
  697. logMod->warn("Data in %s is invalid!", dataName);
  698. logMod->warn(log);
  699. logMod->trace("%s json: %s", dataName, node.toJson(true));
  700. }
  701. return log.empty();
  702. }
  703. const JsonNode & getSchemaByName(std::string name)
  704. {
  705. // cached schemas to avoid loading json data multiple times
  706. static std::map<std::string, JsonNode> loadedSchemas;
  707. if (vstd::contains(loadedSchemas, name))
  708. return loadedSchemas[name];
  709. std::string filename = "config/schemas/" + name + ".json";
  710. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  711. {
  712. loadedSchemas[name] = JsonNode(ResourceID(filename));
  713. return loadedSchemas[name];
  714. }
  715. logMod->error("Error: missing schema with name %s!", name);
  716. assert(0);
  717. return nullNode;
  718. }
  719. const JsonNode & JsonUtils::getSchema(std::string URI)
  720. {
  721. size_t posColon = URI.find(':');
  722. size_t posHash = URI.find('#');
  723. if(posColon == std::string::npos)
  724. {
  725. logMod->error("Invalid schema URI:%s", URI);
  726. return nullNode;
  727. }
  728. std::string protocolName = URI.substr(0, posColon);
  729. std::string filename = URI.substr(posColon + 1, posHash - posColon - 1);
  730. if(protocolName != "vcmi")
  731. {
  732. logMod->error("Error: unsupported URI protocol for schema: %s", URI);
  733. return nullNode;
  734. }
  735. // check if json pointer if present (section after hash in string)
  736. if(posHash == std::string::npos || posHash == URI.size() - 1)
  737. return getSchemaByName(filename);
  738. else
  739. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  740. }
  741. void JsonUtils::merge(JsonNode & dest, JsonNode & source)
  742. {
  743. if (dest.getType() == JsonNode::JsonType::DATA_NULL)
  744. {
  745. std::swap(dest, source);
  746. return;
  747. }
  748. switch (source.getType())
  749. {
  750. case JsonNode::JsonType::DATA_NULL:
  751. {
  752. dest.clear();
  753. break;
  754. }
  755. case JsonNode::JsonType::DATA_BOOL:
  756. case JsonNode::JsonType::DATA_FLOAT:
  757. case JsonNode::JsonType::DATA_INTEGER:
  758. case JsonNode::JsonType::DATA_STRING:
  759. case JsonNode::JsonType::DATA_VECTOR:
  760. {
  761. std::swap(dest, source);
  762. break;
  763. }
  764. case JsonNode::JsonType::DATA_STRUCT:
  765. {
  766. //recursively merge all entries from struct
  767. for(auto & node : source.Struct())
  768. merge(dest[node.first], node.second);
  769. }
  770. }
  771. }
  772. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source)
  773. {
  774. // uses copy created in stack to safely merge two nodes
  775. merge(dest, source);
  776. }
  777. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  778. {
  779. JsonNode inheritedNode(base);
  780. merge(inheritedNode,descendant);
  781. descendant.swap(inheritedNode);
  782. }
  783. JsonNode JsonUtils::intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty)
  784. {
  785. if(nodes.size() == 0)
  786. return nullNode;
  787. JsonNode result = nodes[0];
  788. for(int i = 1; i < nodes.size(); i++)
  789. {
  790. if(result.isNull())
  791. break;
  792. result = JsonUtils::intersect(result, nodes[i], pruneEmpty);
  793. }
  794. return result;
  795. }
  796. JsonNode JsonUtils::intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty)
  797. {
  798. if(a.getType() == JsonNode::JsonType::DATA_STRUCT && b.getType() == JsonNode::JsonType::DATA_STRUCT)
  799. {
  800. // intersect individual properties
  801. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  802. for(auto property : a.Struct())
  803. {
  804. if(vstd::contains(b.Struct(), property.first))
  805. {
  806. JsonNode propertyIntersect = JsonUtils::intersect(property.second, b.Struct().find(property.first)->second);
  807. if(pruneEmpty && !propertyIntersect.containsBaseData())
  808. continue;
  809. result[property.first] = propertyIntersect;
  810. }
  811. }
  812. return result;
  813. }
  814. else
  815. {
  816. // not a struct - same or different, no middle ground
  817. if(a == b)
  818. return a;
  819. }
  820. return nullNode;
  821. }
  822. JsonNode JsonUtils::difference(const JsonNode & node, const JsonNode & base)
  823. {
  824. auto addsInfo = [](JsonNode diff) -> bool
  825. {
  826. switch(diff.getType())
  827. {
  828. case JsonNode::JsonType::DATA_NULL:
  829. return false;
  830. case JsonNode::JsonType::DATA_STRUCT:
  831. return diff.Struct().size() > 0;
  832. default:
  833. return true;
  834. }
  835. };
  836. if(node.getType() == JsonNode::JsonType::DATA_STRUCT && base.getType() == JsonNode::JsonType::DATA_STRUCT)
  837. {
  838. // subtract individual properties
  839. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  840. for(auto property : node.Struct())
  841. {
  842. if(vstd::contains(base.Struct(), property.first))
  843. {
  844. const JsonNode propertyDifference = JsonUtils::difference(property.second, base.Struct().find(property.first)->second);
  845. if(addsInfo(propertyDifference))
  846. result[property.first] = propertyDifference;
  847. }
  848. else
  849. {
  850. result[property.first] = property.second;
  851. }
  852. }
  853. return result;
  854. }
  855. else
  856. {
  857. if(node == base)
  858. return nullNode;
  859. }
  860. return node;
  861. }
  862. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  863. {
  864. bool isValid;
  865. return assembleFromFiles(files, isValid);
  866. }
  867. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  868. {
  869. isValid = true;
  870. JsonNode result;
  871. for(std::string file : files)
  872. {
  873. bool isValidFile;
  874. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  875. merge(result, section);
  876. isValid |= isValidFile;
  877. }
  878. return result;
  879. }
  880. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  881. {
  882. JsonNode result;
  883. ResourceID resID(filename, EResType::TEXT);
  884. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  885. {
  886. // FIXME: some way to make this code more readable
  887. auto stream = loader->load(resID);
  888. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  889. stream->read(textData.get(), stream->getSize());
  890. JsonNode section((char*)textData.get(), stream->getSize());
  891. merge(result, section);
  892. }
  893. return result;
  894. }
  895. DLL_LINKAGE JsonNode JsonUtils::boolNode(bool value)
  896. {
  897. JsonNode node;
  898. node.Bool() = value;
  899. return node;
  900. }
  901. DLL_LINKAGE JsonNode JsonUtils::floatNode(double value)
  902. {
  903. JsonNode node;
  904. node.Float() = value;
  905. return node;
  906. }
  907. DLL_LINKAGE JsonNode JsonUtils::stringNode(std::string value)
  908. {
  909. JsonNode node;
  910. node.String() = value;
  911. return node;
  912. }
  913. DLL_LINKAGE JsonNode JsonUtils::intNode(si64 value)
  914. {
  915. JsonNode node;
  916. node.Integer() = value;
  917. return node;
  918. }