MapFormatJson.cpp 35 KB

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