/* * CTownHandler.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 "CTownHandler.h" #include "VCMI_Lib.h" #include "CGeneralTextHandler.h" #include "JsonNode.h" #include "StringConstants.h" #include "CCreatureHandler.h" #include "CModHandler.h" #include "CHeroHandler.h" #include "CArtHandler.h" #include "spells/CSpellHandler.h" #include "filesystem/Filesystem.h" #include "mapObjects/CObjectClassesHandler.h" #include "mapObjects/CObjectHandler.h" #include "HeroBonus.h" const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number const std::map CBuilding::MODES = { { "normal", CBuilding::BUILD_NORMAL }, { "auto", CBuilding::BUILD_AUTO }, { "special", CBuilding::BUILD_SPECIAL }, { "grail", CBuilding::BUILD_GRAIL } }; const std::map CBuilding::TOWER_TYPES = { { "low", CBuilding::HEIGHT_LOW }, { "average", CBuilding::HEIGHT_AVERAGE }, { "high", CBuilding::HEIGHT_HIGH }, { "skyship", CBuilding::HEIGHT_SKYSHIP } }; const std::string & CBuilding::Name() const { return name; } const std::string & CBuilding::Description() const { return description; } BuildingID CBuilding::getBase() const { const CBuilding * build = this; while (build->upgrade >= 0) { build = build->town->buildings.at(build->upgrade); } return build->bid; } si32 CBuilding::getDistance(BuildingID buildID) const { const CBuilding * build = town->buildings.at(buildID); int distance = 0; while (build->upgrade >= 0 && build != this) { build = build->town->buildings.at(build->upgrade); distance++; } if (build == this) return distance; return -1; } void CBuilding::deserializeFix() { //default value for mode was broken, have to fix it here for old saves (v777 and older) switch(mode) { case BUILD_NORMAL: case BUILD_AUTO: case BUILD_SPECIAL: case BUILD_GRAIL: break; default: mode = BUILD_NORMAL; break; } } void CBuilding::addNewBonus(std::shared_ptr b, BonusList & bonusList) { bonusList.push_back(b); } const JsonNode & CBuilding::getCurrentFactionForUpdateRoutine() const { const auto & faction = town->faction->identifier; const auto & factionsContent = (*VLC->modh->content)["factions"]; const auto & coreData = factionsContent.modData.at("core"); const auto & coreFactions = coreData.modData; const auto & currentFaction = coreFactions[faction]; if(currentFaction.isNull()) { const auto index = faction.find(':'); const std::string factionDir = index == std::string::npos ? faction : faction.substr(0, index); const auto it = factionsContent.modData.find(factionDir); if(it == factionsContent.modData.end()) { logMod->warn("Warning: Update old save failed: Faction: '%s' is not found.", factionDir); return currentFaction; } const std::string modFaction = index == std::string::npos ? faction : faction.substr(index + 1); return it->second.modData[modFaction]; } return currentFaction; } void CBuilding::update792() { subId = BuildingSubID::NONE; height = ETowerHeight::HEIGHT_NO_TOWER; if(!bid.IsSpecialOrGrail() || town == nullptr || town->faction == nullptr || town->faction->identifier.empty()) return; const auto buildingName = CTownHandler::getMappedValue(bid, std::string(), MappedKeys::BUILDING_TYPES_TO_NAMES); if(buildingName.empty()) return; auto & currentFaction = getCurrentFactionForUpdateRoutine(); if(!currentFaction.isNull() && currentFaction.getType() == JsonNode::JsonType::DATA_STRUCT) { const auto & buildings = currentFaction["town"]["buildings"]; const auto & currentBuilding = buildings[buildingName]; subId = CTownHandler::getMappedValue(currentBuilding["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS); height = subId == BuildingSubID::LOOKOUT_TOWER || bid == BuildingID::GRAIL ? CTownHandler::getMappedValue(currentBuilding["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES) : height = CBuilding::HEIGHT_NO_TOWER; } } void CBuilding::update794() { if(bid == BuildingID::TAVERN || subId == BuildingSubID::BROTHERHOOD_OF_SWORD) { VLC->townh->addBonusesForVanilaBuilding(this); return; } if(!bid.IsSpecialOrGrail()) return; VLC->townh->addBonusesForVanilaBuilding(this); if(!buildingBonuses.empty() //addBonusesForVanilaBuilding has done all work || town->faction == nullptr //or faction data is not valid || town->faction->identifier.empty()) return; const auto buildingName = CTownHandler::getMappedValue(bid, std::string(), MappedKeys::BUILDING_TYPES_TO_NAMES, false); if(buildingName.empty()) return; auto & currentFaction = getCurrentFactionForUpdateRoutine(); if(currentFaction.isNull() || currentFaction.getType() != JsonNode::JsonType::DATA_STRUCT) return; const auto & buildings = currentFaction["town"]["buildings"]; const auto & currentBuilding = buildings[buildingName]; CTownHandler::loadSpecialBuildingBonuses(currentBuilding["bonuses"], buildingBonuses, this); CTownHandler::loadSpecialBuildingBonuses(currentBuilding["onVisitBonuses"], onVisitBonuses, this); if(!onVisitBonuses.empty()) { if(subId == BuildingSubID::NONE) subId = BuildingSubID::CUSTOM_VISITING_BONUS; for(auto & bonus : onVisitBonuses) bonus->sid = Bonus::getSid32(town->faction->index, bid); } const auto & overriddenBids = currentBuilding["overrides"]; if(overriddenBids.isNull()) return; auto scope = town->getBuildingScope(); for(auto b : overriddenBids.Vector()) { auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get()); overrideBids.insert(bid); } } CFaction::CFaction() { town = nullptr; index = 0; alignment = EAlignment::NEUTRAL; } CFaction::~CFaction() { delete town; } int32_t CFaction::getIndex() const { return index; } int32_t CFaction::getIconIndex() const { return index; //??? } const std::string & CFaction::getName() const { return name; } const std::string & CFaction::getJsonKey() const { return identifier; } void CFaction::registerIcons(const IconRegistar & cb) const { if(town) { auto & info = town->clientInfo; cb(info.icons[0][0], "ITPT", info.iconLarge[0][0]); cb(info.icons[0][1], "ITPT", info.iconLarge[0][1]); cb(info.icons[1][0], "ITPT", info.iconLarge[1][0]); cb(info.icons[1][1], "ITPT", info.iconLarge[1][1]); cb(info.icons[0][0] + 2, "ITPA", info.iconSmall[0][0]); cb(info.icons[0][1] + 2, "ITPA", info.iconSmall[0][1]); cb(info.icons[1][0] + 2, "ITPA", info.iconSmall[1][0]); cb(info.icons[1][1] + 2, "ITPA", info.iconSmall[1][1]); } } FactionID CFaction::getId() const { return FactionID(index); } bool CFaction::hasTown() const { return town != nullptr; } void CFaction::updateFrom(const JsonNode & data) { } void CFaction::serializeJson(JsonSerializeFormat & handler) { } CTown::CTown() : faction(nullptr), mageLevel(0), primaryRes(0), moatDamage(0), defaultTavernChance(0) { } CTown::~CTown() { for(auto & build : buildings) build.second.dellNull(); for(auto & str : clientInfo.structures) str.dellNull(); } std::vector CTown::defaultMoatHexes() { static const std::vector moatHexes = {11, 28, 44, 61, 77, 111, 129, 146, 164, 181}; return moatHexes; } std::string CTown::getLocalizedFactionName() const { if(faction == nullptr) return "Random"; else return faction->name; } std::string CTown::getBuildingScope() const { if(faction == nullptr) //no faction == random faction return "building"; else return "building." + faction->identifier; } std::set CTown::getAllBuildings() const { std::set res; for(const auto & b : buildings) { res.insert(b.first.num); } return res; } const CBuilding * CTown::getSpecialBuilding(BuildingSubID::EBuildingSubID subID) const { for(const auto & kvp : buildings) { if(kvp.second->subId == subID) return buildings.at(kvp.first); } return nullptr; } BuildingID::EBuildingID CTown::getBuildingType(BuildingSubID::EBuildingSubID subID) const { auto building = getSpecialBuilding(subID); return building == nullptr ? BuildingID::NONE : building->bid.num; } const std::string CTown::getGreeting(BuildingSubID::EBuildingSubID subID) const { return VLC->townh->getMappedValue(subID, std::string(), specialMessages, false); } void CTown::setGreeting(BuildingSubID::EBuildingSubID subID, const std::string message) const { specialMessages.insert(std::pair(subID, message)); } CTownHandler::CTownHandler() { randomTown = new CTown(); } CTownHandler::~CTownHandler() { delete randomTown; } JsonNode readBuilding(CLegacyConfigParser & parser) { JsonNode ret; JsonNode & cost = ret["cost"]; //note: this code will try to parse mithril as well but wil always return 0 for it for(const std::string & resID : GameConstants::RESOURCE_NAMES) cost[resID].Float() = parser.readNumber(); cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator parser.endLine(); return ret; } TPropagatorPtr & CTownHandler::emptyPropagator() { static TPropagatorPtr emptyProp(nullptr); return emptyProp; } std::vector CTownHandler::loadLegacyData(size_t dataSize) { std::vector dest(dataSize); objects.resize(dataSize); auto getBuild = [&](size_t town, size_t building) -> JsonNode & { return dest[town]["town"]["buildings"][EBuildingType::names[building]]; }; CLegacyConfigParser parser("DATA/BUILDING.TXT"); parser.endLine(); // header parser.endLine(); //Unique buildings for (size_t town=0; town & bidsToLoad) { if (source.isNull()) return; BuildingRequirementsHelper hlp; hlp.building = building; hlp.town = building->town; hlp.json = source; bidsToLoad.push_back(hlp); } template R CTownHandler::getMappedValue(const K key, const R defval, const std::map & map, bool required) { auto it = map.find(key); if(it != map.end()) return it->second; if(required) logMod->warn("Warning: Property: '%s' is unknown. Correct the typo or update VCMI.", key); return defval; } template R CTownHandler::getMappedValue(const JsonNode & node, const R defval, const std::map & map, bool required) { if(!node.isNull() && node.getType() == JsonNode::JsonType::DATA_STRING) return getMappedValue(node.String(), defval, map, required); return defval; } void CTownHandler::addBonusesForVanilaBuilding(CBuilding * building) { std::shared_ptr b; static TPropagatorPtr playerPropagator = std::make_shared(CBonusSystemNode::ENodeTypes::PLAYER); if(building->subId == BuildingSubID::NONE) { if(building->bid == BuildingID::TAVERN) { b = createBonus(building, Bonus::MORALE, +1); } else if(building->bid == BuildingID::GRAIL && building->town->faction != nullptr && boost::algorithm::ends_with(building->town->faction->identifier, ":cove")) { static TPropagatorPtr allCreaturesPropagator(new CPropagatorNodeType(CBonusSystemNode::ENodeTypes::ALL_CREATURES)); static auto factionLimiter = std::make_shared(building->town->faction->index); b = createBonus(building, Bonus::NO_TERRAIN_PENALTY, 0, allCreaturesPropagator); b->addLimiter(factionLimiter); } } else { switch(building->subId) { case BuildingSubID::BROTHERHOOD_OF_SWORD: b = createBonus(building, Bonus::MORALE, +2); building->overrideBids.insert(BuildingID::TAVERN); break; case BuildingSubID::FOUNTAIN_OF_FORTUNE: b = createBonus(building, Bonus::LUCK, +2); break; case BuildingSubID::SPELL_POWER_GARRISON_BONUS: b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); break; case BuildingSubID::ATTACK_GARRISON_BONUS: b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); break; case BuildingSubID::DEFENSE_GARRISON_BONUS: b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); break; case BuildingSubID::LIGHTHOUSE: b = createBonus(building, Bonus::SEA_MOVEMENT, +500, playerPropagator); break; } } if(b) building->addNewBonus(b, building->buildingBonuses); } std::shared_ptr CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, int subtype) { return createBonus(build, type, val, emptyPropagator(), subtype); } std::shared_ptr CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype) { std::ostringstream descr; descr << build->name; return createBonusImpl(build->bid, type, val, prop, descr.str(), subtype); } std::shared_ptr CTownHandler::createBonusImpl(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, const std::string & description, int subtype) { auto b = std::make_shared(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, description, subtype); if(prop) b->addPropagator(prop); return b; } void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building) { for(auto b : source.Vector()) { auto bonus = JsonUtils::parseBuildingBonus(b, building->bid, building->name); if(bonus == nullptr) continue; if(bonus->limiter != nullptr) { auto limPtr = dynamic_cast(bonus->limiter.get()); if(limPtr != nullptr && limPtr->faction == (TFaction)-1) limPtr->faction = building->town->faction->index; } //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty. if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == CBonusSystemNode::ENodeTypes::UNKNOWN) bonus->addPropagator(emptyPropagator()); building->addNewBonus(bonus, bonusList); } } void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source) { auto ret = new CBuilding(); ret->bid = getMappedValue(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false); if(ret->bid == BuildingID::NONE) ret->bid = source["id"].isNull() ? BuildingID(BuildingID::NONE) : BuildingID(source["id"].Float()); if (ret->bid == BuildingID::NONE) logMod->error("Error: Building '%s' has not internal ID and won't work properly. Correct the typo or update VCMI.", stringID); ret->mode = ret->bid == BuildingID::GRAIL ? CBuilding::BUILD_GRAIL : getMappedValue(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES); ret->subId = getMappedValue(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS); ret->height = CBuilding::HEIGHT_NO_TOWER; if(ret->subId == BuildingSubID::LOOKOUT_TOWER || ret->bid == BuildingID::GRAIL) ret->height = getMappedValue(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES); ret->identifier = stringID; ret->town = town; ret->name = source["name"].String(); ret->description = source["description"].String(); ret->resources = TResources(source["cost"]); ret->produce = TResources(source["produce"]); if(ret->bid == BuildingID::TAVERN) addBonusesForVanilaBuilding(ret); else if(ret->bid.IsSpecialOrGrail()) { loadSpecialBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret); if(ret->buildingBonuses.empty()) addBonusesForVanilaBuilding(ret); loadSpecialBuildingBonuses(source["onVisitBonuses"], ret->onVisitBonuses, ret); if(!ret->onVisitBonuses.empty()) { if(ret->subId == BuildingSubID::NONE) ret->subId = BuildingSubID::CUSTOM_VISITING_BONUS; for(auto & bonus : ret->onVisitBonuses) bonus->sid = Bonus::getSid32(ret->town->faction->index, ret->bid); } } //MODS COMPATIBILITY FOR 0.96 if(!ret->produce.nonZero()) { switch (ret->bid) { break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500; break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000; break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000; break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000; break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000; break; case BuildingID::RESOURCE_SILO : { switch (ret->town->primaryRes) { case Res::GOLD: ret->produce[ret->town->primaryRes] = 500; break; case Res::WOOD_AND_ORE: ret->produce[Res::WOOD] = 1; ret->produce[Res::ORE] = 1; break; default: ret->produce[ret->town->primaryRes] = 1; break; } } } } loadBuildingRequirements(ret, source["requires"], requirementsToLoad); if(ret->bid.IsSpecialOrGrail()) loadBuildingRequirements(ret, source["overrides"], overriddenBidsToLoad); if (!source["upgrades"].isNull()) { // building id and upgrades can't be the same if(stringID == source["upgrades"].String()) { throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") % stringID % ret->town->getLocalizedFactionName())); } VLC->modh->identifiers.requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier) { ret->upgrade = BuildingID(identifier); }); } else ret->upgrade = BuildingID::NONE; ret->town->buildings[ret->bid] = ret; registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid); } void CTownHandler::loadBuildings(CTown * town, const JsonNode & source) { for(auto & node : source.Struct()) { if (!node.second.isNull()) { loadBuilding(town, node.first, node.second); } } } void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source) { auto ret = new CStructure(); ret->building = nullptr; ret->buildable = nullptr; VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable { ret->building = town.buildings[BuildingID(identifier)]; }); if (source["builds"].isNull()) { VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable { ret->building = town.buildings[BuildingID(identifier)]; }); } else { VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable { ret->buildable = town.buildings[BuildingID(identifier)]; }); } ret->identifier = stringID; ret->pos.x = static_cast(source["x"].Float()); ret->pos.y = static_cast(source["y"].Float()); ret->pos.z = static_cast(source["z"].Float()); ret->hiddenUpgrade = source["hidden"].Bool(); ret->defName = source["animation"].String(); ret->borderName = source["border"].String(); ret->areaName = source["area"].String(); town.clientInfo.structures.push_back(ret); } void CTownHandler::loadStructures(CTown &town, const JsonNode & source) { for(auto &node : source.Struct()) { if (!node.second.isNull()) loadStructure(town, node.first, node.second); } } void CTownHandler::loadTownHall(CTown &town, const JsonNode & source) { auto & dstSlots = town.clientInfo.hallSlots; auto & srcSlots = source.Vector(); dstSlots.resize(srcSlots.size()); for(size_t i=0; imodh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier) { dst = BuildingID(identifier); }); } } } } CTown::ClientInfo::Point JsonToPoint(const JsonNode & node) { CTown::ClientInfo::Point ret; ret.x = static_cast(node["x"].Float()); ret.y = static_cast(node["y"].Float()); return ret; } void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source) { town.clientInfo.siegePrefix = source["imagePrefix"].String(); VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature) { auto crId = CreatureID(creature); if(!(*VLC->creh)[crId]->animation.missleFrameAngles.size()) logMod->error("Mod '%s' error: Creature '%s' on the Archer's tower is not a shooter. Mod should be fixed. Siege will not work properly!" , town.faction->name , (*VLC->creh)[crId]->nameSing); town.clientInfo.siegeShooter = crId; }); auto & pos = town.clientInfo.siegePositions; pos.resize(21); pos[8] = JsonToPoint(source["towers"]["top"]["tower"]); pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]); pos[20] = JsonToPoint(source["towers"]["top"]["creature"]); pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]); pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]); pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]); pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]); pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]); pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]); pos[9] = JsonToPoint(source["gate"]["gate"]); pos[10] = JsonToPoint(source["gate"]["arch"]); pos[7] = JsonToPoint(source["walls"]["upper"]); pos[6] = JsonToPoint(source["walls"]["upperMid"]); pos[5] = JsonToPoint(source["walls"]["bottomMid"]); pos[4] = JsonToPoint(source["walls"]["bottom"]); pos[13] = JsonToPoint(source["moat"]["moat"]); pos[14] = JsonToPoint(source["moat"]["bank"]); pos[11] = JsonToPoint(source["static"]["bottom"]); pos[12] = JsonToPoint(source["static"]["top"]); pos[1] = JsonToPoint(source["static"]["background"]); } static void readIcon(JsonNode source, std::string & small, std::string & large) { if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format { small = source["small"].String(); large = source["large"].String(); } } void CTownHandler::loadClientData(CTown &town, const JsonNode & source) { CTown::ClientInfo & info = town.clientInfo; readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]); readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]); readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]); readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]); info.hallBackground = source["hallBackground"].String(); info.musicTheme = source["musicTheme"].String(); info.townBackground = source["townBackground"].String(); info.guildWindow = source["guildWindow"].String(); info.buildingsIcons = source["buildingsIcons"].String(); //left for back compatibility - will be removed later if (source["guildBackground"].String() != "") info.guildBackground = source["guildBackground"].String(); else info.guildBackground = "TPMAGE.bmp"; if (source["tavernVideo"].String() != "") info.tavernVideo = source["tavernVideo"].String(); else info.tavernVideo = "TAVERN.BIK"; //end of legacy assignment loadTownHall(town, source["hallSlots"]); loadStructures(town, source["structures"]); loadSiegeScreen(town, source["siege"]); } void CTownHandler::loadTown(CTown * town, const JsonNode & source) { auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String()); if(resIter == std::end(GameConstants::RESOURCE_NAMES)) town->primaryRes = Res::WOOD_AND_ORE; //Wood + Ore else town->primaryRes = static_cast(resIter - std::begin(GameConstants::RESOURCE_NAMES)); warMachinesToLoad[town] = source["warMachine"]; town->moatDamage = static_cast(source["moatDamage"].Float()); // Compatibility for <= 0.98f mods if(source["moatHexes"].isNull()) town->moatHexes = CTown::defaultMoatHexes(); else town->moatHexes = source["moatHexes"].convertTo >(); town->mageLevel = static_cast(source["mageGuild"].Float()); town->names = source["names"].convertTo >(); // Horde building creature level for(const JsonNode &node : source["horde"].Vector()) town->hordeLvl[(int)town->hordeLvl.size()] = static_cast(node.Float()); // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries // but anything below 2 must be handled here for (size_t i=source["horde"].Vector().size(); i<2; i++) town->hordeLvl[(int)i] = -1; const JsonVector & creatures = source["creatures"].Vector(); town->creatures.resize(creatures.size()); for (size_t i=0; i< creatures.size(); i++) { const JsonVector & level = creatures[i].Vector(); town->creatures[i].resize(level.size()); for (size_t j=0; jmodh->identifiers.requestIdentifier("creature", level[j], [=](si32 creature) { town->creatures[i][j] = CreatureID(creature); }); } } town->defaultTavernChance = static_cast(source["defaultTavern"].Float()); /// set chance of specific hero class to appear in this town for(auto &node : source["tavern"].Struct()) { int chance = static_cast(node.second.Float()); VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID) { VLC->heroh->classes[HeroClassID(classID)]->selectionProbability[town->faction->index] = chance; }); } for(auto &node : source["guildSpells"].Struct()) { int chance = static_cast(node.second.Float()); VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID) { VLC->spellh->objects.at(spellID)->probabilities[town->faction->index] = chance; }); } for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector()) { town->dwellings.push_back(d["graphics"].String()); town->dwellingNames.push_back(d["name"].String()); } loadBuildings(town, source["buildings"]); loadClientData(*town, source); } void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source) { faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES); std::string prefix = source["prefix"].String(); for(const JsonNode &piece : source["pieces"].Vector()) { size_t index = faction.puzzleMap.size(); SPuzzleInfo spi; spi.x = static_cast(piece["x"].Float()); spi.y = static_cast(piece["y"].Float()); spi.whenUncovered = static_cast(piece["index"].Float()); spi.number = static_cast(index); // filename calculation std::ostringstream suffix; suffix << std::setfill('0') << std::setw(2) << index; spi.filename = prefix + suffix.str(); faction.puzzleMap.push_back(spi); } assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES); } ETerrainType::EETerrainType CTownHandler::getDefaultTerrainForAlignment(EAlignment::EAlignment alignment) const { ETerrainType::EETerrainType terrain = defaultGoodTerrain; switch(alignment) { case EAlignment::EAlignment::EVIL: terrain = defaultEvilTerrain; break; case EAlignment::EAlignment::NEUTRAL: terrain = defaultNeutralTerrain; break; } return terrain; } CFaction * CTownHandler::loadFromJson(const std::string & scope, const JsonNode & source, const std::string & identifier, size_t index) { auto faction = new CFaction(); faction->index = index; faction->index = static_cast(index); faction->name = source["name"].String(); faction->identifier = identifier; faction->creatureBg120 = source["creatureBackground"]["120px"].String(); faction->creatureBg130 = source["creatureBackground"]["130px"].String(); int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String()); if (alignment == -1) faction->alignment = EAlignment::NEUTRAL; else faction->alignment = static_cast(alignment); auto nativeTerrain = source["nativeTerrain"]; int terrainNum = nativeTerrain.isNull() ? -1 : vstd::find_pos(GameConstants::TERRAIN_NAMES, nativeTerrain.String()); //Contructor is not called here, but operator= faction->nativeTerrain = terrainNum < 0 ? getDefaultTerrainForAlignment(faction->alignment) : static_cast(terrainNum); if (!source["town"].isNull()) { faction->town = new CTown(); faction->town->faction = faction; loadTown(faction->town, source["town"]); } else faction->town = nullptr; if (!source["puzzleMap"].isNull()) loadPuzzle(*faction, source["puzzleMap"]); return faction; } void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data) { auto object = loadFromJson(scope, data, normalizeIdentifier(scope, "core", name), objects.size()); objects.push_back(object); if (object->town) { auto & info = object->town->clientInfo; info.icons[0][0] = 8 + object->index * 4 + 0; info.icons[0][1] = 8 + object->index * 4 + 1; info.icons[1][0] = 8 + object->index * 4 + 2; info.icons[1][1] = 8 + object->index * 4 + 3; VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index) { // register town once objects are loaded JsonNode config = data["town"]["mapObject"]; config["faction"].String() = name; config["faction"].meta = scope; if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96 config.meta = scope; VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index); // MODS COMPATIBILITY FOR 0.96 auto & advMap = data["town"]["adventureMap"]; if (!advMap.isNull()) { logMod->warn("Outdated town mod. Will try to generate valid templates out of fort"); JsonNode config; config["animation"] = advMap["castle"]; VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config); } }); } registerObject(scope, "faction", name, object->index); } void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index) { auto object = loadFromJson(scope, data, normalizeIdentifier(scope, "core", name), index); if (objects.size() > index) assert(objects[index] == nullptr); // ensure that this id was not loaded before else objects.resize(index + 1); objects[index] = object; if (object->town) { auto & info = object->town->clientInfo; info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0; info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1; info.icons[1][0] = object->index * 2 + 0; info.icons[1][1] = object->index * 2 + 1; VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index) { // register town once objects are loaded JsonNode config = data["town"]["mapObject"]; config["faction"].String() = name; config["faction"].meta = scope; VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index); }); } registerObject(scope, "faction", name, object->index); } void CTownHandler::loadRandomFaction() { static const ResourceID randomFactionPath("config/factions/random.json"); JsonNode randomFactionJson(randomFactionPath); randomFactionJson.setMeta("core", true); loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]); } void CTownHandler::loadCustom() { loadRandomFaction(); } void CTownHandler::afterLoadFinalization() { initializeRequirements(); initializeOverridden(); initializeWarMachines(); } void CTownHandler::initializeRequirements() { // must be done separately after all ID's are known for (auto & requirement : requirementsToLoad) { requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID { if (node.Vector().size() > 1) { logMod->warn("Unexpected length of town buildings requirements: %d", node.Vector().size()); logMod->warn("Entry contains: "); logMod->warn(node.toJson()); } return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get()); }); } requirementsToLoad.clear(); } void CTownHandler::initializeOverridden() { for(auto & bidHelper : overriddenBidsToLoad) { auto jsonNode = bidHelper.json; auto scope = bidHelper.town->getBuildingScope(); for(auto b : jsonNode.Vector()) { auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get()); bidHelper.building->overrideBids.insert(bid); } } overriddenBidsToLoad.clear(); } void CTownHandler::initializeWarMachines() { // must be done separately after all objects are loaded for(auto & p : warMachinesToLoad) { CTown * t = p.first; JsonNode creatureKey = p.second; auto ret = VLC->modh->identifiers.getIdentifier("creature", creatureKey, false); if(ret) { const CCreature * creature = CreatureID(*ret).toCreature(); t->warMachine = creature->warMachine; } } warMachinesToLoad.clear(); } std::vector CTownHandler::getDefaultAllowed() const { std::vector allowedFactions; for(auto town : objects) { allowedFactions.push_back(town->town != nullptr); } return allowedFactions; } std::set CTownHandler::getAllowedFactions(bool withTown) const { std::set allowedFactions; std::vector allowed; if (withTown) allowed = getDefaultAllowed(); else allowed.resize( objects.size(), true); for (size_t i=0; i & CTownHandler::getTypeNames() const { static const std::vector typeNames = { "faction", "town" }; return typeNames; }