JsonNode.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. #include "StringConstants.h"
  20. namespace
  21. {
  22. // to avoid duplicating const and non-const code
  23. template<typename Node>
  24. Node & resolvePointer(Node & in, const std::string & pointer)
  25. {
  26. if(pointer.empty())
  27. return in;
  28. assert(pointer[0] == '/');
  29. size_t splitPos = pointer.find('/', 1);
  30. std::string entry = pointer.substr(1, splitPos - 1);
  31. std::string remainer = splitPos == std::string::npos ? "" : pointer.substr(splitPos);
  32. if(in.getType() == VCMI_LIB_WRAP_NAMESPACE(JsonNode)::JsonType::DATA_VECTOR)
  33. {
  34. if(entry.find_first_not_of("0123456789") != std::string::npos) // non-numbers in string
  35. throw std::runtime_error("Invalid Json pointer");
  36. if(entry.size() > 1 && entry[0] == '0') // leading zeros are not allowed
  37. throw std::runtime_error("Invalid Json pointer");
  38. size_t index = boost::lexical_cast<size_t>(entry);
  39. if (in.Vector().size() > index)
  40. return in.Vector()[index].resolvePointer(remainer);
  41. }
  42. return in[entry].resolvePointer(remainer);
  43. }
  44. }
  45. VCMI_LIB_NAMESPACE_BEGIN
  46. using namespace JsonDetail;
  47. class LibClasses;
  48. class CModHandler;
  49. static const JsonNode nullNode;
  50. JsonNode::JsonNode(JsonType Type):
  51. type(JsonType::DATA_NULL)
  52. {
  53. setType(Type);
  54. }
  55. JsonNode::JsonNode(const char *data, size_t datasize):
  56. type(JsonType::DATA_NULL)
  57. {
  58. JsonParser parser(data, datasize);
  59. *this = parser.parse("<unknown>");
  60. }
  61. JsonNode::JsonNode(ResourceID && fileURI):
  62. type(JsonType::DATA_NULL)
  63. {
  64. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  65. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  66. *this = parser.parse(fileURI.getName());
  67. }
  68. JsonNode::JsonNode(const ResourceID & fileURI):
  69. type(JsonType::DATA_NULL)
  70. {
  71. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  72. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  73. *this = parser.parse(fileURI.getName());
  74. }
  75. JsonNode::JsonNode(const std::string & idx, const ResourceID & fileURI):
  76. type(JsonType::DATA_NULL)
  77. {
  78. auto file = CResourceHandler::get(idx)->load(fileURI)->readAll();
  79. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  80. *this = parser.parse(fileURI.getName());
  81. }
  82. JsonNode::JsonNode(ResourceID && fileURI, bool &isValidSyntax):
  83. type(JsonType::DATA_NULL)
  84. {
  85. auto file = CResourceHandler::get()->load(fileURI)->readAll();
  86. JsonParser parser(reinterpret_cast<char*>(file.first.get()), file.second);
  87. *this = parser.parse(fileURI.getName());
  88. isValidSyntax = parser.isValid();
  89. }
  90. JsonNode::JsonNode(const JsonNode &copy):
  91. type(JsonType::DATA_NULL),
  92. meta(copy.meta),
  93. flags(copy.flags)
  94. {
  95. setType(copy.getType());
  96. switch(type)
  97. {
  98. break; case JsonType::DATA_NULL:
  99. break; case JsonType::DATA_BOOL: Bool() = copy.Bool();
  100. break; case JsonType::DATA_FLOAT: Float() = copy.Float();
  101. break; case JsonType::DATA_STRING: String() = copy.String();
  102. break; case JsonType::DATA_VECTOR: Vector() = copy.Vector();
  103. break; case JsonType::DATA_STRUCT: Struct() = copy.Struct();
  104. break; case JsonType::DATA_INTEGER:Integer() = copy.Integer();
  105. }
  106. }
  107. JsonNode::~JsonNode()
  108. {
  109. setType(JsonType::DATA_NULL);
  110. }
  111. void JsonNode::swap(JsonNode &b)
  112. {
  113. using std::swap;
  114. swap(meta, b.meta);
  115. swap(data, b.data);
  116. swap(type, b.type);
  117. swap(flags, b.flags);
  118. }
  119. JsonNode & JsonNode::operator =(JsonNode node)
  120. {
  121. swap(node);
  122. return *this;
  123. }
  124. bool JsonNode::operator == (const JsonNode &other) const
  125. {
  126. if (getType() == other.getType())
  127. {
  128. switch(type)
  129. {
  130. case JsonType::DATA_NULL: return true;
  131. case JsonType::DATA_BOOL: return Bool() == other.Bool();
  132. case JsonType::DATA_FLOAT: return Float() == other.Float();
  133. case JsonType::DATA_STRING: return String() == other.String();
  134. case JsonType::DATA_VECTOR: return Vector() == other.Vector();
  135. case JsonType::DATA_STRUCT: return Struct() == other.Struct();
  136. case JsonType::DATA_INTEGER:return Integer()== other.Integer();
  137. }
  138. }
  139. return false;
  140. }
  141. bool JsonNode::operator != (const JsonNode &other) const
  142. {
  143. return !(*this == other);
  144. }
  145. JsonNode::JsonType JsonNode::getType() const
  146. {
  147. return type;
  148. }
  149. void JsonNode::setMeta(std::string metadata, bool recursive)
  150. {
  151. meta = metadata;
  152. if (recursive)
  153. {
  154. switch (type)
  155. {
  156. break; case JsonType::DATA_VECTOR:
  157. {
  158. for(auto & node : Vector())
  159. {
  160. node.setMeta(metadata);
  161. }
  162. }
  163. break; case JsonType::DATA_STRUCT:
  164. {
  165. for(auto & node : Struct())
  166. {
  167. node.second.setMeta(metadata);
  168. }
  169. }
  170. }
  171. }
  172. }
  173. void JsonNode::setType(JsonType Type)
  174. {
  175. if (type == Type)
  176. return;
  177. //float<->int conversion
  178. if(type == JsonType::DATA_FLOAT && Type == JsonType::DATA_INTEGER)
  179. {
  180. si64 converted = static_cast<si64>(data.Float);
  181. type = Type;
  182. data.Integer = converted;
  183. return;
  184. }
  185. else if(type == JsonType::DATA_INTEGER && Type == JsonType::DATA_FLOAT)
  186. {
  187. double converted = static_cast<double>(data.Integer);
  188. type = Type;
  189. data.Float = converted;
  190. return;
  191. }
  192. //Reset node to nullptr
  193. if (Type != JsonType::DATA_NULL)
  194. setType(JsonType::DATA_NULL);
  195. switch (type)
  196. {
  197. break; case JsonType::DATA_STRING: delete data.String;
  198. break; case JsonType::DATA_VECTOR: delete data.Vector;
  199. break; case JsonType::DATA_STRUCT: delete data.Struct;
  200. break; default:
  201. break;
  202. }
  203. //Set new node type
  204. type = Type;
  205. switch(type)
  206. {
  207. break; case JsonType::DATA_NULL:
  208. break; case JsonType::DATA_BOOL: data.Bool = false;
  209. break; case JsonType::DATA_FLOAT: data.Float = 0;
  210. break; case JsonType::DATA_STRING: data.String = new std::string();
  211. break; case JsonType::DATA_VECTOR: data.Vector = new JsonVector();
  212. break; case JsonType::DATA_STRUCT: data.Struct = new JsonMap();
  213. break; case JsonType::DATA_INTEGER: data.Integer = 0;
  214. }
  215. }
  216. bool JsonNode::isNull() const
  217. {
  218. return type == JsonType::DATA_NULL;
  219. }
  220. bool JsonNode::isNumber() const
  221. {
  222. return type == JsonType::DATA_INTEGER || type == JsonType::DATA_FLOAT;
  223. }
  224. bool JsonNode::isString() const
  225. {
  226. return type == JsonType::DATA_STRING;
  227. }
  228. bool JsonNode::isVector() const
  229. {
  230. return type == JsonType::DATA_VECTOR;
  231. }
  232. bool JsonNode::isStruct() const
  233. {
  234. return type == JsonType::DATA_STRUCT;
  235. }
  236. bool JsonNode::containsBaseData() const
  237. {
  238. switch(type)
  239. {
  240. case JsonType::DATA_NULL:
  241. return false;
  242. case JsonType::DATA_STRUCT:
  243. for(auto elem : *data.Struct)
  244. {
  245. if(elem.second.containsBaseData())
  246. return true;
  247. }
  248. return false;
  249. default:
  250. //other types (including vector) cannot be extended via merge
  251. return true;
  252. }
  253. }
  254. bool JsonNode::isCompact() const
  255. {
  256. switch(type)
  257. {
  258. case JsonType::DATA_VECTOR:
  259. for(JsonNode & elem : *data.Vector)
  260. {
  261. if(!elem.isCompact())
  262. return false;
  263. }
  264. return true;
  265. case JsonType::DATA_STRUCT:
  266. {
  267. auto propertyCount = data.Struct->size();
  268. if(propertyCount == 0)
  269. return true;
  270. else if(propertyCount == 1)
  271. return data.Struct->begin()->second.isCompact();
  272. }
  273. return false;
  274. default:
  275. return true;
  276. }
  277. }
  278. bool JsonNode::TryBoolFromString(bool & success) const
  279. {
  280. success = true;
  281. if(type == JsonNode::JsonType::DATA_BOOL)
  282. return Bool();
  283. success = type == JsonNode::JsonType::DATA_STRING;
  284. if(success)
  285. {
  286. auto boolParamStr = String();
  287. boost::algorithm::trim(boolParamStr);
  288. boost::algorithm::to_lower(boolParamStr);
  289. success = boolParamStr == "true";
  290. if(success)
  291. return true;
  292. success = boolParamStr == "false";
  293. }
  294. return false;
  295. }
  296. void JsonNode::clear()
  297. {
  298. setType(JsonType::DATA_NULL);
  299. }
  300. bool & JsonNode::Bool()
  301. {
  302. setType(JsonType::DATA_BOOL);
  303. return data.Bool;
  304. }
  305. double & JsonNode::Float()
  306. {
  307. setType(JsonType::DATA_FLOAT);
  308. return data.Float;
  309. }
  310. si64 & JsonNode::Integer()
  311. {
  312. setType(JsonType::DATA_INTEGER);
  313. return data.Integer;
  314. }
  315. std::string & JsonNode::String()
  316. {
  317. setType(JsonType::DATA_STRING);
  318. return *data.String;
  319. }
  320. JsonVector & JsonNode::Vector()
  321. {
  322. setType(JsonType::DATA_VECTOR);
  323. return *data.Vector;
  324. }
  325. JsonMap & JsonNode::Struct()
  326. {
  327. setType(JsonType::DATA_STRUCT);
  328. return *data.Struct;
  329. }
  330. const bool boolDefault = false;
  331. bool JsonNode::Bool() const
  332. {
  333. if (type == JsonType::DATA_NULL)
  334. return boolDefault;
  335. assert(type == JsonType::DATA_BOOL);
  336. return data.Bool;
  337. }
  338. const double floatDefault = 0;
  339. double JsonNode::Float() const
  340. {
  341. if(type == JsonType::DATA_NULL)
  342. return floatDefault;
  343. else if(type == JsonType::DATA_INTEGER)
  344. return static_cast<double>(data.Integer);
  345. assert(type == JsonType::DATA_FLOAT);
  346. return data.Float;
  347. }
  348. const si64 integetDefault = 0;
  349. si64 JsonNode::Integer() const
  350. {
  351. if(type == JsonType::DATA_NULL)
  352. return integetDefault;
  353. else if(type == JsonType::DATA_FLOAT)
  354. return static_cast<si64>(data.Float);
  355. assert(type == JsonType::DATA_INTEGER);
  356. return data.Integer;
  357. }
  358. const std::string stringDefault = std::string();
  359. const std::string & JsonNode::String() const
  360. {
  361. if (type == JsonType::DATA_NULL)
  362. return stringDefault;
  363. assert(type == JsonType::DATA_STRING);
  364. return *data.String;
  365. }
  366. const JsonVector vectorDefault = JsonVector();
  367. const JsonVector & JsonNode::Vector() const
  368. {
  369. if (type == JsonType::DATA_NULL)
  370. return vectorDefault;
  371. assert(type == JsonType::DATA_VECTOR);
  372. return *data.Vector;
  373. }
  374. const JsonMap mapDefault = JsonMap();
  375. const JsonMap & JsonNode::Struct() const
  376. {
  377. if (type == JsonType::DATA_NULL)
  378. return mapDefault;
  379. assert(type == JsonType::DATA_STRUCT);
  380. return *data.Struct;
  381. }
  382. JsonNode & JsonNode::operator[](std::string child)
  383. {
  384. return Struct()[child];
  385. }
  386. const JsonNode & JsonNode::operator[](std::string child) const
  387. {
  388. auto it = Struct().find(child);
  389. if (it != Struct().end())
  390. return it->second;
  391. return nullNode;
  392. }
  393. const JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer) const
  394. {
  395. return ::resolvePointer(*this, jsonPointer);
  396. }
  397. JsonNode & JsonNode::resolvePointer(const std::string &jsonPointer)
  398. {
  399. return ::resolvePointer(*this, jsonPointer);
  400. }
  401. std::string JsonNode::toJson(bool compact) const
  402. {
  403. std::ostringstream out;
  404. JsonWriter writer(out, compact);
  405. writer.writeNode(*this);
  406. return out.str();
  407. }
  408. ///JsonUtils
  409. void JsonUtils::parseTypedBonusShort(const JsonVector& source, std::shared_ptr<Bonus> dest)
  410. {
  411. dest->val = static_cast<si32>(source[1].Float());
  412. resolveIdentifier(source[2],dest->subtype);
  413. dest->additionalInfo = static_cast<si32>(source[3].Float());
  414. dest->duration = Bonus::PERMANENT; //TODO: handle flags (as integer)
  415. dest->turnsRemain = 0;
  416. }
  417. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonVector & ability_vec)
  418. {
  419. auto b = std::make_shared<Bonus>();
  420. std::string type = ability_vec[0].String();
  421. auto it = bonusNameMap.find(type);
  422. if (it == bonusNameMap.end())
  423. {
  424. logMod->error("Error: invalid ability type %s.", type);
  425. return b;
  426. }
  427. b->type = it->second;
  428. parseTypedBonusShort(ability_vec, b);
  429. return b;
  430. }
  431. template <typename T>
  432. const T parseByMap(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  433. {
  434. static T defaultValue = T();
  435. if (!val->isNull())
  436. {
  437. std::string type = val->String();
  438. auto it = map.find(type);
  439. if (it == map.end())
  440. {
  441. logMod->error("Error: invalid %s%s.", err, type);
  442. return defaultValue;
  443. }
  444. else
  445. {
  446. return it->second;
  447. }
  448. }
  449. else
  450. return defaultValue;
  451. }
  452. template <typename T>
  453. const T parseByMapN(const std::map<std::string, T> & map, const JsonNode * val, std::string err)
  454. {
  455. if(val->isNumber())
  456. return static_cast<T>(val->Integer());
  457. else
  458. return parseByMap<T>(map, val, err);
  459. }
  460. void JsonUtils::resolveIdentifier(si32 &var, const JsonNode &node, std::string name)
  461. {
  462. const JsonNode &value = node[name];
  463. if (!value.isNull())
  464. {
  465. switch (value.getType())
  466. {
  467. case JsonNode::JsonType::DATA_INTEGER:
  468. var = static_cast<si32>(value.Integer());
  469. break;
  470. case JsonNode::JsonType::DATA_FLOAT:
  471. var = static_cast<si32>(value.Float());
  472. break;
  473. case JsonNode::JsonType::DATA_STRING:
  474. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  475. {
  476. var = identifier;
  477. });
  478. break;
  479. default:
  480. logMod->error("Error! Wrong identifier used for value of %s.", name);
  481. }
  482. }
  483. }
  484. void JsonUtils::resolveAddInfo(CAddInfo & var, const JsonNode & node)
  485. {
  486. const JsonNode & value = node["addInfo"];
  487. if (!value.isNull())
  488. {
  489. switch (value.getType())
  490. {
  491. case JsonNode::JsonType::DATA_INTEGER:
  492. var = static_cast<si32>(value.Integer());
  493. break;
  494. case JsonNode::JsonType::DATA_FLOAT:
  495. var = static_cast<si32>(value.Float());
  496. break;
  497. case JsonNode::JsonType::DATA_STRING:
  498. VLC->modh->identifiers.requestIdentifier(value, [&](si32 identifier)
  499. {
  500. var = identifier;
  501. });
  502. break;
  503. case JsonNode::JsonType::DATA_VECTOR:
  504. {
  505. const JsonVector & vec = value.Vector();
  506. var.resize(vec.size());
  507. for(int i = 0; i < vec.size(); i++)
  508. {
  509. switch(vec[i].getType())
  510. {
  511. case JsonNode::JsonType::DATA_INTEGER:
  512. var[i] = static_cast<si32>(vec[i].Integer());
  513. break;
  514. case JsonNode::JsonType::DATA_FLOAT:
  515. var[i] = static_cast<si32>(vec[i].Float());
  516. break;
  517. case JsonNode::JsonType::DATA_STRING:
  518. VLC->modh->identifiers.requestIdentifier(vec[i], [&var,i](si32 identifier)
  519. {
  520. var[i] = identifier;
  521. });
  522. break;
  523. default:
  524. logMod->error("Error! Wrong identifier used for value of addInfo[%d].", i);
  525. }
  526. }
  527. break;
  528. }
  529. default:
  530. logMod->error("Error! Wrong identifier used for value of addInfo.");
  531. }
  532. }
  533. }
  534. void JsonUtils::resolveIdentifier(const JsonNode &node, si32 &var)
  535. {
  536. switch (node.getType())
  537. {
  538. case JsonNode::JsonType::DATA_INTEGER:
  539. var = static_cast<si32>(node.Integer());
  540. break;
  541. case JsonNode::JsonType::DATA_FLOAT:
  542. var = static_cast<si32>(node.Float());
  543. break;
  544. case JsonNode::JsonType::DATA_STRING:
  545. VLC->modh->identifiers.requestIdentifier(node, [&](si32 identifier)
  546. {
  547. var = identifier;
  548. });
  549. break;
  550. default:
  551. logMod->error("Error! Wrong identifier used for identifier!");
  552. }
  553. }
  554. std::shared_ptr<ILimiter> JsonUtils::parseLimiter(const JsonNode & limiter)
  555. {
  556. switch(limiter.getType())
  557. {
  558. case JsonNode::JsonType::DATA_VECTOR:
  559. {
  560. const JsonVector & subLimiters = limiter.Vector();
  561. if(subLimiters.size() == 0)
  562. {
  563. logMod->warn("Warning: empty limiter list");
  564. return std::make_shared<AllOfLimiter>();
  565. }
  566. std::shared_ptr<AggregateLimiter> result;
  567. int offset = 1;
  568. // determine limiter type and offset for sub-limiters
  569. if(subLimiters[0].getType() == JsonNode::JsonType::DATA_STRING)
  570. {
  571. const std::string & aggregator = subLimiters[0].String();
  572. if(aggregator == AllOfLimiter::aggregator)
  573. result = std::make_shared<AllOfLimiter>();
  574. else if(aggregator == AnyOfLimiter::aggregator)
  575. result = std::make_shared<AnyOfLimiter>();
  576. else if(aggregator == NoneOfLimiter::aggregator)
  577. result = std::make_shared<NoneOfLimiter>();
  578. }
  579. if(!result)
  580. {
  581. // collapse for single limiter without explicit aggregate operator
  582. if(subLimiters.size() == 1)
  583. return parseLimiter(subLimiters[0]);
  584. // implicit aggregator must be allOf
  585. result = std::make_shared<AllOfLimiter>();
  586. offset = 0;
  587. }
  588. if(subLimiters.size() == offset)
  589. logMod->warn("Warning: empty sub-limiter list");
  590. for(int sl = offset; sl < subLimiters.size(); ++sl)
  591. result->add(parseLimiter(subLimiters[sl]));
  592. return result;
  593. }
  594. break;
  595. case JsonNode::JsonType::DATA_STRING: //pre-defined limiters
  596. return parseByMap(bonusLimiterMap, &limiter, "limiter type ");
  597. break;
  598. case JsonNode::JsonType::DATA_STRUCT: //customizable limiters
  599. {
  600. std::string limiterType = limiter["type"].String();
  601. const JsonVector & parameters = limiter["parameters"].Vector();
  602. if(limiterType == "CREATURE_TYPE_LIMITER")
  603. {
  604. std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::make_shared<CCreatureTypeLimiter>();
  605. VLC->modh->identifiers.requestIdentifier("creature", parameters[0], [=](si32 creature)
  606. {
  607. creatureLimiter->setCreature(CreatureID(creature));
  608. });
  609. auto includeUpgrades = false;
  610. if(parameters.size() > 1)
  611. {
  612. bool success = true;
  613. includeUpgrades = parameters[1].TryBoolFromString(success);
  614. if(!success)
  615. logMod->error("Second parameter of '%s' limiter should be Bool", limiterType);
  616. }
  617. creatureLimiter->includeUpgrades = includeUpgrades;
  618. return creatureLimiter;
  619. }
  620. else if(limiterType == "HAS_ANOTHER_BONUS_LIMITER")
  621. {
  622. std::string anotherBonusType = parameters[0].String();
  623. auto it = bonusNameMap.find(anotherBonusType);
  624. if(it == bonusNameMap.end())
  625. {
  626. logMod->error("Error: invalid ability type %s.", anotherBonusType);
  627. }
  628. else
  629. {
  630. std::shared_ptr<HasAnotherBonusLimiter> bonusLimiter = std::make_shared<HasAnotherBonusLimiter>();
  631. bonusLimiter->type = it->second;
  632. auto findSource = [&](const JsonNode & parameter)
  633. {
  634. if(parameter.getType() == JsonNode::JsonType::DATA_STRUCT)
  635. {
  636. auto sourceIt = bonusSourceMap.find(parameter["type"].String());
  637. if(sourceIt != bonusSourceMap.end())
  638. {
  639. bonusLimiter->source = sourceIt->second;
  640. bonusLimiter->isSourceRelevant = true;
  641. if(!parameter["id"].isNull()) {
  642. resolveIdentifier(parameter["id"], bonusLimiter->sid);
  643. bonusLimiter->isSourceIDRelevant = true;
  644. }
  645. }
  646. }
  647. return false;
  648. };
  649. if(parameters.size() > 1)
  650. {
  651. if(findSource(parameters[1]) && parameters.size() == 2)
  652. return bonusLimiter;
  653. else
  654. {
  655. resolveIdentifier(parameters[1], bonusLimiter->subtype);
  656. bonusLimiter->isSubtypeRelevant = true;
  657. if(parameters.size() > 2)
  658. findSource(parameters[2]);
  659. }
  660. }
  661. return bonusLimiter;
  662. }
  663. }
  664. else if(limiterType == "CREATURE_ALIGNMENT_LIMITER")
  665. {
  666. int alignment = vstd::find_pos(EAlignment::names, parameters[0].String());
  667. if(alignment == -1)
  668. logMod->error("Error: invalid alignment %s.", parameters[0].String());
  669. else
  670. return std::make_shared<CreatureAlignmentLimiter>(alignment);
  671. }
  672. else if(limiterType == "CREATURE_FACTION_LIMITER")
  673. {
  674. std::shared_ptr<CreatureFactionLimiter> factionLimiter = std::make_shared<CreatureFactionLimiter>();
  675. VLC->modh->identifiers.requestIdentifier("faction", parameters[0], [=](si32 faction)
  676. {
  677. factionLimiter->faction = faction;
  678. });
  679. return factionLimiter;
  680. }
  681. else if(limiterType == "CREATURE_TERRAIN_LIMITER")
  682. {
  683. std::shared_ptr<CreatureTerrainLimiter> terrainLimiter = std::make_shared<CreatureTerrainLimiter>();
  684. if(parameters.size())
  685. {
  686. VLC->modh->identifiers.requestIdentifier("terrain", parameters[0], [=](si32 terrain)
  687. {
  688. //TODO: support limiters
  689. //terrainLimiter->terrainType = terrain;
  690. });
  691. }
  692. return terrainLimiter;
  693. }
  694. else
  695. {
  696. logMod->error("Error: invalid customizable limiter type %s.", limiterType);
  697. }
  698. }
  699. break;
  700. default:
  701. break;
  702. }
  703. return nullptr;
  704. }
  705. std::shared_ptr<Bonus> JsonUtils::parseBonus(const JsonNode &ability)
  706. {
  707. auto b = std::make_shared<Bonus>();
  708. if (!parseBonus(ability, b.get()))
  709. {
  710. return nullptr;
  711. }
  712. return b;
  713. }
  714. std::shared_ptr<Bonus> JsonUtils::parseBuildingBonus(const JsonNode &ability, BuildingID building, std::string description)
  715. {
  716. /* duration = Bonus::PERMANENT
  717. source = Bonus::TOWN_STRUCTURE
  718. bonusType, val, subtype - get from json
  719. */
  720. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::NONE, Bonus::TOWN_STRUCTURE, 0, building, description, -1);
  721. if(!parseBonus(ability, b.get()))
  722. return nullptr;
  723. return b;
  724. }
  725. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  726. {
  727. const JsonNode *value;
  728. std::string type = ability["type"].String();
  729. auto it = bonusNameMap.find(type);
  730. if (it == bonusNameMap.end())
  731. {
  732. logMod->error("Error: invalid ability type %s.", type);
  733. return false;
  734. }
  735. b->type = it->second;
  736. resolveIdentifier(b->subtype, ability, "subtype");
  737. b->val = static_cast<si32>(ability["val"].Float());
  738. value = &ability["valueType"];
  739. if (!value->isNull())
  740. b->valType = static_cast<Bonus::ValueType>(parseByMapN(bonusValueMap, value, "value type "));
  741. b->stacking = ability["stacking"].String();
  742. resolveAddInfo(b->additionalInfo, ability);
  743. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  744. b->sid = static_cast<si32>(ability["sourceID"].Float());
  745. if(!ability["description"].isNull())
  746. {
  747. if (ability["description"].isString())
  748. b->description = ability["description"].String();
  749. if (ability["description"].isNumber())
  750. b->description = VLC->generaltexth->translate("core.arraytxt", ability["description"].Integer());
  751. }
  752. value = &ability["effectRange"];
  753. if (!value->isNull())
  754. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  755. value = &ability["duration"];
  756. if (!value->isNull())
  757. {
  758. switch (value->getType())
  759. {
  760. case JsonNode::JsonType::DATA_STRING:
  761. b->duration = (Bonus::BonusDuration)parseByMap(bonusDurationMap, value, "duration type ");
  762. break;
  763. case JsonNode::JsonType::DATA_VECTOR:
  764. {
  765. ui16 dur = 0;
  766. for (const JsonNode & d : value->Vector())
  767. {
  768. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  769. }
  770. b->duration = (Bonus::BonusDuration)dur;
  771. }
  772. break;
  773. default:
  774. logMod->error("Error! Wrong bonus duration format.");
  775. }
  776. }
  777. value = &ability["sourceType"];
  778. if (!value->isNull())
  779. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  780. value = &ability["targetSourceType"];
  781. if (!value->isNull())
  782. b->targetSourceType = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  783. value = &ability["limiters"];
  784. if (!value->isNull())
  785. b->limiter = parseLimiter(*value);
  786. value = &ability["propagator"];
  787. if (!value->isNull())
  788. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  789. value = &ability["updater"];
  790. if(!value->isNull())
  791. {
  792. const JsonNode & updaterJson = *value;
  793. switch(updaterJson.getType())
  794. {
  795. case JsonNode::JsonType::DATA_STRING:
  796. b->addUpdater(parseByMap(bonusUpdaterMap, &updaterJson, "updater type "));
  797. break;
  798. case JsonNode::JsonType::DATA_STRUCT:
  799. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  800. {
  801. std::shared_ptr<GrowsWithLevelUpdater> updater = std::make_shared<GrowsWithLevelUpdater>();
  802. const JsonVector param = updaterJson["parameters"].Vector();
  803. updater->valPer20 = static_cast<int>(param[0].Integer());
  804. if(param.size() > 1)
  805. updater->stepSize = static_cast<int>(param[1].Integer());
  806. b->addUpdater(updater);
  807. }
  808. else
  809. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  810. break;
  811. }
  812. }
  813. b->updateOppositeBonuses();
  814. return true;
  815. }
  816. //returns first Key with value equal to given one
  817. template<class Key, class Val>
  818. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  819. {
  820. for(auto it : map)
  821. {
  822. if(it.second == val)
  823. {
  824. return it.first;
  825. }
  826. }
  827. assert(0);
  828. return "";
  829. }
  830. void minimizeNode(JsonNode & node, const JsonNode & schema)
  831. {
  832. if (schema["type"].String() == "object")
  833. {
  834. std::set<std::string> foundEntries;
  835. for(auto & entry : schema["required"].Vector())
  836. {
  837. std::string name = entry.String();
  838. foundEntries.insert(name);
  839. minimizeNode(node[name], schema["properties"][name]);
  840. if (vstd::contains(node.Struct(), name) &&
  841. node[name] == schema["properties"][name]["default"])
  842. {
  843. node.Struct().erase(name);
  844. }
  845. }
  846. // erase all unhandled entries
  847. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  848. {
  849. if (!vstd::contains(foundEntries, it->first))
  850. it = node.Struct().erase(it);
  851. else
  852. it++;
  853. }
  854. }
  855. }
  856. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  857. {
  858. minimizeNode(node, getSchema(schemaName));
  859. }
  860. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  861. void maximizeNode(JsonNode & node, const JsonNode & schema)
  862. {
  863. // "required" entry can only be found in object/struct
  864. if (schema["type"].String() == "object")
  865. {
  866. std::set<std::string> foundEntries;
  867. // check all required entries that have default version
  868. for(auto & entry : schema["required"].Vector())
  869. {
  870. std::string name = entry.String();
  871. foundEntries.insert(name);
  872. if (node[name].isNull() &&
  873. !schema["properties"][name]["default"].isNull())
  874. {
  875. node[name] = schema["properties"][name]["default"];
  876. }
  877. maximizeNode(node[name], schema["properties"][name]);
  878. }
  879. // erase all unhandled entries
  880. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  881. {
  882. if (!vstd::contains(foundEntries, it->first))
  883. it = node.Struct().erase(it);
  884. else
  885. it++;
  886. }
  887. }
  888. }
  889. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  890. {
  891. maximizeNode(node, getSchema(schemaName));
  892. }
  893. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  894. {
  895. std::string log = Validation::check(schemaName, node);
  896. if (!log.empty())
  897. {
  898. logMod->warn("Data in %s is invalid!", dataName);
  899. logMod->warn(log);
  900. logMod->trace("%s json: %s", dataName, node.toJson(true));
  901. }
  902. return log.empty();
  903. }
  904. const JsonNode & getSchemaByName(std::string name)
  905. {
  906. // cached schemas to avoid loading json data multiple times
  907. static std::map<std::string, JsonNode> loadedSchemas;
  908. if (vstd::contains(loadedSchemas, name))
  909. return loadedSchemas[name];
  910. std::string filename = "config/schemas/" + name;
  911. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  912. {
  913. loadedSchemas[name] = JsonNode(ResourceID(filename));
  914. return loadedSchemas[name];
  915. }
  916. logMod->error("Error: missing schema with name %s!", name);
  917. assert(0);
  918. return nullNode;
  919. }
  920. const JsonNode & JsonUtils::getSchema(std::string URI)
  921. {
  922. size_t posColon = URI.find(':');
  923. size_t posHash = URI.find('#');
  924. std::string filename;
  925. if(posColon == std::string::npos)
  926. {
  927. filename = URI.substr(0, posHash);
  928. }
  929. else
  930. {
  931. std::string protocolName = URI.substr(0, posColon);
  932. filename = URI.substr(posColon + 1, posHash - posColon - 1) + ".json";
  933. if(protocolName != "vcmi")
  934. {
  935. logMod->error("Error: unsupported URI protocol for schema: %s", URI);
  936. return nullNode;
  937. }
  938. }
  939. // check if json pointer if present (section after hash in string)
  940. if(posHash == std::string::npos || posHash == URI.size() - 1)
  941. return getSchemaByName(filename);
  942. else
  943. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  944. }
  945. void JsonUtils::merge(JsonNode & dest, JsonNode & source, bool ignoreOverride, bool copyMeta)
  946. {
  947. if (dest.getType() == JsonNode::JsonType::DATA_NULL)
  948. {
  949. std::swap(dest, source);
  950. return;
  951. }
  952. switch (source.getType())
  953. {
  954. case JsonNode::JsonType::DATA_NULL:
  955. {
  956. dest.clear();
  957. break;
  958. }
  959. case JsonNode::JsonType::DATA_BOOL:
  960. case JsonNode::JsonType::DATA_FLOAT:
  961. case JsonNode::JsonType::DATA_INTEGER:
  962. case JsonNode::JsonType::DATA_STRING:
  963. case JsonNode::JsonType::DATA_VECTOR:
  964. {
  965. std::swap(dest, source);
  966. break;
  967. }
  968. case JsonNode::JsonType::DATA_STRUCT:
  969. {
  970. if(!ignoreOverride && vstd::contains(source.flags, "override"))
  971. {
  972. std::swap(dest, source);
  973. }
  974. else
  975. {
  976. if (copyMeta)
  977. dest.meta = source.meta;
  978. //recursively merge all entries from struct
  979. for(auto & node : source.Struct())
  980. merge(dest[node.first], node.second, ignoreOverride);
  981. }
  982. }
  983. }
  984. }
  985. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride, bool copyMeta)
  986. {
  987. // uses copy created in stack to safely merge two nodes
  988. merge(dest, source, ignoreOverride, copyMeta);
  989. }
  990. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  991. {
  992. JsonNode inheritedNode(base);
  993. merge(inheritedNode, descendant, true, true);
  994. descendant.swap(inheritedNode);
  995. }
  996. JsonNode JsonUtils::intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty)
  997. {
  998. if(nodes.size() == 0)
  999. return nullNode;
  1000. JsonNode result = nodes[0];
  1001. for(int i = 1; i < nodes.size(); i++)
  1002. {
  1003. if(result.isNull())
  1004. break;
  1005. result = JsonUtils::intersect(result, nodes[i], pruneEmpty);
  1006. }
  1007. return result;
  1008. }
  1009. JsonNode JsonUtils::intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty)
  1010. {
  1011. if(a.getType() == JsonNode::JsonType::DATA_STRUCT && b.getType() == JsonNode::JsonType::DATA_STRUCT)
  1012. {
  1013. // intersect individual properties
  1014. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  1015. for(auto property : a.Struct())
  1016. {
  1017. if(vstd::contains(b.Struct(), property.first))
  1018. {
  1019. JsonNode propertyIntersect = JsonUtils::intersect(property.second, b.Struct().find(property.first)->second);
  1020. if(pruneEmpty && !propertyIntersect.containsBaseData())
  1021. continue;
  1022. result[property.first] = propertyIntersect;
  1023. }
  1024. }
  1025. return result;
  1026. }
  1027. else
  1028. {
  1029. // not a struct - same or different, no middle ground
  1030. if(a == b)
  1031. return a;
  1032. }
  1033. return nullNode;
  1034. }
  1035. JsonNode JsonUtils::difference(const JsonNode & node, const JsonNode & base)
  1036. {
  1037. auto addsInfo = [](JsonNode diff) -> bool
  1038. {
  1039. switch(diff.getType())
  1040. {
  1041. case JsonNode::JsonType::DATA_NULL:
  1042. return false;
  1043. case JsonNode::JsonType::DATA_STRUCT:
  1044. return diff.Struct().size() > 0;
  1045. default:
  1046. return true;
  1047. }
  1048. };
  1049. if(node.getType() == JsonNode::JsonType::DATA_STRUCT && base.getType() == JsonNode::JsonType::DATA_STRUCT)
  1050. {
  1051. // subtract individual properties
  1052. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  1053. for(auto property : node.Struct())
  1054. {
  1055. if(vstd::contains(base.Struct(), property.first))
  1056. {
  1057. const JsonNode propertyDifference = JsonUtils::difference(property.second, base.Struct().find(property.first)->second);
  1058. if(addsInfo(propertyDifference))
  1059. result[property.first] = propertyDifference;
  1060. }
  1061. else
  1062. {
  1063. result[property.first] = property.second;
  1064. }
  1065. }
  1066. return result;
  1067. }
  1068. else
  1069. {
  1070. if(node == base)
  1071. return nullNode;
  1072. }
  1073. return node;
  1074. }
  1075. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1076. {
  1077. bool isValid;
  1078. return assembleFromFiles(files, isValid);
  1079. }
  1080. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  1081. {
  1082. isValid = true;
  1083. JsonNode result;
  1084. for(std::string file : files)
  1085. {
  1086. bool isValidFile;
  1087. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  1088. merge(result, section);
  1089. isValid |= isValidFile;
  1090. }
  1091. return result;
  1092. }
  1093. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  1094. {
  1095. JsonNode result;
  1096. ResourceID resID(filename, EResType::TEXT);
  1097. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  1098. {
  1099. // FIXME: some way to make this code more readable
  1100. auto stream = loader->load(resID);
  1101. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1102. stream->read(textData.get(), stream->getSize());
  1103. JsonNode section((char*)textData.get(), stream->getSize());
  1104. merge(result, section);
  1105. }
  1106. return result;
  1107. }
  1108. DLL_LINKAGE JsonNode JsonUtils::boolNode(bool value)
  1109. {
  1110. JsonNode node;
  1111. node.Bool() = value;
  1112. return node;
  1113. }
  1114. DLL_LINKAGE JsonNode JsonUtils::floatNode(double value)
  1115. {
  1116. JsonNode node;
  1117. node.Float() = value;
  1118. return node;
  1119. }
  1120. DLL_LINKAGE JsonNode JsonUtils::stringNode(std::string value)
  1121. {
  1122. JsonNode node;
  1123. node.String() = value;
  1124. return node;
  1125. }
  1126. DLL_LINKAGE JsonNode JsonUtils::intNode(si64 value)
  1127. {
  1128. JsonNode node;
  1129. node.Integer() = value;
  1130. return node;
  1131. }
  1132. VCMI_LIB_NAMESPACE_END