1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-11-26 08:41:13 +02:00
vcmi/lib/mapping/MapFormatJson.cpp

925 lines
24 KiB
C++
Raw Normal View History

/*
* MapFormatJson.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "MapFormatJson.h"
2015-08-08 17:35:54 +02:00
#include "../filesystem/CInputStream.h"
#include "../filesystem/COutputStream.h"
#include "CMap.h"
#include "../CModHandler.h"
2015-12-05 11:04:00 +02:00
#include "../CHeroHandler.h"
#include "../CTownHandler.h"
#include "../VCMI_Lib.h"
#include "../mapObjects/ObjectTemplate.h"
#include "../mapObjects/CObjectHandler.h"
#include "../mapObjects/CObjectClassesHandler.h"
2015-12-05 12:56:38 +02:00
#include "../mapObjects/CGHeroInstance.h"
#include "../mapObjects/CGTownInstance.h"
#include "../StringConstants.h"
2016-02-13 09:47:40 +02:00
#include "../serializer/JsonDeserializer.h"
#include "../serializer/JsonSerializer.h"
namespace HeaderDetail
{
static const std::map<std::string, ui8> difficultyReverseMap =
{
{"", 1},
{"EASY", 0},
{"NORMAL", 1},
{"HARD", 2},
{"EXPERT", 3},
{"IMPOSSIBLE", 4}
};
static const std::map<ui8, std::string> difficultyForwardMap =
{
{0, "EASY"},
{1, "NORMAL"},
{2, "HARD"},
{3, "EXPERT"},
{4, "IMPOSSIBLE"}
};
}
2015-08-18 01:21:35 +02:00
namespace TriggeredEventsDetail
{
2015-08-18 01:21:35 +02:00
static const std::array<std::string, 12> conditionNames =
{
2015-08-18 01:21:35 +02:00
"haveArtifact", "haveCreatures", "haveResources", "haveBuilding",
"control", "destroy", "transport", "daysPassed",
"isHuman", "daysWithoutTown", "standardWin", "constValue"
};
2015-08-18 01:21:35 +02:00
static const std::array<std::string, 2> typeNames = { "victory", "defeat" };
2015-08-18 01:21:35 +02:00
static EventCondition JsonToCondition(const JsonNode & node)
{
2016-02-10 12:24:03 +02:00
//todo: support of new condition format
2015-08-18 01:21:35 +02:00
EventCondition event;
2016-02-10 12:24:03 +02:00
const auto & conditionName = node.Vector()[0].String();
auto pos = vstd::find_pos(conditionNames, conditionName);
2016-02-13 09:47:40 +02:00
event.condition = EventCondition::EWinLoseType(pos);
2015-08-18 01:21:35 +02:00
if (node.Vector().size() > 1)
{
2015-08-18 01:21:35 +02:00
const JsonNode & data = node.Vector()[1];
if (data["type"].getType() == JsonNode::DATA_STRING)
2016-02-10 12:24:03 +02:00
{
auto identifier = VLC->modh->identifiers.getIdentifier(data["type"]);
if(identifier)
event.objectType = identifier.get();
else
throw std::runtime_error("Identifier resolution failed in event condition");
}
2015-08-18 01:21:35 +02:00
if (data["type"].getType() == JsonNode::DATA_FLOAT)
event.objectType = data["type"].Float();
if (!data["value"].isNull())
event.value = data["value"].Float();
if (!data["position"].isNull())
{
auto & position = data["position"].Vector();
event.position.x = position.at(0).Float();
event.position.y = position.at(1).Float();
event.position.z = position.at(2).Float();
}
}
2015-08-18 01:21:35 +02:00
return event;
}
2015-08-18 01:21:35 +02:00
static JsonNode ConditionToJson(const EventCondition& event)
{
2015-08-18 01:21:35 +02:00
JsonNode json;
JsonVector& asVector = json.Vector();
JsonNode condition;
condition.String() = conditionNames.at(event.condition);
asVector.push_back(condition);
JsonNode data;
//todo: save identifier
if(event.objectType != -1)
data["type"].Float() = event.objectType;
2015-08-18 01:21:35 +02:00
if(event.value != -1)
data["value"].Float() = event.value;
if(event.position != int3(-1,-1,-1))
{
auto & position = data["position"].Vector();
position.resize(3);
position[0].Float() = event.position.x;
position[1].Float() = event.position.y;
position[2].Float() = event.position.z;
}
if(!data.isNull())
asVector.push_back(data);
2015-08-14 04:22:24 +02:00
2015-08-18 01:21:35 +02:00
return std::move(json);
}
}//namespace TriggeredEventsDetail
2015-08-18 01:21:35 +02:00
namespace TerrainDetail
{
static const std::array<std::string, 10> terrainCodes =
{
"dt", "sa", "gr", "sn", "sw", "rg", "sb", "lv", "wt", "rc"
};
2015-08-18 01:21:35 +02:00
static const std::array<std::string, 4> roadCodes =
{
"", "pd", "pg", "pc"
};
2015-08-18 01:21:35 +02:00
static const std::array<std::string, 5> riverCodes =
{
"", "rw", "ri", "rm", "rl"
};
2015-08-18 01:21:35 +02:00
static const std::array<char, 10> flipCodes =
{
'_', '-', '|', '+'
2015-08-18 01:21:35 +02:00
};
}
static std::string tailString(const std::string & input, char separator)
{
std::string ret;
size_t splitPos = input.find(separator);
if (splitPos != std::string::npos)
ret = input.substr(splitPos + 1);
return ret;
}
static si32 extractNumber(const std::string & input, char separator)
{
std::string tmp = tailString(input, separator);
return atoi(tmp.c_str());
}
///CMapFormatJson
const int CMapFormatJson::VERSION_MAJOR = 1;
const int CMapFormatJson::VERSION_MINOR = 0;
2015-08-11 20:20:13 +02:00
const std::string CMapFormatJson::HEADER_FILE_NAME = "header.json";
const std::string CMapFormatJson::OBJECTS_FILE_NAME = "objects.json";
2015-08-11 20:20:13 +02:00
2016-02-13 14:22:26 +02:00
void CMapFormatJson::readTriggeredEvents(JsonDeserializer & handler)
{
2016-02-13 14:22:26 +02:00
const JsonNode & input = handler.getCurrent();
mapHeader->victoryMessage = input["victoryString"].String();
mapHeader->victoryIconIndex = input["victoryIconIndex"].Float();
mapHeader->defeatMessage = input["defeatString"].String();
2015-08-18 01:21:35 +02:00
mapHeader->defeatIconIndex = input["defeatIconIndex"].Float();
mapHeader->triggeredEvents.clear();
for (auto & entry : input["triggeredEvents"].Struct())
{
TriggeredEvent event;
event.identifier = entry.first;
readTriggeredEvent(event, entry.second);
mapHeader->triggeredEvents.push_back(event);
}
}
void CMapFormatJson::readTriggeredEvent(TriggeredEvent & event, const JsonNode & source)
{
using namespace TriggeredEventsDetail;
event.onFulfill = source["message"].String();
event.description = source["description"].String();
event.effect.type = vstd::find_pos(typeNames, source["effect"]["type"].String());
event.effect.toOtherMessage = source["effect"]["messageToSend"].String();
event.trigger = EventExpression(source["condition"], JsonToCondition); // logical expression
}
2015-08-14 04:22:24 +02:00
void CMapFormatJson::writeTriggeredEvents(JsonNode& output)
{
2016-02-13 14:22:26 +02:00
output["victoryString"].String() = mapHeader->victoryMessage;
output["victoryIconIndex"].Float() = mapHeader->victoryIconIndex;
2015-08-14 04:22:24 +02:00
2016-02-13 14:22:26 +02:00
output["defeatString"].String() = mapHeader->defeatMessage;
output["defeatIconIndex"].Float() = mapHeader->defeatIconIndex;
2015-08-18 01:21:35 +02:00
JsonMap & triggeredEvents = output["triggeredEvents"].Struct();
2015-08-18 01:21:35 +02:00
2016-02-13 14:22:26 +02:00
for(auto event : mapHeader->triggeredEvents)
writeTriggeredEvent(event, triggeredEvents[event.identifier]);
2015-08-14 04:22:24 +02:00
}
void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent& event, JsonNode& dest)
{
using namespace TriggeredEventsDetail;
2015-08-14 04:22:24 +02:00
dest["message"].String() = event.onFulfill;
dest["description"].String() = event.description;
2015-08-18 01:21:35 +02:00
2015-08-15 17:46:29 +02:00
dest["effect"]["type"].String() = typeNames.at(size_t(event.effect.type));
2015-08-14 04:22:24 +02:00
dest["effect"]["messageToSend"].String() = event.effect.toOtherMessage;
2015-08-18 01:21:35 +02:00
dest["condition"] = event.trigger.toJson(ConditionToJson);
2015-08-14 04:22:24 +02:00
}
///CMapPatcher
CMapPatcher::CMapPatcher(JsonNode stream):
input(stream)
{
}
void CMapPatcher::patchMapHeader(std::unique_ptr<CMapHeader> & header)
{
2016-02-13 14:22:26 +02:00
map = nullptr;
mapHeader = header.get();
if (!input.isNull())
readPatchData();
}
void CMapPatcher::readPatchData()
{
2016-02-13 14:22:26 +02:00
JsonDeserializer handler(input);
readTriggeredEvents(handler);
}
///CMapLoaderJson
2016-02-10 06:28:00 +02:00
CMapLoaderJson::CMapLoaderJson(CInputStream * stream):
buffer(stream),
ioApi(new CProxyROIOApi(buffer)),
2015-08-18 01:21:35 +02:00
loader("", "_", ioApi)
{
2015-08-18 01:21:35 +02:00
}
si32 CMapLoaderJson::getIdentifier(const std::string& type, const std::string& name)
{
boost::optional<si32> res = VLC->modh->identifiers.getIdentifier("core", type, name, false);
if(!res)
{
throw new std::runtime_error("Map load failed. Identifier not resolved.");
}
return res.get();
}
std::unique_ptr<CMap> CMapLoaderJson::loadMap()
{
2016-02-10 07:59:24 +02:00
LOG_TRACE(logGlobal);
2016-02-13 14:22:26 +02:00
std::unique_ptr<CMap> result = std::unique_ptr<CMap>(new CMap());
map = result.get();
mapHeader = map;
readMap();
2016-02-13 14:22:26 +02:00
return std::move(result);
}
std::unique_ptr<CMapHeader> CMapLoaderJson::loadMapHeader()
{
2016-02-10 07:59:24 +02:00
LOG_TRACE(logGlobal);
2016-02-13 14:22:26 +02:00
map = nullptr;
std::unique_ptr<CMapHeader> result = std::unique_ptr<CMapHeader>(new CMapHeader());
mapHeader = result.get();
readHeader();
2016-02-13 14:22:26 +02:00
return std::move(result);
}
2016-02-13 09:47:40 +02:00
const JsonNode CMapLoaderJson::getFromArchive(const std::string & archiveFilename)
{
ResourceID resource(archiveFilename, EResType::TEXT);
2015-08-18 01:21:35 +02:00
if(!loader.existsResource(resource))
throw new std::runtime_error(archiveFilename+" not found");
2015-08-18 01:21:35 +02:00
auto data = loader.load(resource)->readAll();
2015-08-18 01:21:35 +02:00
JsonNode res(reinterpret_cast<char*>(data.first.get()), data.second);
2015-08-18 01:21:35 +02:00
return std::move(res);
}
void CMapLoaderJson::readMap()
{
2016-02-10 07:59:24 +02:00
LOG_TRACE(logGlobal);
readHeader();
map->initTerrain();
readTerrain();
readObjects();
// Calculate blocked / visitable positions
for(auto & elem : map->objects)
{
map->addBlockVisTiles(elem);
}
map->calculateGuardingGreaturePositions();
}
void CMapLoaderJson::readHeader()
{
//do not use map field here, use only mapHeader
2016-02-13 09:47:40 +02:00
JsonNode header = getFromArchive(HEADER_FILE_NAME);
JsonDeserializer handler(header);
mapHeader->version = EMapFormat::VCMI;//todo: new version field
2015-08-18 01:21:35 +02:00
//todo: multilevel map load support
2016-02-13 09:47:40 +02:00
{
auto levels = handler.enterStruct("mapLevels");
{
auto surface = levels.enterStruct("surface");
mapHeader->height = surface.get()["height"].Float();
mapHeader->width = surface.get()["width"].Float();
}
{
auto underground = levels.enterStruct("underground");
mapHeader->twoLevel = !underground.get().isNull();
}
}
mapHeader->name = header["name"].String();
mapHeader->description = header["description"].String();
2015-08-18 01:21:35 +02:00
//todo: support arbitrary percentage
2015-08-18 01:21:35 +02:00
2016-02-13 09:47:40 +02:00
mapHeader->difficulty = HeaderDetail::difficultyReverseMap.at(header["difficulty"].String());
mapHeader->levelLimit = header["heroLevelLimit"].Float();
2015-08-18 01:21:35 +02:00
// std::vector<bool> allowedHeroes;
2015-08-18 01:21:35 +02:00
// std::vector<ui16> placeholdedHeroes;
2016-02-13 14:22:26 +02:00
readTriggeredEvents(handler);
2016-02-13 09:47:40 +02:00
readPlayerInfo(handler);
readTeams(handler);
2015-08-08 18:16:33 +02:00
//TODO: readHeader
}
2016-02-13 09:47:40 +02:00
void CMapLoaderJson::readPlayerInfo(JsonDeserializer & handler)
{
2016-02-13 09:47:40 +02:00
auto playersData = handler.enterStruct("players");
for(int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
{
2016-02-10 06:28:00 +02:00
PlayerInfo & info = mapHeader->players.at(player);
2016-02-13 09:47:40 +02:00
auto playerData = playersData.enterStruct(GameConstants::PLAYER_COLOR_NAMES[player]);
2016-02-13 09:47:40 +02:00
if(playerData.get().isNull())
{
info.canComputerPlay = false;
info.canHumanPlay = false;
}
else
{
2016-02-13 09:47:40 +02:00
//allowed factions
2016-02-13 09:47:40 +02:00
// info.isFactionRandom =
2015-11-13 12:08:25 +02:00
2016-02-13 09:47:40 +02:00
info.canComputerPlay = true;
info.canHumanPlay = playerData.get()["canPlay"].String() != "AIOnly";
2016-02-13 09:47:40 +02:00
//placedHeroes
2016-02-13 09:47:40 +02:00
//mainTown
2016-02-13 09:47:40 +02:00
info.generateHeroAtMainTown = playerData.get()["generateHeroAtMainTown"].Bool();
2016-02-13 09:47:40 +02:00
//mainHero
2016-02-13 09:47:40 +02:00
//mainHeroPortrait
2016-02-13 09:47:40 +02:00
//mainCustomHeroName
}
}
}
2016-02-13 09:47:40 +02:00
void CMapLoaderJson::readTeams(JsonDeserializer & handler)
{
2016-02-13 09:47:40 +02:00
auto teamsData = handler.enterStruct("teams");
const JsonNode & src = teamsData.get();
if(src.getType() != JsonNode::DATA_VECTOR)
{
// No alliances
if(src.getType() != JsonNode::DATA_NULL)
logGlobal->errorStream() << "Invalid teams field type";
mapHeader->howManyTeams = 0;
for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
{
if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
{
mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
}
}
}
else
{
const JsonVector & srcVector = src.Vector();
mapHeader->howManyTeams = srcVector.size();
for(int team = 0; team < mapHeader->howManyTeams; team++)
{
for(const JsonNode & playerData : srcVector[team].Vector())
{
2015-12-05 11:04:00 +02:00
PlayerColor player = PlayerColor(vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, playerData.String()));
if(player.isValidPlayer())
{
2016-02-10 06:28:00 +02:00
if(mapHeader->players[player.getNum()].canAnyonePlay())
2015-11-13 12:08:25 +02:00
{
2016-02-10 06:28:00 +02:00
mapHeader->players[player.getNum()].team = TeamID(team);
2015-11-13 12:08:25 +02:00
}
}
}
}
2015-11-13 12:08:25 +02:00
2016-02-10 06:28:00 +02:00
for(PlayerInfo & player : mapHeader->players)
2015-11-13 12:08:25 +02:00
{
if(player.canAnyonePlay() && player.team == TeamID::NO_TEAM)
player.team = TeamID(mapHeader->howManyTeams++);
}
}
}
void CMapLoaderJson::readTerrainTile(const std::string& src, TerrainTile& tile)
{
using namespace TerrainDetail;
{//terrain type
const std::string typeCode = src.substr(0,2);
int rawType = vstd::find_pos(terrainCodes, typeCode);
if(rawType < 0)
throw new std::runtime_error("Invalid terrain type code in "+src);
tile.terType = ETerrainType(rawType);
2015-08-18 01:21:35 +02:00
}
int startPos = 2; //0+typeCode fixed length
{//terrain view
2015-08-18 01:21:35 +02:00
int pos = startPos;
while(isdigit(src.at(pos)))
2015-08-18 01:21:35 +02:00
pos++;
int len = pos - startPos;
if(len<=0)
2015-08-18 01:21:35 +02:00
throw new std::runtime_error("Invalid terrain view in "+src);
const std::string rawCode = src.substr(startPos,len);
tile.terView = atoi(rawCode.c_str());
startPos+=len;
}
{//terrain flip
2015-08-18 01:21:35 +02:00
int terrainFlip = vstd::find_pos(flipCodes, src.at(startPos++));
if(terrainFlip < 0)
throw new std::runtime_error("Invalid terrain flip in "+src);
else
2015-08-18 01:21:35 +02:00
tile.extTileFlags = terrainFlip;
}
if(startPos >= src.size())
return;
bool hasRoad = true;
{//road type
const std::string typeCode = src.substr(startPos,2);
startPos+=2;
int rawType = vstd::find_pos(roadCodes, typeCode);
if(rawType < 0)
{
rawType = vstd::find_pos(riverCodes, typeCode);
if(rawType < 0)
throw new std::runtime_error("Invalid river type in "+src);
else
{
tile.riverType = ERiverType::ERiverType(rawType);
hasRoad = false;
2015-08-18 01:21:35 +02:00
}
}
else
tile.roadType = ERoadType::ERoadType(rawType);
}
if(hasRoad)
{//road dir
int pos = startPos;
while(isdigit(src.at(pos)))
2015-08-18 01:21:35 +02:00
pos++;
int len = pos - startPos;
if(len<=0)
2015-08-18 01:21:35 +02:00
throw new std::runtime_error("Invalid road dir in "+src);
const std::string rawCode = src.substr(startPos,len);
tile.roadDir = atoi(rawCode.c_str());
startPos+=len;
}
if(hasRoad)
{//road flip
2015-08-18 01:21:35 +02:00
int flip = vstd::find_pos(flipCodes, src.at(startPos++));
if(flip < 0)
throw new std::runtime_error("Invalid road flip in "+src);
else
2015-08-18 01:21:35 +02:00
tile.extTileFlags |= (flip<<4);
}
if(startPos >= src.size())
2015-08-18 01:21:35 +02:00
return;
if(hasRoad)
{//river type
const std::string typeCode = src.substr(startPos,2);
2015-08-18 01:21:35 +02:00
startPos+=2;
int rawType = vstd::find_pos(riverCodes, typeCode);
if(rawType < 0)
throw new std::runtime_error("Invalid river type in "+src);
2015-08-18 01:21:35 +02:00
tile.riverType = ERiverType::ERiverType(rawType);
}
{//river dir
int pos = startPos;
while(isdigit(src.at(pos)))
2015-08-18 01:21:35 +02:00
pos++;
int len = pos - startPos;
if(len<=0)
2015-08-18 01:21:35 +02:00
throw new std::runtime_error("Invalid river dir in "+src);
const std::string rawCode = src.substr(startPos,len);
tile.riverDir = atoi(rawCode.c_str());
startPos+=len;
}
{//river flip
int flip = vstd::find_pos(flipCodes, src.at(startPos++));
if(flip < 0)
throw new std::runtime_error("Invalid road flip in "+src);
else
2015-08-18 01:21:35 +02:00
tile.extTileFlags |= (flip<<2);
}
}
void CMapLoaderJson::readTerrainLevel(const JsonNode& src, const int index)
{
int3 pos(0,0,index);
2015-08-18 01:21:35 +02:00
const JsonVector & rows = src.Vector();
2015-08-18 01:21:35 +02:00
if(rows.size() != map->height)
throw new std::runtime_error("Invalid terrain data");
2015-08-18 01:21:35 +02:00
for(pos.y = 0; pos.y < map->height; pos.y++)
{
const JsonVector & tiles = rows[pos.y].Vector();
2015-08-18 01:21:35 +02:00
if(tiles.size() != map->width)
2015-08-18 01:21:35 +02:00
throw new std::runtime_error("Invalid terrain data");
for(pos.x = 0; pos.x < map->width; pos.x++)
readTerrainTile(tiles[pos.x].String(), map->getTile(pos));
2015-08-18 01:21:35 +02:00
}
}
void CMapLoaderJson::readTerrain()
{
{
2016-02-13 09:47:40 +02:00
const JsonNode surface = getFromArchive("surface_terrain.json");
2015-08-18 01:21:35 +02:00
readTerrainLevel(surface, 0);
}
if(map->twoLevel)
{
2016-02-13 09:47:40 +02:00
const JsonNode underground = getFromArchive("underground_terrain.json");
2015-08-18 01:21:35 +02:00
readTerrainLevel(underground, 1);
}
2015-08-18 01:21:35 +02:00
}
CMapLoaderJson::MapObjectLoader::MapObjectLoader(CMapLoaderJson * _owner, const JsonMap::value_type& json):
2016-02-13 16:16:00 +02:00
owner(_owner), instance(nullptr),id(-1), jsonKey(json.first), configuration(json.second), internalId(extractNumber(jsonKey, '_'))
{
}
void CMapLoaderJson::MapObjectLoader::construct()
{
2016-02-13 16:16:00 +02:00
logGlobal->debugStream() <<"Loading: " <<jsonKey;
//TODO:consider move to ObjectTypeHandler
//find type handler
std::string typeName = configuration["type"].String(), subTypeName = configuration["subType"].String();
if(typeName.empty())
{
logGlobal->errorStream() << "Object type missing";
2016-02-10 07:59:24 +02:00
logGlobal->traceStream() << configuration;
return;
}
2016-02-13 16:16:00 +02:00
2016-01-24 01:26:32 +02:00
//special case for grail
if(typeName == "grail")
{
auto & pos = owner->map->grailPos;
pos.x = configuration["x"].Float();
pos.y = configuration["y"].Float();
pos.z = configuration["l"].Float();
2016-02-04 11:28:12 +02:00
owner->map->grailRadius = configuration["options"]["grailRadius"].Float();
2016-02-13 16:16:00 +02:00
return;
}
else if(subTypeName.empty())
{
logGlobal->errorStream() << "Object subType missing";
logGlobal->traceStream() << configuration;
return;
2016-01-24 01:26:32 +02:00
}
2016-02-13 16:16:00 +02:00
auto handler = VLC->objtypeh->getHandlerFor(typeName, subTypeName);
instance = handler->create(ObjectTemplate());
instance->id = ObjectInstanceID(owner->map->objects.size());
owner->map->objects.push_back(instance);
}
void CMapLoaderJson::MapObjectLoader::configure()
{
2016-01-24 01:26:32 +02:00
if(nullptr == instance)
return;
2016-01-15 19:24:17 +02:00
instance->readJson(configuration);
2015-12-05 11:04:00 +02:00
if(instance->ID == Obj::TOWN)
{
owner->map->towns.push_back(static_cast<CGTownInstance *>(instance));
}
if(instance->ID == Obj::HERO)
{
logGlobal->debugStream() << "Hero: " << VLC->heroh->heroes[instance->subID]->name << " at " << instance->pos;
2015-12-05 12:56:38 +02:00
owner->map->heroesOnMap.push_back(static_cast<CGHeroInstance *>(instance));
2015-12-05 11:04:00 +02:00
}
}
void CMapLoaderJson::readObjects()
{
LOG_TRACE(logGlobal);
std::vector<std::unique_ptr<MapObjectLoader>> loaders;//todo: optimize MapObjectLoader memory layout
2016-02-13 09:47:40 +02:00
const JsonNode data = getFromArchive(OBJECTS_FILE_NAME);
//get raw data
for(const auto & p : data.Struct())
loaders.push_back(vstd::make_unique<MapObjectLoader>(this, p));
auto sortInfos = [](const std::unique_ptr<MapObjectLoader> & lhs, const std::unique_ptr<MapObjectLoader> & rhs) -> bool
{
return lhs->internalId < rhs->internalId;
};
boost::sort(loaders, sortInfos);//this makes instance ids consistent after save-load, needed for testing
//todo: use internalId in CMap
for(auto & ptr : loaders)
ptr->construct();
//configure objects after all objects are constructed so we may resolve internal IDs even to actual pointers OTF
for(auto & ptr : loaders)
ptr->configure();
}
2015-08-08 16:30:19 +02:00
///CMapSaverJson
2015-08-11 20:20:13 +02:00
CMapSaverJson::CMapSaverJson(CInputOutputStream * stream):
2016-02-10 06:28:00 +02:00
buffer(stream),
ioApi(new CProxyIOApi(buffer)),
2015-08-11 20:20:13 +02:00
saver(ioApi, "_")
2015-08-08 16:30:19 +02:00
{
2015-08-18 01:21:35 +02:00
2015-08-08 16:30:19 +02:00
}
2015-08-11 20:20:13 +02:00
CMapSaverJson::~CMapSaverJson()
{
2015-08-18 01:21:35 +02:00
2015-08-11 20:20:13 +02:00
}
2015-08-08 17:35:54 +02:00
void CMapSaverJson::addToArchive(const JsonNode& data, const std::string& filename)
{
std::ostringstream out;
out << data;
out.flush();
2015-08-18 01:21:35 +02:00
{
auto s = out.str();
std::unique_ptr<COutputStream> stream = saver.addFile(filename);
2015-08-18 01:21:35 +02:00
if (stream->write((const ui8*)s.c_str(), s.size()) != s.size())
throw new std::runtime_error("CMapSaverJson::saveHeader() zip compression failed.");
2015-08-18 01:21:35 +02:00
}
}
2015-08-08 17:35:54 +02:00
void CMapSaverJson::saveMap(const std::unique_ptr<CMap>& map)
{
2015-08-11 20:20:13 +02:00
this->map = map.get();
2016-02-13 14:22:26 +02:00
this->mapHeader = this->map;
2015-08-18 01:21:35 +02:00
writeHeader();
writeTerrain();
writeObjects();
2015-08-08 17:35:54 +02:00
}
void CMapSaverJson::writeHeader()
2015-08-11 20:20:13 +02:00
{
JsonNode header;
2016-02-13 09:47:40 +02:00
JsonSerializer handler(header);
header["versionMajor"].Float() = VERSION_MAJOR;
2015-08-18 01:21:35 +02:00
header["versionMinor"].Float() = VERSION_MINOR;
//todo: multilevel map save support
2015-08-13 23:42:01 +02:00
JsonNode & levels = header["mapLevels"];
2016-02-13 14:22:26 +02:00
levels["surface"]["height"].Float() = mapHeader->height;
levels["surface"]["width"].Float() = mapHeader->width;
levels["surface"]["index"].Float() = 0;
2015-08-18 01:21:35 +02:00
2016-02-13 14:22:26 +02:00
if(mapHeader->twoLevel)
{
2016-02-13 14:22:26 +02:00
levels["underground"]["height"].Float() = mapHeader->height;
levels["underground"]["width"].Float() = mapHeader->width;
levels["underground"]["index"].Float() = 1;
}
2015-08-18 01:21:35 +02:00
2016-02-13 14:22:26 +02:00
header["name"].String() = mapHeader->name;
header["description"].String() = mapHeader->description;
2015-08-18 01:21:35 +02:00
//todo: support arbitrary percentage
2016-02-13 14:22:26 +02:00
header["difficulty"].String() = HeaderDetail::difficultyForwardMap.at(mapHeader->difficulty);
header["heroLevelLimit"].Float() = mapHeader->levelLimit;
2015-08-18 01:21:35 +02:00
2015-08-14 04:22:24 +02:00
writeTriggeredEvents(header);
2015-08-18 01:21:35 +02:00
writePlayerInfo(header);
2015-08-18 01:21:35 +02:00
writeTeams(header);
//todo: allowedHeroes;
2015-08-18 01:21:35 +02:00
//todo: placeholdedHeroes;
addToArchive(header, HEADER_FILE_NAME);
}
void CMapSaverJson::writePlayerInfo(JsonNode & output)
{
JsonNode & dest = output["players"];
dest.setType(JsonNode::DATA_STRUCT);
for(int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
{
2016-02-13 14:22:26 +02:00
const PlayerInfo & info = mapHeader->players[player];
if(info.canAnyonePlay())
2015-08-20 05:16:31 +02:00
writePlayerInfo(info, dest[GameConstants::PLAYER_COLOR_NAMES[player]]);
}
}
void CMapSaverJson::writePlayerInfo(const PlayerInfo & info, JsonNode & output)
{
//allowed factions
2015-11-13 12:08:25 +02:00
output["canPlay"].String() = info.canHumanPlay ? "PlayerOrAI" : "AIOnly";
//mainTown
output["generateHeroAtMainTown"].Bool() = info.generateHeroAtMainTown;
//mainHero
2015-11-13 12:08:25 +02:00
//towns
//heroes
}
void CMapSaverJson::writeTeams(JsonNode& output)
{
JsonNode & dest = output["teams"];
std::vector<std::set<PlayerColor>> teamsData;
2016-02-13 14:22:26 +02:00
teamsData.resize(mapHeader->howManyTeams);
//get raw data
2016-02-13 14:22:26 +02:00
for(int idx = 0; idx < mapHeader->players.size(); idx++)
{
2016-02-13 14:22:26 +02:00
const PlayerInfo & player = mapHeader->players.at(idx);
int team = player.team.getNum();
2016-02-13 14:22:26 +02:00
if(vstd::iswithin(team, 0, mapHeader->howManyTeams-1) && player.canAnyonePlay())
teamsData.at(team).insert(PlayerColor(idx));
}
2016-02-13 09:47:40 +02:00
//remove single-member teams
vstd::erase_if(teamsData, [](std::set<PlayerColor> & elem) -> bool
{
return elem.size() <= 1;
});
2015-11-13 12:08:25 +02:00
//construct output
dest.setType(JsonNode::DATA_VECTOR);
for(const std::set<PlayerColor> & teamData : teamsData)
{
JsonNode team(JsonNode::DATA_VECTOR);
for(const PlayerColor & player : teamData)
{
JsonNode member(JsonNode::DATA_STRING);
member.String() = GameConstants::PLAYER_COLOR_NAMES[player.getNum()];
team.Vector().push_back(std::move(member));
}
dest.Vector().push_back(std::move(team));
}
}
const std::string CMapSaverJson::writeTerrainTile(const TerrainTile & tile)
{
using namespace TerrainDetail;
2015-08-11 20:20:13 +02:00
std::ostringstream out;
out.setf(std::ios::dec, std::ios::basefield);
out.unsetf(std::ios::showbase);
out << terrainCodes.at(int(tile.terType)) << (int)tile.terView << flipCodes[tile.extTileFlags % 4];
if(tile.roadType != ERoadType::NO_ROAD)
{
out << roadCodes.at(int(tile.roadType)) << (int)tile.roadDir << flipCodes[(tile.extTileFlags >> 4) % 4];
}
if(tile.riverType != ERiverType::NO_RIVER)
{
out << riverCodes.at(int(tile.riverType)) << (int)tile.riverDir << flipCodes[(tile.extTileFlags >> 2) % 4];
}
return out.str();
}
JsonNode CMapSaverJson::writeTerrainLevel(const int index)
{
JsonNode data;
int3 pos(0,0,index);
2015-08-18 01:21:35 +02:00
data.Vector().resize(map->height);
2015-08-18 01:21:35 +02:00
for(pos.y = 0; pos.y < map->height; pos.y++)
2015-08-11 20:20:13 +02:00
{
JsonNode & row = data.Vector()[pos.y];
2015-08-18 01:21:35 +02:00
row.Vector().resize(map->width);
2015-08-18 01:21:35 +02:00
for(pos.x = 0; pos.x < map->width; pos.x++)
row.Vector()[pos.x].String() = writeTerrainTile(map->getTile(pos));
}
2015-08-18 01:21:35 +02:00
return std::move(data);
}
void CMapSaverJson::writeTerrain()
{
2015-08-18 01:21:35 +02:00
//todo: multilevel map save support
JsonNode surface = writeTerrainLevel(0);
2015-08-20 05:16:31 +02:00
addToArchive(surface, "surface_terrain.json");
2015-08-18 01:21:35 +02:00
if(map->twoLevel)
{
JsonNode underground = writeTerrainLevel(1);
2015-08-20 05:16:31 +02:00
addToArchive(underground, "underground_terrain.json");
}
2015-08-11 20:20:13 +02:00
}
void CMapSaverJson::writeObjects()
{
JsonNode data(JsonNode::DATA_STRUCT);
for(const CGObjectInstance * obj : map->objects)
2016-01-15 19:24:17 +02:00
obj->writeJson(data[obj->getStringId()]);
2016-01-24 01:26:32 +02:00
if(map->grailPos.valid())
{
JsonNode grail(JsonNode::DATA_STRUCT);
grail["type"].String() = "grail";
grail["x"].Float() = map->grailPos.x;
grail["y"].Float() = map->grailPos.y;
grail["l"].Float() = map->grailPos.z;
2016-02-04 11:28:12 +02:00
grail["options"]["radius"].Float() = map->grailRadius;
2016-01-24 01:26:32 +02:00
std::string grailId = boost::str(boost::format("grail_%d") % map->objects.size());
data[grailId] = grail;
}
addToArchive(data, OBJECTS_FILE_NAME);
}