MapFormatJson.cpp 36 KB

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