JsonNode.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. static BonusParams convertDeprecatedBonus(const JsonNode &ability)
  726. {
  727. if(vstd::contains(deprecatedBonusSet, ability["type"].String()))
  728. {
  729. logMod->warn("There is deprecated bonus found:\n%s\nTrying to convert...", ability.toJson());
  730. auto params = BonusParams(ability["type"].String(),
  731. ability["subtype"].isString() ? ability["subtype"].String() : "",
  732. ability["subtype"].isNumber() ? ability["subtype"].Integer() : -1);
  733. if(params.isConverted)
  734. {
  735. if(!params.valRelevant) {
  736. params.val = static_cast<si32>(ability["val"].Float());
  737. params.valRelevant = true;
  738. if(params.type == Bonus::SPECIFIC_SPELL_POWER) //First Aid value should be substracted by 10
  739. params.val -= 10; //Base First Aid value
  740. }
  741. Bonus::ValueType valueType = Bonus::ADDITIVE_VALUE;
  742. if(!ability["valueType"].isNull())
  743. valueType = bonusValueMap.find(ability["valueType"].String())->second;
  744. if(ability["type"].String() == "SECONDARY_SKILL_PREMY" && valueType == Bonus::PERCENT_TO_BASE) //assume secondary skill special
  745. {
  746. params.valueType = Bonus::PERCENT_TO_TARGET_TYPE;
  747. params.targetType = Bonus::SECONDARY_SKILL;
  748. params.targetTypeRelevant = true;
  749. }
  750. if(!params.valueTypeRelevant) {
  751. params.valueType = valueType;
  752. params.valueTypeRelevant = true;
  753. }
  754. logMod->warn("Please, use this bonus:\n%s\nConverted sucessfully!", params.toJson().toJson());
  755. return params;
  756. }
  757. else
  758. logMod->error("Cannot convert bonus!\n%s", ability.toJson());
  759. }
  760. BonusParams ret;
  761. ret.isConverted = false;
  762. return ret;
  763. }
  764. bool JsonUtils::parseBonus(const JsonNode &ability, Bonus *b)
  765. {
  766. const JsonNode *value;
  767. std::string type = ability["type"].String();
  768. auto it = bonusNameMap.find(type);
  769. auto params = std::make_unique<BonusParams>(false);
  770. if (it == bonusNameMap.end())
  771. {
  772. params = std::make_unique<BonusParams>(convertDeprecatedBonus(ability));
  773. if(!params->isConverted)
  774. {
  775. logMod->error("Error: invalid ability type %s.", type);
  776. return false;
  777. }
  778. b->type = params->type;
  779. b->val = params->val;
  780. b->valType = params->valueType;
  781. if(params->targetTypeRelevant)
  782. b->targetSourceType = params->targetType;
  783. }
  784. else
  785. b->type = it->second;
  786. resolveIdentifier(b->subtype, params->isConverted ? params->toJson() : ability, "subtype");
  787. if(!params->isConverted)
  788. {
  789. b->val = static_cast<si32>(ability["val"].Float());
  790. value = &ability["valueType"];
  791. if (!value->isNull())
  792. b->valType = static_cast<Bonus::ValueType>(parseByMapN(bonusValueMap, value, "value type "));
  793. }
  794. b->stacking = ability["stacking"].String();
  795. resolveAddInfo(b->additionalInfo, ability);
  796. b->turnsRemain = static_cast<si32>(ability["turns"].Float());
  797. b->sid = static_cast<si32>(ability["sourceID"].Float());
  798. if(!ability["description"].isNull())
  799. {
  800. if (ability["description"].isString())
  801. b->description = ability["description"].String();
  802. if (ability["description"].isNumber())
  803. b->description = VLC->generaltexth->translate("core.arraytxt", ability["description"].Integer());
  804. }
  805. value = &ability["effectRange"];
  806. if (!value->isNull())
  807. b->effectRange = static_cast<Bonus::LimitEffect>(parseByMapN(bonusLimitEffect, value, "effect range "));
  808. value = &ability["duration"];
  809. if (!value->isNull())
  810. {
  811. switch (value->getType())
  812. {
  813. case JsonNode::JsonType::DATA_STRING:
  814. b->duration = (Bonus::BonusDuration)parseByMap(bonusDurationMap, value, "duration type ");
  815. break;
  816. case JsonNode::JsonType::DATA_VECTOR:
  817. {
  818. ui16 dur = 0;
  819. for (const JsonNode & d : value->Vector())
  820. {
  821. dur |= parseByMapN(bonusDurationMap, &d, "duration type ");
  822. }
  823. b->duration = (Bonus::BonusDuration)dur;
  824. }
  825. break;
  826. default:
  827. logMod->error("Error! Wrong bonus duration format.");
  828. }
  829. }
  830. value = &ability["sourceType"];
  831. if (!value->isNull())
  832. b->source = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "source type "));
  833. value = &ability["targetSourceType"];
  834. if (!value->isNull())
  835. b->targetSourceType = static_cast<Bonus::BonusSource>(parseByMap(bonusSourceMap, value, "target type "));
  836. value = &ability["limiters"];
  837. if (!value->isNull())
  838. b->limiter = parseLimiter(*value);
  839. value = &ability["propagator"];
  840. if (!value->isNull())
  841. b->propagator = parseByMap(bonusPropagatorMap, value, "propagator type ");
  842. value = &ability["updater"];
  843. if(!value->isNull())
  844. {
  845. const JsonNode & updaterJson = *value;
  846. switch(updaterJson.getType())
  847. {
  848. case JsonNode::JsonType::DATA_STRING:
  849. b->addUpdater(parseByMap(bonusUpdaterMap, &updaterJson, "updater type "));
  850. break;
  851. case JsonNode::JsonType::DATA_STRUCT:
  852. if(updaterJson["type"].String() == "GROWS_WITH_LEVEL")
  853. {
  854. std::shared_ptr<GrowsWithLevelUpdater> updater = std::make_shared<GrowsWithLevelUpdater>();
  855. const JsonVector param = updaterJson["parameters"].Vector();
  856. updater->valPer20 = static_cast<int>(param[0].Integer());
  857. if(param.size() > 1)
  858. updater->stepSize = static_cast<int>(param[1].Integer());
  859. b->addUpdater(updater);
  860. }
  861. else
  862. logMod->warn("Unknown updater type \"%s\"", updaterJson["type"].String());
  863. break;
  864. }
  865. }
  866. b->updateOppositeBonuses();
  867. return true;
  868. }
  869. //returns first Key with value equal to given one
  870. template<class Key, class Val>
  871. Key reverseMapFirst(const Val & val, const std::map<Key, Val> & map)
  872. {
  873. for(auto it : map)
  874. {
  875. if(it.second == val)
  876. {
  877. return it.first;
  878. }
  879. }
  880. assert(0);
  881. return "";
  882. }
  883. void minimizeNode(JsonNode & node, const JsonNode & schema)
  884. {
  885. if (schema["type"].String() == "object")
  886. {
  887. std::set<std::string> foundEntries;
  888. for(auto & entry : schema["required"].Vector())
  889. {
  890. std::string name = entry.String();
  891. foundEntries.insert(name);
  892. minimizeNode(node[name], schema["properties"][name]);
  893. if (vstd::contains(node.Struct(), name) &&
  894. node[name] == schema["properties"][name]["default"])
  895. {
  896. node.Struct().erase(name);
  897. }
  898. }
  899. // erase all unhandled entries
  900. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  901. {
  902. if (!vstd::contains(foundEntries, it->first))
  903. it = node.Struct().erase(it);
  904. else
  905. it++;
  906. }
  907. }
  908. }
  909. void JsonUtils::minimize(JsonNode & node, std::string schemaName)
  910. {
  911. minimizeNode(node, getSchema(schemaName));
  912. }
  913. // FIXME: except for several lines function is identical to minimizeNode. Some way to reduce duplication?
  914. void maximizeNode(JsonNode & node, const JsonNode & schema)
  915. {
  916. // "required" entry can only be found in object/struct
  917. if (schema["type"].String() == "object")
  918. {
  919. std::set<std::string> foundEntries;
  920. // check all required entries that have default version
  921. for(auto & entry : schema["required"].Vector())
  922. {
  923. std::string name = entry.String();
  924. foundEntries.insert(name);
  925. if (node[name].isNull() &&
  926. !schema["properties"][name]["default"].isNull())
  927. {
  928. node[name] = schema["properties"][name]["default"];
  929. }
  930. maximizeNode(node[name], schema["properties"][name]);
  931. }
  932. // erase all unhandled entries
  933. for (auto it = node.Struct().begin(); it != node.Struct().end();)
  934. {
  935. if (!vstd::contains(foundEntries, it->first))
  936. it = node.Struct().erase(it);
  937. else
  938. it++;
  939. }
  940. }
  941. }
  942. void JsonUtils::maximize(JsonNode & node, std::string schemaName)
  943. {
  944. maximizeNode(node, getSchema(schemaName));
  945. }
  946. bool JsonUtils::validate(const JsonNode &node, std::string schemaName, std::string dataName)
  947. {
  948. std::string log = Validation::check(schemaName, node);
  949. if (!log.empty())
  950. {
  951. logMod->warn("Data in %s is invalid!", dataName);
  952. logMod->warn(log);
  953. logMod->trace("%s json: %s", dataName, node.toJson(true));
  954. }
  955. return log.empty();
  956. }
  957. const JsonNode & getSchemaByName(std::string name)
  958. {
  959. // cached schemas to avoid loading json data multiple times
  960. static std::map<std::string, JsonNode> loadedSchemas;
  961. if (vstd::contains(loadedSchemas, name))
  962. return loadedSchemas[name];
  963. std::string filename = "config/schemas/" + name;
  964. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  965. {
  966. loadedSchemas[name] = JsonNode(ResourceID(filename));
  967. return loadedSchemas[name];
  968. }
  969. logMod->error("Error: missing schema with name %s!", name);
  970. assert(0);
  971. return nullNode;
  972. }
  973. const JsonNode & JsonUtils::getSchema(std::string URI)
  974. {
  975. size_t posColon = URI.find(':');
  976. size_t posHash = URI.find('#');
  977. std::string filename;
  978. if(posColon == std::string::npos)
  979. {
  980. filename = URI.substr(0, posHash);
  981. }
  982. else
  983. {
  984. std::string protocolName = URI.substr(0, posColon);
  985. filename = URI.substr(posColon + 1, posHash - posColon - 1) + ".json";
  986. if(protocolName != "vcmi")
  987. {
  988. logMod->error("Error: unsupported URI protocol for schema: %s", URI);
  989. return nullNode;
  990. }
  991. }
  992. // check if json pointer if present (section after hash in string)
  993. if(posHash == std::string::npos || posHash == URI.size() - 1)
  994. return getSchemaByName(filename);
  995. else
  996. return getSchemaByName(filename).resolvePointer(URI.substr(posHash + 1));
  997. }
  998. void JsonUtils::merge(JsonNode & dest, JsonNode & source, bool ignoreOverride, bool copyMeta)
  999. {
  1000. if (dest.getType() == JsonNode::JsonType::DATA_NULL)
  1001. {
  1002. std::swap(dest, source);
  1003. return;
  1004. }
  1005. switch (source.getType())
  1006. {
  1007. case JsonNode::JsonType::DATA_NULL:
  1008. {
  1009. dest.clear();
  1010. break;
  1011. }
  1012. case JsonNode::JsonType::DATA_BOOL:
  1013. case JsonNode::JsonType::DATA_FLOAT:
  1014. case JsonNode::JsonType::DATA_INTEGER:
  1015. case JsonNode::JsonType::DATA_STRING:
  1016. case JsonNode::JsonType::DATA_VECTOR:
  1017. {
  1018. std::swap(dest, source);
  1019. break;
  1020. }
  1021. case JsonNode::JsonType::DATA_STRUCT:
  1022. {
  1023. if(!ignoreOverride && vstd::contains(source.flags, "override"))
  1024. {
  1025. std::swap(dest, source);
  1026. }
  1027. else
  1028. {
  1029. if (copyMeta)
  1030. dest.meta = source.meta;
  1031. //recursively merge all entries from struct
  1032. for(auto & node : source.Struct())
  1033. merge(dest[node.first], node.second, ignoreOverride);
  1034. }
  1035. }
  1036. }
  1037. }
  1038. void JsonUtils::mergeCopy(JsonNode & dest, JsonNode source, bool ignoreOverride, bool copyMeta)
  1039. {
  1040. // uses copy created in stack to safely merge two nodes
  1041. merge(dest, source, ignoreOverride, copyMeta);
  1042. }
  1043. void JsonUtils::inherit(JsonNode & descendant, const JsonNode & base)
  1044. {
  1045. JsonNode inheritedNode(base);
  1046. merge(inheritedNode, descendant, true, true);
  1047. descendant.swap(inheritedNode);
  1048. }
  1049. JsonNode JsonUtils::intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty)
  1050. {
  1051. if(nodes.size() == 0)
  1052. return nullNode;
  1053. JsonNode result = nodes[0];
  1054. for(int i = 1; i < nodes.size(); i++)
  1055. {
  1056. if(result.isNull())
  1057. break;
  1058. result = JsonUtils::intersect(result, nodes[i], pruneEmpty);
  1059. }
  1060. return result;
  1061. }
  1062. JsonNode JsonUtils::intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty)
  1063. {
  1064. if(a.getType() == JsonNode::JsonType::DATA_STRUCT && b.getType() == JsonNode::JsonType::DATA_STRUCT)
  1065. {
  1066. // intersect individual properties
  1067. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  1068. for(auto property : a.Struct())
  1069. {
  1070. if(vstd::contains(b.Struct(), property.first))
  1071. {
  1072. JsonNode propertyIntersect = JsonUtils::intersect(property.second, b.Struct().find(property.first)->second);
  1073. if(pruneEmpty && !propertyIntersect.containsBaseData())
  1074. continue;
  1075. result[property.first] = propertyIntersect;
  1076. }
  1077. }
  1078. return result;
  1079. }
  1080. else
  1081. {
  1082. // not a struct - same or different, no middle ground
  1083. if(a == b)
  1084. return a;
  1085. }
  1086. return nullNode;
  1087. }
  1088. JsonNode JsonUtils::difference(const JsonNode & node, const JsonNode & base)
  1089. {
  1090. auto addsInfo = [](JsonNode diff) -> bool
  1091. {
  1092. switch(diff.getType())
  1093. {
  1094. case JsonNode::JsonType::DATA_NULL:
  1095. return false;
  1096. case JsonNode::JsonType::DATA_STRUCT:
  1097. return diff.Struct().size() > 0;
  1098. default:
  1099. return true;
  1100. }
  1101. };
  1102. if(node.getType() == JsonNode::JsonType::DATA_STRUCT && base.getType() == JsonNode::JsonType::DATA_STRUCT)
  1103. {
  1104. // subtract individual properties
  1105. JsonNode result(JsonNode::JsonType::DATA_STRUCT);
  1106. for(auto property : node.Struct())
  1107. {
  1108. if(vstd::contains(base.Struct(), property.first))
  1109. {
  1110. const JsonNode propertyDifference = JsonUtils::difference(property.second, base.Struct().find(property.first)->second);
  1111. if(addsInfo(propertyDifference))
  1112. result[property.first] = propertyDifference;
  1113. }
  1114. else
  1115. {
  1116. result[property.first] = property.second;
  1117. }
  1118. }
  1119. return result;
  1120. }
  1121. else
  1122. {
  1123. if(node == base)
  1124. return nullNode;
  1125. }
  1126. return node;
  1127. }
  1128. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files)
  1129. {
  1130. bool isValid;
  1131. return assembleFromFiles(files, isValid);
  1132. }
  1133. JsonNode JsonUtils::assembleFromFiles(std::vector<std::string> files, bool &isValid)
  1134. {
  1135. isValid = true;
  1136. JsonNode result;
  1137. for(std::string file : files)
  1138. {
  1139. bool isValidFile;
  1140. JsonNode section(ResourceID(file, EResType::TEXT), isValidFile);
  1141. merge(result, section);
  1142. isValid |= isValidFile;
  1143. }
  1144. return result;
  1145. }
  1146. JsonNode JsonUtils::assembleFromFiles(std::string filename)
  1147. {
  1148. JsonNode result;
  1149. ResourceID resID(filename, EResType::TEXT);
  1150. for(auto & loader : CResourceHandler::get()->getResourcesWithName(resID))
  1151. {
  1152. // FIXME: some way to make this code more readable
  1153. auto stream = loader->load(resID);
  1154. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1155. stream->read(textData.get(), stream->getSize());
  1156. JsonNode section((char*)textData.get(), stream->getSize());
  1157. merge(result, section);
  1158. }
  1159. return result;
  1160. }
  1161. DLL_LINKAGE JsonNode JsonUtils::boolNode(bool value)
  1162. {
  1163. JsonNode node;
  1164. node.Bool() = value;
  1165. return node;
  1166. }
  1167. DLL_LINKAGE JsonNode JsonUtils::floatNode(double value)
  1168. {
  1169. JsonNode node;
  1170. node.Float() = value;
  1171. return node;
  1172. }
  1173. DLL_LINKAGE JsonNode JsonUtils::stringNode(std::string value)
  1174. {
  1175. JsonNode node;
  1176. node.String() = value;
  1177. return node;
  1178. }
  1179. DLL_LINKAGE JsonNode JsonUtils::intNode(si64 value)
  1180. {
  1181. JsonNode node;
  1182. node.Integer() = value;
  1183. return node;
  1184. }
  1185. VCMI_LIB_NAMESPACE_END