2
0

MapFormatJson.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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 "../CHeroHandler.h"
  19. #include "../CTownHandler.h"
  20. #include "../VCMI_Lib.h"
  21. #include "../RiverHandler.h"
  22. #include "../RoadHandler.h"
  23. #include "../TerrainHandler.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 "../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. si32 oid = id.getNum();
  79. if(oid < 0 || oid >= owner->map->objects.size())
  80. {
  81. logGlobal->error("Cannot get object with id %d", oid);
  82. return "";
  83. }
  84. return owner->map->objects[oid]->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. TerrainType * CMapFormatJson::getTerrainByCode(const std::string & code)
  221. {
  222. for(const auto & object : VLC->terrainTypeHandler->objects)
  223. {
  224. if(object->shortIdentifier == code)
  225. return const_cast<TerrainType *>(object.get());
  226. }
  227. return nullptr;
  228. }
  229. RiverType * CMapFormatJson::getRiverByCode(const std::string & code)
  230. {
  231. for(const auto & object : VLC->riverTypeHandler->objects)
  232. {
  233. if (object->shortIdentifier == code)
  234. return const_cast<RiverType *>(object.get());
  235. }
  236. return nullptr;
  237. }
  238. RoadType * CMapFormatJson::getRoadByCode(const std::string & code)
  239. {
  240. for(const auto & object : VLC->roadTypeHandler->objects)
  241. {
  242. if (object->shortIdentifier == code)
  243. return const_cast<RoadType *>(object.get());
  244. }
  245. return nullptr;
  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 : VLC->townh->getDefaultAllowed())
  253. if(vstd::contains(value, factionID))
  254. temp.insert(factionID);
  255. }
  256. handler.serializeLIC("allowedFactions", &FactionID::decode, &FactionID::encode, VLC->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, VLC->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. }
  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.valid())
  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.valid();
  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 & obj : map->objects)
  355. {
  356. if((obj->ID == Obj::HERO || obj->ID == Obj::RANDOM_HERO) && obj->tempOwner == PlayerColor(player))
  357. {
  358. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  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->type)
  368. temp = hero->type->getJsonKey();
  369. else
  370. temp = hero->getHeroType().toEntity(VLC)->getJsonKey();
  371. handler.serializeString("type", temp);
  372. }
  373. }
  374. }
  375. }
  376. }
  377. else
  378. {
  379. info.heroesNames.clear();
  380. auto heroes = handler.enterStruct("heroes");
  381. for(const auto & hero : handler.getCurrent().Struct())
  382. {
  383. const JsonNode & data = hero.second;
  384. const std::string instanceName = hero.first;
  385. SHeroName hname;
  386. hname.heroId = HeroTypeID::NONE;
  387. std::string rawId = data["type"].String();
  388. if(!rawId.empty())
  389. hname.heroId = HeroTypeID(HeroTypeID::decode(rawId));
  390. hname.heroName = data["name"].String();
  391. if(instanceName == info.mainHeroInstance)
  392. {
  393. //this is main hero
  394. info.mainCustomHeroNameTextId = hname.heroName;
  395. info.hasRandomHero = (hname.heroId == HeroTypeID::NONE);
  396. info.mainCustomHeroId = hname.heroId;
  397. info.mainCustomHeroPortrait = HeroTypeID::NONE;
  398. //todo:mainHeroPortrait
  399. }
  400. info.heroesNames.push_back(hname);
  401. }
  402. }
  403. handler.serializeBool("randomFaction", info.isFactionRandom);
  404. }
  405. }
  406. void CMapFormatJson::readTeams(JsonDeserializer & handler)
  407. {
  408. auto teams = handler.enterArray("teams");
  409. const JsonNode & src = teams->getCurrent();
  410. if(src.getType() != JsonNode::JsonType::DATA_VECTOR)
  411. {
  412. // No alliances
  413. if(src.getType() != JsonNode::JsonType::DATA_NULL)
  414. logGlobal->error("Invalid teams field type");
  415. mapHeader->howManyTeams = 0;
  416. for(auto & player : mapHeader->players)
  417. if(player.canAnyonePlay())
  418. player.team = TeamID(mapHeader->howManyTeams++);
  419. }
  420. else
  421. {
  422. const JsonVector & srcVector = src.Vector();
  423. mapHeader->howManyTeams = static_cast<ui8>(srcVector.size());
  424. for(int team = 0; team < mapHeader->howManyTeams; team++)
  425. for(const JsonNode & playerData : srcVector[team].Vector())
  426. {
  427. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  428. if(player.isValidPlayer())
  429. if(mapHeader->players[player.getNum()].canAnyonePlay())
  430. mapHeader->players[player.getNum()].team = TeamID(team);
  431. }
  432. for(PlayerInfo & player : mapHeader->players)
  433. if(player.canAnyonePlay() && player.team == TeamID::NO_TEAM)
  434. player.team = TeamID(mapHeader->howManyTeams++);
  435. }
  436. }
  437. void CMapFormatJson::writeTeams(JsonSerializer & handler)
  438. {
  439. std::vector<std::set<PlayerColor>> teamsData;
  440. teamsData.resize(mapHeader->howManyTeams);
  441. //get raw data
  442. for(int idx = 0; idx < mapHeader->players.size(); idx++)
  443. {
  444. const PlayerInfo & player = mapHeader->players.at(idx);
  445. int team = player.team.getNum();
  446. if(vstd::iswithin(team, 0, mapHeader->howManyTeams-1) && player.canAnyonePlay())
  447. teamsData.at(team).insert(PlayerColor(idx));
  448. }
  449. //remove single-member teams
  450. vstd::erase_if(teamsData, [](std::set<PlayerColor> & elem) -> bool
  451. {
  452. return elem.size() <= 1;
  453. });
  454. if(!teamsData.empty())
  455. {
  456. JsonNode dest;
  457. //construct output
  458. dest.setType(JsonNode::JsonType::DATA_VECTOR);
  459. for(const std::set<PlayerColor> & teamData : teamsData)
  460. {
  461. JsonNode team;
  462. for(const PlayerColor & player : teamData)
  463. team.Vector().emplace_back(GameConstants::PLAYER_COLOR_NAMES[player.getNum()]);
  464. dest.Vector().push_back(std::move(team));
  465. }
  466. handler.serializeRaw("teams", dest, std::nullopt);
  467. }
  468. }
  469. void CMapFormatJson::readTriggeredEvents(JsonDeserializer & handler)
  470. {
  471. const JsonNode & input = handler.getCurrent();
  472. mapHeader->triggeredEvents.clear();
  473. for(const auto & entry : input["triggeredEvents"].Struct())
  474. {
  475. TriggeredEvent event;
  476. event.identifier = entry.first;
  477. readTriggeredEvent(event, entry.second);
  478. mapHeader->triggeredEvents.push_back(event);
  479. }
  480. }
  481. void CMapFormatJson::readTriggeredEvent(TriggeredEvent & event, const JsonNode & source) const
  482. {
  483. using namespace TriggeredEventsDetail;
  484. event.onFulfill.jsonDeserialize(source["message"]);
  485. event.description.jsonDeserialize(source["description"]);
  486. event.effect.type = vstd::find_pos(typeNames, source["effect"]["type"].String());
  487. event.effect.toOtherMessage.jsonDeserialize(source["effect"]["messageToSend"]);
  488. event.trigger = EventExpression(source["condition"], JsonToCondition); // logical expression
  489. }
  490. void CMapFormatJson::writeTriggeredEvents(JsonSerializer & handler)
  491. {
  492. JsonNode triggeredEvents;
  493. for(const auto & event : mapHeader->triggeredEvents)
  494. writeTriggeredEvent(event, triggeredEvents[event.identifier]);
  495. handler.serializeRaw("triggeredEvents", triggeredEvents, std::nullopt);
  496. }
  497. void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent & event, JsonNode & dest) const
  498. {
  499. using namespace TriggeredEventsDetail;
  500. if(!event.onFulfill.empty())
  501. event.onFulfill.jsonSerialize(dest["message"]);
  502. if(!event.description.empty())
  503. event.description.jsonSerialize(dest["description"]);
  504. dest["effect"]["type"].String() = typeNames.at(static_cast<size_t>(event.effect.type));
  505. if(!event.effect.toOtherMessage.empty())
  506. event.description.jsonSerialize(dest["effect"]["messageToSend"]);
  507. dest["condition"] = event.trigger.toJson(ConditionToJson);
  508. }
  509. void CMapFormatJson::readDisposedHeroes(JsonSerializeFormat & handler)
  510. {
  511. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  512. const JsonNode & data = handler.getCurrent();
  513. for(const auto & entry : data.Struct())
  514. {
  515. HeroTypeID type(HeroTypeID::decode(entry.first));
  516. std::set<PlayerColor> mask;
  517. for(const JsonNode & playerData : entry.second["availableFor"].Vector())
  518. {
  519. PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
  520. if(player.isValidPlayer())
  521. mask.insert(player);
  522. }
  523. if(!mask.empty() && mask.size() != PlayerColor::PLAYER_LIMIT_I && type.getNum() >= 0)
  524. {
  525. DisposedHero hero;
  526. hero.heroId = type;
  527. hero.players = mask;
  528. //name and portrait are not used
  529. map->disposedHeroes.push_back(hero);
  530. }
  531. }
  532. }
  533. void CMapFormatJson::writeDisposedHeroes(JsonSerializeFormat & handler)
  534. {
  535. if(map->disposedHeroes.empty())
  536. return;
  537. auto definitions = handler.enterStruct("predefinedHeroes");//DisposedHeroes are part of predefinedHeroes in VCMI map format
  538. for(DisposedHero & hero : map->disposedHeroes)
  539. {
  540. std::string type = HeroTypeID::encode(hero.heroId.getNum());
  541. auto definition = definitions->enterStruct(type);
  542. JsonNode players;
  543. definition->serializeIdArray("availableFor", hero.players);
  544. }
  545. }
  546. void CMapFormatJson::serializeRumors(JsonSerializeFormat & handler)
  547. {
  548. auto rumors = handler.enterArray("rumors");
  549. rumors.serializeStruct(map->rumors);
  550. }
  551. void CMapFormatJson::serializeTimedEvents(JsonSerializeFormat & handler)
  552. {
  553. auto events = handler.enterArray("events");
  554. std::vector<CMapEvent> temp(map->events.begin(), map->events.end());
  555. events.serializeStruct(temp);
  556. map->events.assign(temp.begin(), temp.end());
  557. }
  558. void CMapFormatJson::serializePredefinedHeroes(JsonSerializeFormat & handler)
  559. {
  560. //todo:serializePredefinedHeroes
  561. if(handler.saving)
  562. {
  563. if(!map->predefinedHeroes.empty())
  564. {
  565. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  566. for(auto & hero : map->predefinedHeroes)
  567. {
  568. auto predefinedHero = handler.enterStruct(hero->getHeroTypeName());
  569. hero->serializeJsonDefinition(handler);
  570. }
  571. }
  572. }
  573. else
  574. {
  575. auto predefinedHeroes = handler.enterStruct("predefinedHeroes");
  576. const JsonNode & data = handler.getCurrent();
  577. for(const auto & p : data.Struct())
  578. {
  579. auto predefinedHero = handler.enterStruct(p.first);
  580. auto * hero = new CGHeroInstance(map->cb);
  581. hero->ID = Obj::HERO;
  582. hero->setHeroTypeName(p.first);
  583. hero->serializeJsonDefinition(handler);
  584. map->predefinedHeroes.emplace_back(hero);
  585. }
  586. }
  587. }
  588. void CMapFormatJson::serializeOptions(JsonSerializeFormat & handler)
  589. {
  590. serializeRumors(handler);
  591. serializeTimedEvents(handler);
  592. serializePredefinedHeroes(handler);
  593. handler.serializeLIC("allowedAbilities", &SecondarySkill::decode, &SecondarySkill::encode, VLC->skillh->getDefaultAllowed(), map->allowedAbilities);
  594. handler.serializeLIC("allowedArtifacts", &ArtifactID::decode, &ArtifactID::encode, VLC->arth->getDefaultAllowed(), map->allowedArtifact);
  595. handler.serializeLIC("allowedSpells", &SpellID::decode, &SpellID::encode, VLC->spellh->getDefaultAllowed(), map->allowedSpells);
  596. //todo:events
  597. }
  598. void CMapFormatJson::readOptions(JsonDeserializer & handler)
  599. {
  600. readDisposedHeroes(handler);
  601. serializeOptions(handler);
  602. }
  603. void CMapFormatJson::writeOptions(JsonSerializer & handler)
  604. {
  605. writeDisposedHeroes(handler);
  606. serializeOptions(handler);
  607. }
  608. ///CMapPatcher
  609. CMapPatcher::CMapPatcher(const JsonNode & stream): input(stream)
  610. {
  611. //todo: update map patches and change this
  612. fileVersionMajor = 0;
  613. fileVersionMinor = 0;
  614. }
  615. void CMapPatcher::patchMapHeader(std::unique_ptr<CMapHeader> & header)
  616. {
  617. map = nullptr;
  618. mapHeader = header.get();
  619. if (!input.isNull())
  620. readPatchData();
  621. }
  622. void CMapPatcher::readPatchData()
  623. {
  624. JsonDeserializer handler(mapObjectResolver.get(), input);
  625. readTriggeredEvents(handler);
  626. handler.serializeInt("defeatIconIndex", mapHeader->defeatIconIndex);
  627. handler.serializeInt("victoryIconIndex", mapHeader->victoryIconIndex);
  628. handler.serializeStruct("victoryString", mapHeader->victoryMessage);
  629. handler.serializeStruct("defeatString", mapHeader->defeatMessage);
  630. }
  631. ///CMapLoaderJson
  632. CMapLoaderJson::CMapLoaderJson(CInputStream * stream)
  633. : buffer(stream)
  634. , ioApi(new CProxyROIOApi(buffer))
  635. , loader("", "_", ioApi)
  636. {
  637. }
  638. std::unique_ptr<CMap> CMapLoaderJson::loadMap(IGameCallback * cb)
  639. {
  640. LOG_TRACE(logGlobal);
  641. auto result = std::make_unique<CMap>(cb);
  642. map = result.get();
  643. mapHeader = map;
  644. readMap();
  645. return result;
  646. }
  647. std::unique_ptr<CMapHeader> CMapLoaderJson::loadMapHeader()
  648. {
  649. LOG_TRACE(logGlobal);
  650. map = nullptr;
  651. auto result = std::make_unique<CMapHeader>();
  652. mapHeader = result.get();
  653. readHeader(false);
  654. return result;
  655. }
  656. bool CMapLoaderJson::isExistArchive(const std::string & archiveFilename)
  657. {
  658. return loader.existsResource(JsonPath::builtin(archiveFilename));
  659. }
  660. JsonNode CMapLoaderJson::getFromArchive(const std::string & archiveFilename)
  661. {
  662. JsonPath resource = JsonPath::builtin(archiveFilename);
  663. if(!loader.existsResource(resource))
  664. throw std::runtime_error(archiveFilename+" not found");
  665. auto data = loader.load(resource)->readAll();
  666. JsonNode res(reinterpret_cast<const std::byte*>(data.first.get()), data.second);
  667. return res;
  668. }
  669. void CMapLoaderJson::readMap()
  670. {
  671. LOG_TRACE(logGlobal);
  672. readHeader(true);
  673. map->initTerrain();
  674. readTerrain();
  675. readObjects();
  676. map->calculateGuardingGreaturePositions();
  677. }
  678. void CMapLoaderJson::readHeader(const bool complete)
  679. {
  680. //do not use map field here, use only mapHeader
  681. JsonNode header = getFromArchive(HEADER_FILE_NAME);
  682. fileVersionMajor = static_cast<int>(header["versionMajor"].Integer());
  683. if(fileVersionMajor > VERSION_MAJOR)
  684. {
  685. logGlobal->error("Unsupported map format version: %d", fileVersionMajor);
  686. throw std::runtime_error("Unsupported map format version");
  687. }
  688. fileVersionMinor = static_cast<int>(header["versionMinor"].Integer());
  689. if(fileVersionMinor > VERSION_MINOR)
  690. {
  691. logGlobal->warn("Too new map format revision: %d. This map should work but some of map features may be ignored.", fileVersionMinor);
  692. }
  693. JsonDeserializer handler(mapObjectResolver.get(), header);
  694. mapHeader->version = EMapFormat::VCMI;//todo: new version field
  695. //loading mods
  696. mapHeader->mods = ModVerificationInfo::jsonDeserializeList(header["mods"]);
  697. //todo: multilevel map load support
  698. {
  699. auto levels = handler.enterStruct("mapLevels");
  700. {
  701. auto surface = handler.enterStruct("surface");
  702. handler.serializeInt("height", mapHeader->height);
  703. handler.serializeInt("width", mapHeader->width);
  704. }
  705. {
  706. auto underground = handler.enterStruct("underground");
  707. mapHeader->twoLevel = !underground->getCurrent().isNull();
  708. }
  709. }
  710. serializeHeader(handler);
  711. readTriggeredEvents(handler);
  712. readTeams(handler);
  713. //TODO: check mods
  714. if(complete)
  715. readOptions(handler);
  716. readTranslations();
  717. }
  718. void CMapLoaderJson::readTerrainTile(const std::string & src, TerrainTile & tile)
  719. {
  720. try
  721. {
  722. using namespace TerrainDetail;
  723. {//terrain type
  724. const std::string typeCode = src.substr(0, 2);
  725. tile.terType = getTerrainByCode(typeCode);
  726. }
  727. int startPos = 2; //0+typeCode fixed length
  728. {//terrain view
  729. int pos = startPos;
  730. while (isdigit(src.at(pos)))
  731. pos++;
  732. int len = pos - startPos;
  733. if (len <= 0)
  734. throw std::runtime_error("Invalid terrain view in " + src);
  735. const std::string rawCode = src.substr(startPos, len);
  736. tile.terView = atoi(rawCode.c_str());
  737. startPos += len;
  738. }
  739. {//terrain flip
  740. int terrainFlip = vstd::find_pos(flipCodes, src.at(startPos++));
  741. if (terrainFlip < 0)
  742. throw std::runtime_error("Invalid terrain flip in " + src);
  743. else
  744. tile.extTileFlags = terrainFlip;
  745. }
  746. if (startPos >= src.size())
  747. return;
  748. bool hasRoad = true;
  749. {//road type
  750. const std::string typeCode = src.substr(startPos, 2);
  751. startPos += 2;
  752. tile.roadType = getRoadByCode(typeCode);
  753. if(!tile.roadType) //it's not a road, it's a river
  754. {
  755. tile.roadType = VLC->roadTypeHandler->getById(Road::NO_ROAD);
  756. tile.riverType = getRiverByCode(typeCode);
  757. hasRoad = false;
  758. if(!tile.riverType)
  759. {
  760. throw std::runtime_error("Invalid river type in " + src);
  761. }
  762. }
  763. }
  764. if (hasRoad)
  765. {//road dir
  766. int pos = startPos;
  767. while (isdigit(src.at(pos)))
  768. pos++;
  769. int len = pos - startPos;
  770. if (len <= 0)
  771. throw std::runtime_error("Invalid road dir in " + src);
  772. const std::string rawCode = src.substr(startPos, len);
  773. tile.roadDir = atoi(rawCode.c_str());
  774. startPos += len;
  775. }
  776. if (hasRoad)
  777. {//road flip
  778. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  779. if (flip < 0)
  780. throw std::runtime_error("Invalid road flip in " + src);
  781. else
  782. tile.extTileFlags |= (flip << 4);
  783. }
  784. if (startPos >= src.size())
  785. return;
  786. if (hasRoad)
  787. {//river type
  788. const std::string typeCode = src.substr(startPos, 2);
  789. startPos += 2;
  790. tile.riverType = getRiverByCode(typeCode);
  791. }
  792. {//river dir
  793. int pos = startPos;
  794. while (isdigit(src.at(pos)))
  795. pos++;
  796. int len = pos - startPos;
  797. if (len <= 0)
  798. throw std::runtime_error("Invalid river dir in " + src);
  799. const std::string rawCode = src.substr(startPos, len);
  800. tile.riverDir = atoi(rawCode.c_str());
  801. startPos += len;
  802. }
  803. {//river flip
  804. int flip = vstd::find_pos(flipCodes, src.at(startPos++));
  805. if (flip < 0)
  806. throw std::runtime_error("Invalid road flip in " + src);
  807. else
  808. tile.extTileFlags |= (flip << 2);
  809. }
  810. }
  811. catch (const std::exception &)
  812. {
  813. logGlobal->error("Failed to read terrain tile: %s");
  814. }
  815. }
  816. void CMapLoaderJson::readTerrainLevel(const JsonNode & src, const int index)
  817. {
  818. int3 pos(0, 0, index);
  819. const JsonVector & rows = src.Vector();
  820. if(rows.size() != map->height)
  821. throw std::runtime_error("Invalid terrain data");
  822. for(pos.y = 0; pos.y < map->height; pos.y++)
  823. {
  824. const JsonVector & tiles = rows[pos.y].Vector();
  825. if(tiles.size() != map->width)
  826. throw std::runtime_error("Invalid terrain data");
  827. for(pos.x = 0; pos.x < map->width; pos.x++)
  828. readTerrainTile(tiles[pos.x].String(), map->getTile(pos));
  829. }
  830. }
  831. void CMapLoaderJson::readTerrain()
  832. {
  833. {
  834. const JsonNode surface = getFromArchive(TERRAIN_FILE_NAMES[0]);
  835. readTerrainLevel(surface, 0);
  836. }
  837. if(map->twoLevel)
  838. {
  839. const JsonNode underground = getFromArchive(TERRAIN_FILE_NAMES[1]);
  840. readTerrainLevel(underground, 1);
  841. }
  842. map->calculateWaterContent();
  843. }
  844. CMapLoaderJson::MapObjectLoader::MapObjectLoader(CMapLoaderJson * _owner, JsonMap::value_type & json):
  845. owner(_owner), instance(nullptr), id(-1), jsonKey(json.first), configuration(json.second)
  846. {
  847. }
  848. void CMapLoaderJson::MapObjectLoader::construct()
  849. {
  850. //TODO:consider move to ObjectTypeHandler
  851. //find type handler
  852. std::string typeName = configuration["type"].String();
  853. std::string subtypeName = configuration["subtype"].String();
  854. if(typeName.empty())
  855. {
  856. logGlobal->error("Object type missing");
  857. logGlobal->debug(configuration.toString());
  858. return;
  859. }
  860. int3 pos;
  861. pos.x = static_cast<si32>(configuration["x"].Float());
  862. pos.y = static_cast<si32>(configuration["y"].Float());
  863. pos.z = static_cast<si32>(configuration["l"].Float());
  864. //special case for grail
  865. if(typeName == "grail")
  866. {
  867. owner->map->grailPos = pos;
  868. owner->map->grailRadius = static_cast<int>(configuration["options"]["grailRadius"].Float());
  869. return;
  870. }
  871. else if(subtypeName.empty())
  872. {
  873. logGlobal->error("Object subtype missing");
  874. logGlobal->debug(configuration.toString());
  875. return;
  876. }
  877. auto handler = VLC->objtypeh->getHandlerFor( ModScope::scopeMap(), typeName, subtypeName);
  878. auto appearance = std::make_shared<ObjectTemplate>();
  879. appearance->id = Obj(handler->getIndex());
  880. appearance->subid = handler->getSubIndex();
  881. appearance->readJson(configuration["template"], false);
  882. // Will be destroyed soon and replaced with shared template
  883. instance = handler->create(owner->map->cb, appearance);
  884. instance->id = ObjectInstanceID(static_cast<si32>(owner->map->objects.size()));
  885. instance->instanceName = jsonKey;
  886. instance->pos = pos;
  887. owner->map->addNewObject(instance);
  888. }
  889. void CMapLoaderJson::MapObjectLoader::configure()
  890. {
  891. if(nullptr == instance)
  892. return;
  893. JsonDeserializer handler(owner->mapObjectResolver.get(), configuration);
  894. instance->serializeJson(handler);
  895. //artifact instance serialization requires access to Map object, handle it here for now
  896. //todo: find better solution for artifact instance serialization
  897. if(auto * art = dynamic_cast<CGArtifact *>(instance))
  898. {
  899. ArtifactID artID = ArtifactID::NONE;
  900. SpellID spellID = SpellID::NONE;
  901. if(art->ID == Obj::SPELL_SCROLL)
  902. {
  903. auto spellIdentifier = configuration["options"]["spell"].String();
  904. auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeBuiltin(), "spell", spellIdentifier);
  905. if(rawId)
  906. spellID = rawId.value();
  907. else
  908. spellID = 0;
  909. artID = ArtifactID::SPELL_SCROLL;
  910. }
  911. else if(art->ID == Obj::ARTIFACT)
  912. {
  913. //specific artifact
  914. artID = art->getArtifact();
  915. }
  916. art->storedArtifact = ArtifactUtils::createArtifact(owner->map, artID, spellID.getNum());
  917. }
  918. if(auto * hero = dynamic_cast<CGHeroInstance *>(instance))
  919. {
  920. auto o = handler.enterStruct("options");
  921. hero->serializeJsonArtifacts(handler, "artifacts", owner->map);
  922. }
  923. }
  924. void CMapLoaderJson::readObjects()
  925. {
  926. LOG_TRACE(logGlobal);
  927. std::vector<std::unique_ptr<MapObjectLoader>> loaders;//todo: optimize MapObjectLoader memory layout
  928. JsonNode data = getFromArchive(OBJECTS_FILE_NAME);
  929. //get raw data
  930. for(auto & p : data.Struct())
  931. loaders.push_back(std::make_unique<MapObjectLoader>(this, p));
  932. for(auto & ptr : loaders)
  933. ptr->construct();
  934. //configure objects after all objects are constructed so we may resolve internal IDs even to actual pointers OTF
  935. for(auto & ptr : loaders)
  936. ptr->configure();
  937. std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  938. {
  939. return a->getObjTypeIndex() < b->getObjTypeIndex();
  940. });
  941. std::set<HeroTypeID> debugHeroesOnMap;
  942. for (auto const & object : map->objects)
  943. {
  944. if(object->ID != Obj::HERO && object->ID != Obj::PRISON)
  945. continue;
  946. auto * hero = dynamic_cast<const CGHeroInstance *>(object.get());
  947. if (debugHeroesOnMap.count(hero->getHeroType()))
  948. logGlobal->error("Hero is already on the map at %s", hero->visitablePos().toString());
  949. debugHeroesOnMap.insert(hero->getHeroType());
  950. }
  951. }
  952. void CMapLoaderJson::readTranslations()
  953. {
  954. std::list<Languages::Options> languages{Languages::getLanguageList().begin(), Languages::getLanguageList().end()};
  955. for(auto & language : Languages::getLanguageList())
  956. {
  957. if(isExistArchive(language.identifier + ".json"))
  958. mapHeader->translations.Struct()[language.identifier] = getFromArchive(language.identifier + ".json");
  959. }
  960. mapHeader->registerMapStrings();
  961. }
  962. ///CMapSaverJson
  963. CMapSaverJson::CMapSaverJson(CInputOutputStream * stream)
  964. : buffer(stream)
  965. , ioApi(new CProxyIOApi(buffer))
  966. , saver(ioApi, "_")
  967. {
  968. fileVersionMajor = VERSION_MAJOR;
  969. fileVersionMinor = VERSION_MINOR;
  970. }
  971. //must be instantiated in .cpp file for access to complete types of all member fields
  972. CMapSaverJson::~CMapSaverJson() = default;
  973. void CMapSaverJson::addToArchive(const JsonNode & data, const std::string & filename)
  974. {
  975. std::ostringstream out;
  976. JsonWriter writer(out, false);
  977. writer.writeNode(data);
  978. out.flush();
  979. {
  980. auto s = out.str();
  981. std::unique_ptr<COutputStream> stream = saver.addFile(filename);
  982. if(stream->write(reinterpret_cast<const ui8 *>(s.c_str()), s.size()) != s.size())
  983. throw std::runtime_error("CMapSaverJson::saveHeader() zip compression failed.");
  984. }
  985. }
  986. void CMapSaverJson::saveMap(const std::unique_ptr<CMap>& map)
  987. {
  988. this->map = map.get();
  989. this->mapHeader = this->map;
  990. writeHeader();
  991. writeTerrain();
  992. writeObjects();
  993. }
  994. void CMapSaverJson::writeHeader()
  995. {
  996. logGlobal->trace("Saving header");
  997. JsonNode header;
  998. JsonSerializer handler(mapObjectResolver.get(), header);
  999. header["versionMajor"].Float() = VERSION_MAJOR;
  1000. header["versionMinor"].Float() = VERSION_MINOR;
  1001. //write mods
  1002. header["mods"] = ModVerificationInfo::jsonSerializeList(mapHeader->mods);
  1003. //todo: multilevel map save support
  1004. JsonNode & levels = header["mapLevels"];
  1005. levels["surface"]["height"].Float() = mapHeader->height;
  1006. levels["surface"]["width"].Float() = mapHeader->width;
  1007. levels["surface"]["index"].Float() = 0;
  1008. if(mapHeader->twoLevel)
  1009. {
  1010. levels["underground"]["height"].Float() = mapHeader->height;
  1011. levels["underground"]["width"].Float() = mapHeader->width;
  1012. levels["underground"]["index"].Float() = 1;
  1013. }
  1014. serializeHeader(handler);
  1015. writeTriggeredEvents(handler);
  1016. writeTeams(handler);
  1017. writeOptions(handler);
  1018. writeTranslations();
  1019. addToArchive(header, HEADER_FILE_NAME);
  1020. }
  1021. std::string CMapSaverJson::writeTerrainTile(const TerrainTile & tile)
  1022. {
  1023. using namespace TerrainDetail;
  1024. std::ostringstream out;
  1025. out.setf(std::ios::dec, std::ios::basefield);
  1026. out.unsetf(std::ios::showbase);
  1027. out << tile.terType->shortIdentifier << static_cast<int>(tile.terView) << flipCodes[tile.extTileFlags % 4];
  1028. if(tile.roadType->getId() != Road::NO_ROAD)
  1029. out << tile.roadType->shortIdentifier << static_cast<int>(tile.roadDir) << flipCodes[(tile.extTileFlags >> 4) % 4];
  1030. if(tile.riverType->getId() != River::NO_RIVER)
  1031. out << tile.riverType->shortIdentifier << static_cast<int>(tile.riverDir) << flipCodes[(tile.extTileFlags >> 2) % 4];
  1032. return out.str();
  1033. }
  1034. JsonNode CMapSaverJson::writeTerrainLevel(const int index)
  1035. {
  1036. JsonNode data;
  1037. int3 pos(0,0,index);
  1038. data.Vector().resize(map->height);
  1039. for(pos.y = 0; pos.y < map->height; pos.y++)
  1040. {
  1041. JsonNode & row = data.Vector()[pos.y];
  1042. row.Vector().resize(map->width);
  1043. for(pos.x = 0; pos.x < map->width; pos.x++)
  1044. row.Vector()[pos.x].String() = writeTerrainTile(map->getTile(pos));
  1045. }
  1046. return data;
  1047. }
  1048. void CMapSaverJson::writeTerrain()
  1049. {
  1050. logGlobal->trace("Saving terrain");
  1051. //todo: multilevel map save support
  1052. JsonNode surface = writeTerrainLevel(0);
  1053. addToArchive(surface, TERRAIN_FILE_NAMES[0]);
  1054. if(map->twoLevel)
  1055. {
  1056. JsonNode underground = writeTerrainLevel(1);
  1057. addToArchive(underground, TERRAIN_FILE_NAMES[1]);
  1058. }
  1059. }
  1060. void CMapSaverJson::writeObjects()
  1061. {
  1062. logGlobal->trace("Saving objects");
  1063. JsonNode data;
  1064. JsonSerializer handler(mapObjectResolver.get(), data);
  1065. for(CGObjectInstance * obj : map->objects)
  1066. {
  1067. //logGlobal->trace("\t%s", obj->instanceName);
  1068. auto temp = handler.enterStruct(obj->instanceName);
  1069. obj->serializeJson(handler);
  1070. }
  1071. if(map->grailPos.valid())
  1072. {
  1073. JsonNode grail;
  1074. grail["type"].String() = "grail";
  1075. grail["x"].Float() = map->grailPos.x;
  1076. grail["y"].Float() = map->grailPos.y;
  1077. grail["l"].Float() = map->grailPos.z;
  1078. grail["options"]["radius"].Float() = map->grailRadius;
  1079. std::string grailId = boost::str(boost::format("grail_%d") % map->objects.size());
  1080. data[grailId] = grail;
  1081. }
  1082. //cleanup empty options
  1083. for(auto & p : data.Struct())
  1084. {
  1085. JsonNode & obj = p.second;
  1086. if(obj["options"].Struct().empty())
  1087. obj.Struct().erase("options");
  1088. }
  1089. addToArchive(data, OBJECTS_FILE_NAME);
  1090. }
  1091. void CMapSaverJson::writeTranslations()
  1092. {
  1093. for(auto & s : mapHeader->translations.Struct())
  1094. {
  1095. auto & language = s.first;
  1096. if(Languages::getLanguageOptions(language).identifier.empty())
  1097. {
  1098. logGlobal->error("Serializing of unsupported language %s is not permitted", language);
  1099. continue;
  1100. }
  1101. logGlobal->trace("Saving translations, language: %s", language);
  1102. addToArchive(s.second, language + ".json");
  1103. }
  1104. }
  1105. VCMI_LIB_NAMESPACE_END