2
0

MapFormatJson.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. /*
  2. * MapFormatJson.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 "MapFormatJson.h"
  12. #include "../filesystem/CInputStream.h"
  13. #include "../filesystem/COutputStream.h"
  14. #include "../json/JsonWriter.h"
  15. #include "CMap.h"
  16. #include "MapFormat.h"
  17. #include "../GameLibrary.h"
  18. #include "../RiverHandler.h"
  19. #include "../RoadHandler.h"
  20. #include "../TerrainHandler.h"
  21. #include "../entities/artifact/CArtHandler.h"
  22. #include "../entities/faction/CTownHandler.h"
  23. #include "../entities/hero/CHeroHandler.h"
  24. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  26. #include "../mapObjects/ObjectTemplate.h"
  27. #include "../mapObjects/CGHeroInstance.h"
  28. #include "../mapObjects/CGTownInstance.h"
  29. #include "../mapObjects/MiscObjects.h"
  30. #include "../modding/ModScope.h"
  31. #include "../modding/ModUtility.h"
  32. #include "../spells/CSpellHandler.h"
  33. #include "../CSkillHandler.h"
  34. #include "../constants/StringConstants.h"
  35. #include "../serializer/JsonDeserializer.h"
  36. #include "../serializer/JsonSerializer.h"
  37. #include "../texts/Languages.h"
  38. VCMI_LIB_NAMESPACE_BEGIN
  39. class MapObjectResolver: public IInstanceResolver
  40. {
  41. public:
  42. MapObjectResolver(const CMapFormatJson * owner_);
  43. si32 decode (const std::string & identifier) const override;
  44. std::string encode(si32 identifier) const override;
  45. private:
  46. const CMapFormatJson * owner;
  47. };
  48. MapObjectResolver::MapObjectResolver(const CMapFormatJson * owner_):
  49. owner(owner_)
  50. {
  51. }
  52. si32 MapObjectResolver::decode(const std::string & identifier) const
  53. {
  54. //always decode as ObjectInstanceID
  55. auto it = owner->map->instanceNames.find(identifier);
  56. if(it != owner->map->instanceNames.end())
  57. {
  58. return (*it).second->id.getNum();
  59. }
  60. else
  61. {
  62. logGlobal->error("Object not found: %s", identifier);
  63. return -1;
  64. }
  65. }
  66. std::string MapObjectResolver::encode(si32 identifier) const
  67. {
  68. ObjectInstanceID id(identifier);
  69. auto object = owner->map->getObject(id);
  70. if(!object)
  71. {
  72. logGlobal->error("Cannot get object with id %d", id.getNum());
  73. return "";
  74. }
  75. return object->instanceName;
  76. }
  77. namespace HeaderDetail
  78. {
  79. static const std::vector<std::string> difficultyMap =
  80. {
  81. "EASY",
  82. "NORMAL",
  83. "HARD",
  84. "EXPERT",
  85. "IMPOSSIBLE"
  86. };
  87. enum class ECanPlay
  88. {
  89. NONE = 0,
  90. PLAYER_OR_AI = 1,
  91. PLAYER_ONLY = 2,
  92. AI_ONLY = 3
  93. };
  94. static const std::vector<std::string> canPlayMap =
  95. {
  96. "",
  97. "PlayerOrAI",
  98. "PlayerOnly",
  99. "AIOnly"
  100. };
  101. }
  102. namespace TriggeredEventsDetail
  103. {
  104. static const std::array conditionNames =
  105. {
  106. "haveArtifact", "haveCreatures", "haveResources", "haveBuilding",
  107. "control", "destroy", "transport", "daysPassed",
  108. "isHuman", "daysWithoutTown", "standardWin", "constValue"
  109. };
  110. static const std::array typeNames = { "victory", "defeat" };
  111. static EventCondition JsonToCondition(const JsonNode & node)
  112. {
  113. EventCondition event;
  114. const auto & conditionName = node.Vector()[0].String();
  115. auto pos = vstd::find_pos(conditionNames, conditionName);
  116. event.condition = static_cast<EventCondition::EWinLoseType>(pos);
  117. if (node.Vector().size() > 1)
  118. {
  119. const JsonNode & data = node.Vector()[1];
  120. event.objectInstanceName = data["object"].String();
  121. event.value = data["value"].Integer();
  122. switch (event.condition)
  123. {
  124. case EventCondition::HAVE_ARTIFACT:
  125. case EventCondition::TRANSPORT:
  126. if (data["type"].isNumber()) // compatibility
  127. event.objectType = ArtifactID(data["type"].Integer());
  128. else
  129. event.objectType = ArtifactID(ArtifactID::decode(data["type"].String()));
  130. break;
  131. case EventCondition::HAVE_CREATURES:
  132. if (data["type"].isNumber()) // compatibility
  133. event.objectType = CreatureID(data["type"].Integer());
  134. else
  135. event.objectType = CreatureID(CreatureID::decode(data["type"].String()));
  136. break;
  137. case EventCondition::HAVE_RESOURCES:
  138. if (data["type"].isNumber()) // compatibility
  139. event.objectType = GameResID(data["type"].Integer());
  140. else
  141. event.objectType = GameResID(GameResID::decode(data["type"].String()));
  142. break;
  143. case EventCondition::HAVE_BUILDING:
  144. if (data["type"].isNumber()) // compatibility
  145. event.objectType = BuildingID(data["type"].Integer());
  146. else
  147. event.objectType = BuildingID(BuildingID::decode(data["type"].String()));
  148. break;
  149. case EventCondition::CONTROL:
  150. case EventCondition::DESTROY:
  151. if (data["type"].isNumber()) // compatibility
  152. event.objectType = MapObjectID(data["type"].Integer());
  153. else
  154. event.objectType = MapObjectID(MapObjectID::decode(data["type"].String()));
  155. break;
  156. }
  157. if (!data["position"].isNull())
  158. {
  159. const auto & position = data["position"].Vector();
  160. event.position.x = static_cast<si32>(position.at(0).Float());
  161. event.position.y = static_cast<si32>(position.at(1).Float());
  162. event.position.z = static_cast<si32>(position.at(2).Float());
  163. }
  164. }
  165. return event;
  166. }
  167. static JsonNode ConditionToJson(const EventCondition & event)
  168. {
  169. JsonNode json;
  170. JsonVector & asVector = json.Vector();
  171. JsonNode condition;
  172. condition.String() = conditionNames.at(event.condition);
  173. asVector.push_back(condition);
  174. JsonNode data;
  175. if(!event.objectInstanceName.empty())
  176. data["object"].String() = event.objectInstanceName;
  177. data["type"].String() = event.objectType.toString();
  178. data["value"].Integer() = event.value;
  179. if(event.position != int3(-1, -1, -1))
  180. {
  181. auto & position = data["position"].Vector();
  182. position.resize(3);
  183. position[0].Float() = event.position.x;
  184. position[1].Float() = event.position.y;
  185. position[2].Float() = event.position.z;
  186. }
  187. if(!data.isNull())
  188. asVector.push_back(data);
  189. return json;
  190. }
  191. }//namespace TriggeredEventsDetail
  192. namespace TerrainDetail
  193. {
  194. static const std::array<char, 4> flipCodes =
  195. {
  196. '_', '-', '|', '+'
  197. };
  198. }
  199. ///CMapFormatJson
  200. const int CMapFormatJson::VERSION_MAJOR = 2;
  201. const int CMapFormatJson::VERSION_MINOR = 0;
  202. const std::string CMapFormatJson::HEADER_FILE_NAME = "header.json";
  203. const std::string CMapFormatJson::OBJECTS_FILE_NAME = "objects.json";
  204. std::string getTerrainFilename(int i)
  205. {
  206. if(i == 0)
  207. return "surface_terrain.json";
  208. else if(i == 1)
  209. return "underground_terrain.json";
  210. else
  211. return "level-" + std::to_string(i + 1) + "_terrain.json";
  212. }
  213. CMapFormatJson::CMapFormatJson():
  214. fileVersionMajor(0), fileVersionMinor(0),
  215. mapObjectResolver(std::make_unique<MapObjectResolver>(this)),
  216. map(nullptr), mapHeader(nullptr)
  217. {
  218. }
  219. TerrainId CMapFormatJson::getTerrainByCode(const std::string & code)
  220. {
  221. for(const auto & object : LIBRARY->terrainTypeHandler->objects)
  222. {
  223. if(object->shortIdentifier == code)
  224. return object->getId();
  225. }
  226. return TerrainId::NONE;
  227. }
  228. RiverId CMapFormatJson::getRiverByCode(const std::string & code)
  229. {
  230. for(const auto & object : LIBRARY->riverTypeHandler->objects)
  231. {
  232. if (object->shortIdentifier == code)
  233. return object->getId();
  234. }
  235. return RiverId::NO_RIVER;
  236. }
  237. RoadId CMapFormatJson::getRoadByCode(const std::string & code)
  238. {
  239. for(const auto & object : LIBRARY->roadTypeHandler->objects)
  240. {
  241. if (object->shortIdentifier == code)
  242. return object->getId();
  243. }
  244. return RoadId::NO_ROAD;
  245. }
  246. void CMapFormatJson::serializeAllowedFactions(JsonSerializeFormat & handler, std::set<FactionID> & value) const
  247. {
  248. std::set<FactionID> temp;
  249. if(handler.saving)
  250. {
  251. for(auto const factionID : LIBRARY->townh->getDefaultAllowed())
  252. if(vstd::contains(value, factionID))
  253. temp.insert(factionID);
  254. }
  255. handler.serializeLIC("allowedFactions", &FactionID::decode, &FactionID::encode, LIBRARY->townh->getDefaultAllowed(), temp);
  256. if(!handler.saving)
  257. value = temp;
  258. }
  259. void CMapFormatJson::serializeHeader(JsonSerializeFormat & handler)
  260. {
  261. handler.serializeStruct("name", mapHeader->name);
  262. handler.serializeStruct("description", mapHeader->description);
  263. handler.serializeStruct("author", mapHeader->author);
  264. handler.serializeStruct("authorContact", mapHeader->authorContact);
  265. handler.serializeStruct("mapVersion", mapHeader->mapVersion);
  266. handler.serializeInt("creationDateTime", mapHeader->creationDateTime, 0);
  267. handler.serializeInt("heroLevelLimit", mapHeader->levelLimit, 0);
  268. //todo: support arbitrary percentage
  269. handler.serializeEnum("difficulty", mapHeader->difficulty, HeaderDetail::difficultyMap);
  270. serializePlayerInfo(handler);
  271. handler.serializeLIC("allowedHeroes", &HeroTypeID::decode, &HeroTypeID::encode, LIBRARY->heroh->getDefaultAllowed(), mapHeader->allowedHeroes);
  272. handler.serializeStruct("victoryMessage", mapHeader->victoryMessage);
  273. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  274. handler.serializeStruct("defeatMessage", mapHeader->defeatMessage);
  275. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  276. handler.serializeIdArray("reservedCampaignHeroes", mapHeader->reservedCampaignHeroes);
  277. }
  278. void CMapFormatJson::serializePlayerInfo(JsonSerializeFormat & handler)
  279. {
  280. auto playersData = handler.enterStruct("players");
  281. for(int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  282. {
  283. PlayerInfo & info = mapHeader->players[player];
  284. if(handler.saving)
  285. {
  286. if(!info.canAnyonePlay())
  287. continue;
  288. }
  289. auto playerData = handler.enterStruct(GameConstants::PLAYER_COLOR_NAMES[player]);
  290. if(!handler.saving)
  291. {
  292. if(handler.getCurrent().isNull())
  293. {
  294. info.canComputerPlay = false;
  295. info.canHumanPlay = false;
  296. continue;
  297. }
  298. }
  299. serializeAllowedFactions(handler, info.allowedFactions);
  300. HeaderDetail::ECanPlay canPlay = HeaderDetail::ECanPlay::NONE;
  301. if(handler.saving)
  302. {
  303. if(info.canComputerPlay)
  304. {
  305. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_OR_AI : HeaderDetail::ECanPlay::AI_ONLY;
  306. }
  307. else
  308. {
  309. canPlay = info.canHumanPlay ? HeaderDetail::ECanPlay::PLAYER_ONLY : HeaderDetail::ECanPlay::NONE;
  310. }
  311. }
  312. handler.serializeEnum("canPlay", canPlay, HeaderDetail::canPlayMap);
  313. if(!handler.saving)
  314. {
  315. switch(canPlay)
  316. {
  317. case HeaderDetail::ECanPlay::PLAYER_OR_AI:
  318. info.canComputerPlay = true;
  319. info.canHumanPlay = true;
  320. break;
  321. case HeaderDetail::ECanPlay::PLAYER_ONLY:
  322. info.canComputerPlay = false;
  323. info.canHumanPlay = true;
  324. break;
  325. case HeaderDetail::ECanPlay::AI_ONLY:
  326. info.canComputerPlay = true;
  327. info.canHumanPlay = false;
  328. break;
  329. default:
  330. info.canComputerPlay = false;
  331. info.canHumanPlay = false;
  332. break;
  333. }
  334. }
  335. //saving whole structure only if position is valid
  336. if(!handler.saving || info.posOfMainTown.isValid())
  337. {
  338. auto mainTown = handler.enterStruct("mainTown");
  339. handler.serializeBool("generateHero", info.generateHeroAtMainTown);
  340. handler.serializeInt("x", info.posOfMainTown.x, -1);
  341. handler.serializeInt("y", info.posOfMainTown.y, -1);
  342. handler.serializeInt("l", info.posOfMainTown.z, -1);
  343. }
  344. if(!handler.saving)
  345. {
  346. info.hasMainTown = info.posOfMainTown.isValid();
  347. }
  348. handler.serializeString("mainHero", info.mainHeroInstance);//must be before "heroes"
  349. //heroes
  350. if(handler.saving)
  351. {
  352. //ignoring heroesNames and saving from actual map objects
  353. //TODO: optimize
  354. for(auto & hero : map->getObjects<CGHeroInstance>())
  355. {
  356. if((hero->getOwner()) == PlayerColor(player))
  357. {
  358. auto heroes = handler.enterStruct("heroes");
  359. if(hero)
  360. {
  361. auto heroData = handler.enterStruct(hero->instanceName);
  362. heroData->serializeString("name", hero->nameCustomTextId);
  363. if(hero->ID == Obj::HERO)
  364. {
  365. std::string temp;
  366. if(hero->getHeroTypeID().hasValue())
  367. temp = hero->getHeroType()->getJsonKey();
  368. handler.serializeString("type", temp);
  369. }
  370. }
  371. }
  372. }
  373. }
  374. else
  375. {
  376. info.heroesNames.clear();
  377. auto heroes = handler.enterStruct("heroes");
  378. for(const auto & hero : handler.getCurrent().Struct())
  379. {
  380. const JsonNode & data = hero.second;
  381. const std::string instanceName = hero.first;
  382. SHeroName hname;
  383. hname.heroId = HeroTypeID::NONE;
  384. std::string rawId = data["type"].String();
  385. if(!rawId.empty())
  386. hname.heroId = HeroTypeID(HeroTypeID::decode(rawId));
  387. hname.heroName = data["name"].String();
  388. if(instanceName == info.mainHeroInstance)
  389. {
  390. //this is main hero
  391. info.mainCustomHeroNameTextId = hname.heroName;
  392. info.hasRandomHero = (hname.heroId == HeroTypeID::NONE);
  393. info.mainCustomHeroId = hname.heroId;
  394. info.mainCustomHeroPortrait = HeroTypeID::NONE;
  395. //todo:mainHeroPortrait
  396. }
  397. info.heroesNames.push_back(hname);
  398. }
  399. }
  400. handler.serializeBool("randomFaction", info.isFactionRandom);
  401. }
  402. }
  403. void CMapFormatJson::readTeams(JsonDeserializer & handler)
  404. {
  405. auto teams = handler.enterArray("teams");
  406. const JsonNode & src = teams->getCurrent();
  407. if(src.getType() != JsonNode::JsonType::DATA_VECTOR)
  408. {
  409. // No alliances
  410. if(src.getType() != JsonNode::JsonType::DATA_NULL)
  411. logGlobal->error("Invalid teams field type");
  412. mapHeader->howManyTeams = 0;
  413. for(auto & player : mapHeader->players)
  414. if(player.canAnyonePlay())
  415. player.team = TeamID(mapHeader->howManyTeams++);
  416. }
  417. else
  418. {
  419. const JsonVector & srcVector = src.Vector();
  420. mapHeader->howManyTeams = static_cast<ui8>(srcVector.size());
  421. for(int team = 0; team < mapHeader->howManyTeams; team++)
  422. for(const JsonNode & playerData : srcVector[team].Vector())
  423. {
  424. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  425. if(player.isValidPlayer())
  426. if(mapHeader->players[player.getNum()].canAnyonePlay())
  427. mapHeader->players[player.getNum()].team = TeamID(team);
  428. }
  429. for(PlayerInfo & player : mapHeader->players)
  430. if(player.canAnyonePlay() && player.team == TeamID::NO_TEAM)
  431. player.team = TeamID(mapHeader->howManyTeams++);
  432. }
  433. }
  434. void CMapFormatJson::writeTeams(JsonSerializer & handler)
  435. {
  436. std::vector<std::set<PlayerColor>> teamsData;
  437. teamsData.resize(mapHeader->howManyTeams);
  438. //get raw data
  439. for(int idx = 0; idx < mapHeader->players.size(); idx++)
  440. {
  441. const PlayerInfo & player = mapHeader->players.at(idx);
  442. int team = player.team.getNum();
  443. if(vstd::iswithin(team, 0, mapHeader->howManyTeams-1) && player.canAnyonePlay())
  444. teamsData.at(team).insert(PlayerColor(idx));
  445. }
  446. //remove single-member teams
  447. vstd::erase_if(teamsData, [](std::set<PlayerColor> & elem) -> bool
  448. {
  449. return elem.size() <= 1;
  450. });
  451. if(!teamsData.empty())
  452. {
  453. JsonNode dest;
  454. //construct output
  455. dest.setType(JsonNode::JsonType::DATA_VECTOR);
  456. for(const std::set<PlayerColor> & teamData : teamsData)
  457. {
  458. JsonNode team;
  459. for(const PlayerColor & player : teamData)
  460. team.Vector().emplace_back(GameConstants::PLAYER_COLOR_NAMES[player.getNum()]);
  461. dest.Vector().push_back(std::move(team));
  462. }
  463. handler.serializeRaw("teams", dest, std::nullopt);
  464. }
  465. }
  466. void CMapFormatJson::readTriggeredEvents(JsonDeserializer & handler)
  467. {
  468. const JsonNode & input = handler.getCurrent();
  469. mapHeader->triggeredEvents.clear();
  470. for(const auto & entry : input["triggeredEvents"].Struct())
  471. {
  472. TriggeredEvent event;
  473. event.identifier = entry.first;
  474. readTriggeredEvent(event, entry.second);
  475. mapHeader->triggeredEvents.push_back(event);
  476. }
  477. }
  478. void CMapFormatJson::readTriggeredEvent(TriggeredEvent & event, const JsonNode & source) const
  479. {
  480. using namespace TriggeredEventsDetail;
  481. event.onFulfill.jsonDeserialize(source["message"]);
  482. event.description.jsonDeserialize(source["description"]);
  483. event.effect.type = vstd::find_pos(typeNames, source["effect"]["type"].String());
  484. event.effect.toOtherMessage.jsonDeserialize(source["effect"]["messageToSend"]);
  485. event.trigger = EventExpression(source["condition"], JsonToCondition); // logical expression
  486. }
  487. void CMapFormatJson::writeTriggeredEvents(JsonSerializer & handler)
  488. {
  489. JsonNode triggeredEvents;
  490. for(const auto & event : mapHeader->triggeredEvents)
  491. writeTriggeredEvent(event, triggeredEvents[event.identifier]);
  492. handler.serializeRaw("triggeredEvents", triggeredEvents, std::nullopt);
  493. }
  494. void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent & event, JsonNode & dest) const
  495. {
  496. using namespace TriggeredEventsDetail;
  497. if(!event.onFulfill.empty())
  498. event.onFulfill.jsonSerialize(dest["message"]);
  499. if(!event.description.empty())
  500. event.description.jsonSerialize(dest["description"]);
  501. dest["effect"]["type"].String() = typeNames.at(static_cast<size_t>(event.effect.type));
  502. if(!event.effect.toOtherMessage.empty())
  503. event.description.jsonSerialize(dest["effect"]["messageToSend"]);
  504. dest["condition"] = event.trigger.toJson(ConditionToJson);
  505. }
  506. void CMapFormatJson::readDisposedHeroes(JsonSerializeFormat & handler)
  507. {
  508. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  509. const JsonNode & data = handler.getCurrent();
  510. for(const auto & entry : data.Struct())
  511. {
  512. HeroTypeID type(HeroTypeID::decode(entry.first));
  513. std::set<PlayerColor> mask;
  514. for(const JsonNode & playerData : entry.second["availableFor"].Vector())
  515. {
  516. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  517. if(player.isValidPlayer())
  518. mask.insert(player);
  519. }
  520. if(!mask.empty() && mask.size() != PlayerColor::PLAYER_LIMIT_I && type.getNum() >= 0)
  521. {
  522. DisposedHero hero;
  523. hero.heroId = type;
  524. hero.players = mask;
  525. //name and portrait are not used
  526. mapHeader->disposedHeroes.push_back(hero);
  527. }
  528. }
  529. }
  530. void CMapFormatJson::writeDisposedHeroes(JsonSerializeFormat & handler)
  531. {
  532. if(mapHeader->disposedHeroes.empty())
  533. return;
  534. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  535. for(DisposedHero & hero : mapHeader->disposedHeroes)
  536. {
  537. std::string type = HeroTypeID::encode(hero.heroId.getNum());
  538. auto definition = definitions->enterStruct(type);
  539. JsonNode players;
  540. definition->serializeIdArray("availableFor", hero.players);
  541. }
  542. }
  543. void CMapFormatJson::serializeRumors(JsonSerializeFormat & handler)
  544. {
  545. auto rumors = handler.enterArray("rumors");
  546. rumors.serializeStruct(map->rumors);
  547. }
  548. void CMapFormatJson::serializeTimedEvents(JsonSerializeFormat & handler)
  549. {
  550. auto events = handler.enterArray("events");
  551. std::vector<CMapEvent> temp(map->events.begin(), map->events.end());
  552. events.serializeStruct(temp);
  553. map->events.assign(temp.begin(), temp.end());
  554. }
  555. void CMapFormatJson::serializePredefinedHeroes(JsonSerializeFormat & handler)
  556. {
  557. if(handler.saving)
  558. {
  559. auto heroPool = map->getHeroesInPool();
  560. if(!heroPool.empty())
  561. {
  562. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  563. for(auto & heroID : heroPool)
  564. {
  565. auto heroPtr = map->tryGetFromHeroPool(heroID);
  566. auto predefinedHero = handler.enterStruct(heroPtr->getHeroTypeName());
  567. heroPtr->serializeJsonDefinition(handler);
  568. }
  569. }
  570. }
  571. else
  572. {
  573. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  574. const JsonNode & data = handler.getCurrent();
  575. for(const auto & p : data.Struct())
  576. {
  577. auto predefinedHero = handler.enterStruct(p.first);
  578. auto hero = std::make_shared<CGHeroInstance>(map->cb);
  579. hero->ID = Obj::HERO;
  580. hero->setHeroTypeName(p.first);
  581. hero->serializeJsonDefinition(handler);
  582. map->addToHeroPool(hero);
  583. }
  584. }
  585. }
  586. void CMapFormatJson::serializeOptions(JsonSerializeFormat & handler)
  587. {
  588. serializeRumors(handler);
  589. serializeTimedEvents(handler);
  590. serializePredefinedHeroes(handler);
  591. handler.serializeLIC("allowedAbilities", &SecondarySkill::decode, &SecondarySkill::encode, LIBRARY->skillh->getDefaultAllowed(), map->allowedAbilities);
  592. handler.serializeLIC("allowedArtifacts", &ArtifactID::decode, &ArtifactID::encode, LIBRARY->arth->getDefaultAllowed(), map->allowedArtifact);
  593. handler.serializeLIC("allowedSpells", &SpellID::decode, &SpellID::encode, LIBRARY->spellh->getDefaultAllowed(), map->allowedSpells);
  594. //todo:events
  595. }
  596. void CMapFormatJson::readOptions(JsonDeserializer & handler)
  597. {
  598. readDisposedHeroes(handler);
  599. serializeOptions(handler);
  600. }
  601. void CMapFormatJson::writeOptions(JsonSerializer & handler)
  602. {
  603. writeDisposedHeroes(handler);
  604. serializeOptions(handler);
  605. }
  606. ///CMapPatcher
  607. CMapPatcher::CMapPatcher(const JsonNode & stream): input(stream)
  608. {
  609. //todo: update map patches and change this
  610. fileVersionMajor = 0;
  611. fileVersionMinor = 0;
  612. }
  613. void CMapPatcher::patchMapHeader(std::unique_ptr<CMapHeader> & header)
  614. {
  615. map = nullptr;
  616. mapHeader = header.get();
  617. if (!input.isNull())
  618. readPatchData();
  619. }
  620. void CMapPatcher::readPatchData()
  621. {
  622. JsonDeserializer handler(mapObjectResolver.get(), input);
  623. readTriggeredEvents(handler);
  624. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  625. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  626. handler.serializeStruct("victoryString", mapHeader->victoryMessage);
  627. handler.serializeStruct("defeatString", mapHeader->defeatMessage);
  628. }
  629. ///CMapLoaderJson
  630. CMapLoaderJson::CMapLoaderJson(CInputStream * stream)
  631. : buffer(stream)
  632. , ioApi(new CProxyROIOApi(buffer))
  633. , loader("", "_", ioApi)
  634. {
  635. }
  636. std::unique_ptr<CMap> CMapLoaderJson::loadMap(IGameInfoCallback * cb)
  637. {
  638. LOG_TRACE(logGlobal);
  639. auto result = std::make_unique<CMap>(cb);
  640. map = result.get();
  641. mapHeader = map;
  642. readMap();
  643. return result;
  644. }
  645. std::unique_ptr<CMapHeader> CMapLoaderJson::loadMapHeader()
  646. {
  647. LOG_TRACE(logGlobal);
  648. map = nullptr;
  649. auto result = std::make_unique<CMapHeader>();
  650. mapHeader = result.get();
  651. readHeader(false);
  652. return result;
  653. }
  654. bool CMapLoaderJson::isExistArchive(const std::string & archiveFilename)
  655. {
  656. return loader.existsResource(JsonPath::builtin(archiveFilename));
  657. }
  658. JsonNode CMapLoaderJson::getFromArchive(const std::string & archiveFilename)
  659. {
  660. JsonPath resource = JsonPath::builtin(archiveFilename);
  661. if(!loader.existsResource(resource))
  662. throw std::runtime_error(archiveFilename+" not found");
  663. auto data = loader.load(resource)->readAll();
  664. JsonNode res(reinterpret_cast<const std::byte*>(data.first.get()), data.second, archiveFilename);
  665. return res;
  666. }
  667. void CMapLoaderJson::readMap()
  668. {
  669. LOG_TRACE(logGlobal);
  670. readHeader(true);
  671. map->initTerrain();
  672. readTerrain();
  673. readObjects();
  674. map->calculateGuardingGreaturePositions();
  675. }
  676. void CMapLoaderJson::readHeader(const bool complete)
  677. {
  678. //do not use map field here, use only mapHeader
  679. JsonNode header = getFromArchive(HEADER_FILE_NAME);
  680. fileVersionMajor = static_cast<int>(header["versionMajor"].Integer());
  681. if(fileVersionMajor > VERSION_MAJOR)
  682. {
  683. logGlobal->error("Unsupported map format version: %d", fileVersionMajor);
  684. throw std::runtime_error("Unsupported map format version");
  685. }
  686. fileVersionMinor = static_cast<int>(header["versionMinor"].Integer());
  687. if(fileVersionMinor > VERSION_MINOR)
  688. {
  689. logGlobal->warn("Too new map format revision: %d. This map should work but some of map features may be ignored.", fileVersionMinor);
  690. }
  691. JsonDeserializer handler(mapObjectResolver.get(), header);
  692. mapHeader->version = EMapFormat::VCMI;//todo: new version field
  693. //loading mods
  694. mapHeader->mods = ModVerificationInfo::jsonDeserializeList(header["mods"]);
  695. {
  696. auto levels = handler.enterStruct("mapLevels");
  697. {
  698. auto surface = handler.enterStruct("surface");
  699. handler.serializeInt("height", mapHeader->height);
  700. handler.serializeInt("width", mapHeader->width);
  701. }
  702. mapHeader->mapLevels = levels->getCurrent().Struct().size();
  703. }
  704. serializeHeader(handler);
  705. readTriggeredEvents(handler);
  706. readTeams(handler);
  707. //TODO: check mods
  708. if(complete)
  709. readOptions(handler);
  710. readTranslations();
  711. }
  712. void CMapLoaderJson::readTerrainTile(const std::string & src, TerrainTile & tile)
  713. {
  714. try
  715. {
  716. using namespace TerrainDetail;
  717. {//terrain type
  718. const std::string typeCode = src.substr(0, 2);
  719. tile.terrainType = getTerrainByCode(typeCode);
  720. }
  721. int startPos = 2; //0+typeCode fixed length
  722. {//terrain view
  723. int pos = startPos;
  724. while (isdigit(src.at(pos)))
  725. pos++;
  726. int len = pos - startPos;
  727. if (len <= 0)
  728. throw std::runtime_error("Invalid terrain view in " + src);
  729. const std::string rawCode = src.substr(startPos, len);
  730. tile.terView = atoi(rawCode.c_str());
  731. startPos += len;
  732. }
  733. {//terrain flip
  734. int terrainFlip = vstd::find_pos(flipCodes, src.at(startPos++));
  735. if (terrainFlip < 0)
  736. throw std::runtime_error("Invalid terrain flip in " + src);
  737. else
  738. tile.extTileFlags = terrainFlip;
  739. }
  740. if (startPos >= src.size())
  741. return;
  742. bool hasRoad = true;
  743. {//road type
  744. const std::string typeCode = src.substr(startPos, 2);
  745. startPos += 2;
  746. tile.roadType = getRoadByCode(typeCode);
  747. if(!tile.roadType) //it's not a road, it's a river
  748. {
  749. tile.roadType = Road::NO_ROAD;
  750. tile.riverType = getRiverByCode(typeCode);
  751. hasRoad = false;
  752. if(!tile.riverType)
  753. {
  754. throw std::runtime_error("Invalid river type in " + src);
  755. }
  756. }
  757. }
  758. if (hasRoad)
  759. {//road dir
  760. int pos = startPos;
  761. while (isdigit(src.at(pos)))
  762. pos++;
  763. int len = pos - startPos;
  764. if (len <= 0)
  765. throw std::runtime_error("Invalid road dir in " + src);
  766. const std::string rawCode = src.substr(startPos, len);
  767. tile.roadDir = atoi(rawCode.c_str());
  768. startPos += len;
  769. }
  770. if (hasRoad)
  771. {//road flip
  772. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  773. if (flip < 0)
  774. throw std::runtime_error("Invalid road flip in " + src);
  775. else
  776. tile.extTileFlags |= (flip << 4);
  777. }
  778. if (startPos >= src.size())
  779. return;
  780. if (hasRoad)
  781. {//river type
  782. const std::string typeCode = src.substr(startPos, 2);
  783. startPos += 2;
  784. tile.riverType = getRiverByCode(typeCode);
  785. }
  786. {//river dir
  787. int pos = startPos;
  788. while (isdigit(src.at(pos)))
  789. pos++;
  790. int len = pos - startPos;
  791. if (len <= 0)
  792. throw std::runtime_error("Invalid river dir in " + src);
  793. const std::string rawCode = src.substr(startPos, len);
  794. tile.riverDir = atoi(rawCode.c_str());
  795. startPos += len;
  796. }
  797. {//river flip
  798. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  799. if (flip < 0)
  800. throw std::runtime_error("Invalid road flip in " + src);
  801. else
  802. tile.extTileFlags |= (flip << 2);
  803. }
  804. }
  805. catch (const std::exception &)
  806. {
  807. logGlobal->error("Failed to read terrain tile: %s");
  808. }
  809. }
  810. void CMapLoaderJson::readTerrainLevel(const JsonNode & src, const int index)
  811. {
  812. int3 pos(0, 0, index);
  813. const JsonVector & rows = src.Vector();
  814. if(rows.size() != map->height)
  815. throw std::runtime_error("Invalid terrain data");
  816. for(pos.y = 0; pos.y < map->height; pos.y++)
  817. {
  818. const JsonVector & tiles = rows[pos.y].Vector();
  819. if(tiles.size() != map->width)
  820. throw std::runtime_error("Invalid terrain data");
  821. for(pos.x = 0; pos.x < map->width; pos.x++)
  822. readTerrainTile(tiles[pos.x].String(), map->getTile(pos));
  823. }
  824. }
  825. void CMapLoaderJson::readTerrain()
  826. {
  827. for(int i = 0; i < map->mapLevels; i++)
  828. {
  829. const JsonNode node = getFromArchive(getTerrainFilename(i));
  830. readTerrainLevel(node, i);
  831. }
  832. }
  833. CMapLoaderJson::MapObjectLoader::MapObjectLoader(CMapLoaderJson * _owner, JsonMap::value_type & json):
  834. owner(_owner), instance(nullptr), id(-1), jsonKey(json.first), configuration(json.second)
  835. {
  836. }
  837. void CMapLoaderJson::MapObjectLoader::construct()
  838. {
  839. //TODO:consider move to ObjectTypeHandler
  840. //find type handler
  841. std::string typeName = configuration["type"].String();
  842. std::string subtypeName = configuration["subtype"].String();
  843. if(typeName.empty())
  844. {
  845. logGlobal->error("Object type missing");
  846. logGlobal->debug(configuration.toString());
  847. return;
  848. }
  849. int3 pos;
  850. pos.x = static_cast<si32>(configuration["x"].Float());
  851. pos.y = static_cast<si32>(configuration["y"].Float());
  852. pos.z = static_cast<si32>(configuration["l"].Float());
  853. //special case for grail
  854. if(typeName == "grail")
  855. {
  856. owner->map->grailPos = pos;
  857. owner->map->grailRadius = static_cast<int>(configuration["options"]["grailRadius"].Float());
  858. return;
  859. }
  860. else if(subtypeName.empty())
  861. {
  862. logGlobal->error("Object subtype missing");
  863. logGlobal->debug(configuration.toString());
  864. return;
  865. }
  866. configuration.setModScope(ModScope::scopeGame());
  867. auto handler = LIBRARY->objtypeh->getHandlerFor( ModScope::scopeMap(), typeName, subtypeName);
  868. auto appearance = std::make_shared<ObjectTemplate>();
  869. appearance->id = Obj(handler->getIndex());
  870. appearance->subid = handler->getSubIndex();
  871. appearance->readJson(configuration["template"], false);
  872. // Will be destroyed soon and replaced with shared template
  873. instance = handler->create(owner->map->cb, appearance);
  874. instance->instanceName = jsonKey;
  875. instance->setAnchorPos(pos);
  876. owner->map->addNewObject(instance);
  877. }
  878. void CMapLoaderJson::MapObjectLoader::configure()
  879. {
  880. if(nullptr == instance)
  881. return;
  882. JsonDeserializer handler(owner->mapObjectResolver.get(), configuration);
  883. instance->serializeJson(handler);
  884. //artifact instance serialization requires access to Map object, handle it here for now
  885. //todo: find better solution for artifact instance serialization
  886. if(auto art = std::dynamic_pointer_cast<CGArtifact>(instance))
  887. {
  888. ArtifactID artID = ArtifactID::NONE;
  889. SpellID spellID = SpellID::NONE;
  890. if(art->ID == Obj::SPELL_SCROLL)
  891. {
  892. auto spellIdentifier = configuration["options"]["spell"].String();
  893. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "spell", spellIdentifier);
  894. if(rawId)
  895. spellID = rawId.value();
  896. else
  897. spellID = 0;
  898. artID = ArtifactID::SPELL_SCROLL;
  899. }
  900. else if (art->ID == Obj::ARTIFACT || (art->ID >= Obj::RANDOM_ART && art->ID <= Obj::RANDOM_RELIC_ART))
  901. {
  902. //specific artifact
  903. artID = art->getArtifactType();
  904. }
  905. art->setArtifactInstance(owner->map->createArtifact(artID, spellID.getNum()));
  906. }
  907. if(auto hero = std::dynamic_pointer_cast<CGHeroInstance>(instance))
  908. {
  909. auto o = handler.enterStruct("options");
  910. hero->serializeJsonArtifacts(handler, "artifacts", owner->map);
  911. }
  912. }
  913. void CMapLoaderJson::readObjects()
  914. {
  915. LOG_TRACE(logGlobal);
  916. std::vector<std::unique_ptr<MapObjectLoader>> loaders;//todo: optimize MapObjectLoader memory layout
  917. JsonNode data = getFromArchive(OBJECTS_FILE_NAME);
  918. //get raw data
  919. for(auto & p : data.Struct())
  920. loaders.push_back(std::make_unique<MapObjectLoader>(this, p));
  921. for(auto & ptr : loaders)
  922. ptr->construct();
  923. //configure objects after all objects are constructed so we may resolve internal IDs even to actual pointers OTF
  924. for(auto & ptr : loaders)
  925. ptr->configure();
  926. std::set<HeroTypeID> debugHeroesOnMap;
  927. for (auto const & hero : map->getObjects<CGHeroInstance>())
  928. {
  929. if(hero->ID != Obj::HERO && hero->ID != Obj::PRISON)
  930. continue;
  931. if (debugHeroesOnMap.count(hero->getHeroTypeID()))
  932. logGlobal->error("Hero is already on the map at %s", hero->visitablePos().toString());
  933. debugHeroesOnMap.insert(hero->getHeroTypeID());
  934. }
  935. map->parseUidCounter();
  936. }
  937. void CMapLoaderJson::readTranslations()
  938. {
  939. std::list<Languages::Options> languages{Languages::getLanguageList().begin(), Languages::getLanguageList().end()};
  940. for(auto & language : Languages::getLanguageList())
  941. {
  942. if(isExistArchive(language.identifier + ".json"))
  943. mapHeader->translations.Struct()[language.identifier] = getFromArchive(language.identifier + ".json");
  944. }
  945. mapHeader->registerMapStrings();
  946. }
  947. ///CMapSaverJson
  948. CMapSaverJson::CMapSaverJson(CInputOutputStream * stream)
  949. : buffer(stream)
  950. , ioApi(new CProxyIOApi(buffer))
  951. , saver(ioApi, "_")
  952. {
  953. fileVersionMajor = VERSION_MAJOR;
  954. fileVersionMinor = VERSION_MINOR;
  955. }
  956. //must be instantiated in .cpp file for access to complete types of all member fields
  957. CMapSaverJson::~CMapSaverJson() = default;
  958. void CMapSaverJson::addToArchive(const JsonNode & data, const std::string & filename)
  959. {
  960. std::ostringstream out;
  961. JsonWriter writer(out, false);
  962. writer.writeNode(data);
  963. out.flush();
  964. {
  965. auto s = out.str();
  966. std::unique_ptr<COutputStream> stream = saver.addFile(filename);
  967. if(stream->write(reinterpret_cast<const ui8 *>(s.c_str()), s.size()) != s.size())
  968. throw std::runtime_error("CMapSaverJson::saveHeader() zip compression failed.");
  969. }
  970. }
  971. void CMapSaverJson::saveMap(const std::unique_ptr<CMap>& map)
  972. {
  973. this->map = map.get();
  974. this->mapHeader = this->map;
  975. writeHeader();
  976. writeTerrain();
  977. writeObjects();
  978. }
  979. void CMapSaverJson::writeHeader()
  980. {
  981. logGlobal->trace("Saving header");
  982. JsonNode header;
  983. JsonSerializer handler(mapObjectResolver.get(), header);
  984. header["versionMajor"].Float() = VERSION_MAJOR;
  985. header["versionMinor"].Float() = VERSION_MINOR;
  986. //write mods
  987. header["mods"] = ModVerificationInfo::jsonSerializeList(mapHeader->mods);
  988. auto getName = [](int level){
  989. if(level == 0)
  990. return std::string("surface");
  991. else if(level == 1)
  992. return std::string("underground");
  993. else
  994. return "level-" + std::to_string(level + 1);
  995. };
  996. JsonNode & levels = header["mapLevels"];
  997. for(int i = 0; i < map->mapLevels; i++)
  998. {
  999. auto name = getName(i);
  1000. levels[name]["height"].Float() = mapHeader->height;
  1001. levels[name]["width"].Float() = mapHeader->width;
  1002. levels[name]["index"].Float() = i;
  1003. }
  1004. serializeHeader(handler);
  1005. writeTriggeredEvents(handler);
  1006. writeTeams(handler);
  1007. writeOptions(handler);
  1008. writeTranslations();
  1009. addToArchive(header, HEADER_FILE_NAME);
  1010. }
  1011. std::string CMapSaverJson::writeTerrainTile(const TerrainTile & tile)
  1012. {
  1013. using namespace TerrainDetail;
  1014. std::ostringstream out;
  1015. out.setf(std::ios::dec, std::ios::basefield);
  1016. out.unsetf(std::ios::showbase);
  1017. out << tile.getTerrain()->shortIdentifier << static_cast<int>(tile.terView) << flipCodes[tile.extTileFlags % 4];
  1018. if(tile.hasRoad())
  1019. out << tile.getRoad()->shortIdentifier << static_cast<int>(tile.roadDir) << flipCodes[(tile.extTileFlags >> 4) % 4];
  1020. if(tile.hasRiver())
  1021. out << tile.getRiver()->shortIdentifier << static_cast<int>(tile.riverDir) << flipCodes[(tile.extTileFlags >> 2) % 4];
  1022. return out.str();
  1023. }
  1024. JsonNode CMapSaverJson::writeTerrainLevel(const int index)
  1025. {
  1026. JsonNode data;
  1027. int3 pos(0,0,index);
  1028. data.Vector().resize(map->height);
  1029. for(pos.y = 0; pos.y < map->height; pos.y++)
  1030. {
  1031. JsonNode & row = data.Vector()[pos.y];
  1032. row.Vector().resize(map->width);
  1033. for(pos.x = 0; pos.x < map->width; pos.x++)
  1034. row.Vector()[pos.x].String() = writeTerrainTile(map->getTile(pos));
  1035. }
  1036. return data;
  1037. }
  1038. void CMapSaverJson::writeTerrain()
  1039. {
  1040. logGlobal->trace("Saving terrain");
  1041. for(int i = 0; i < map->mapLevels; i++)
  1042. {
  1043. JsonNode node = writeTerrainLevel(i);
  1044. addToArchive(node, getTerrainFilename(i));
  1045. }
  1046. }
  1047. void CMapSaverJson::writeObjects()
  1048. {
  1049. logGlobal->trace("Saving objects");
  1050. JsonNode data;
  1051. JsonSerializer handler(mapObjectResolver.get(), data);
  1052. for(const auto & obj : map->getObjects())
  1053. {
  1054. //logGlobal->trace("\t%s", obj->instanceName);
  1055. auto temp = handler.enterStruct(obj->instanceName);
  1056. obj->serializeJson(handler);
  1057. data[obj->instanceName].setModScope(ModScope::scopeGame());
  1058. }
  1059. if(map->grailPos.isValid())
  1060. {
  1061. JsonNode grail;
  1062. grail["type"].String() = "grail";
  1063. grail["x"].Float() = map->grailPos.x;
  1064. grail["y"].Float() = map->grailPos.y;
  1065. grail["l"].Float() = map->grailPos.z;
  1066. grail["options"]["radius"].Float() = map->grailRadius;
  1067. grail.setModScope(ModScope::scopeGame());
  1068. data["grail"] = grail;
  1069. }
  1070. //cleanup empty options
  1071. for(auto & p : data.Struct())
  1072. {
  1073. JsonNode & obj = p.second;
  1074. if(obj["options"].Struct().empty())
  1075. obj.Struct().erase("options");
  1076. }
  1077. addToArchive(data, OBJECTS_FILE_NAME);
  1078. }
  1079. void CMapSaverJson::writeTranslations()
  1080. {
  1081. for(auto & s : mapHeader->translations.Struct())
  1082. {
  1083. auto & language = s.first;
  1084. if(Languages::getLanguageOptions(language).identifier.empty())
  1085. {
  1086. logGlobal->error("Serializing of unsupported language %s is not permitted", language);
  1087. continue;
  1088. }
  1089. logGlobal->trace("Saving translations, language: %s", language);
  1090. addToArchive(s.second, language + ".json");
  1091. }
  1092. }
  1093. VCMI_LIB_NAMESPACE_END