CTownHandler.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /*
  2. * CTownHandler.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 "CTownHandler.h"
  12. #include "VCMI_Lib.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "JsonNode.h"
  15. #include "StringConstants.h"
  16. #include "CCreatureHandler.h"
  17. #include "CModHandler.h"
  18. #include "CHeroHandler.h"
  19. #include "CArtHandler.h"
  20. #include "spells/CSpellHandler.h"
  21. #include "filesystem/Filesystem.h"
  22. #include "mapObjects/CObjectClassesHandler.h"
  23. #include "mapObjects/CObjectHandler.h"
  24. #include "HeroBonus.h"
  25. const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number
  26. const std::map<std::string, CBuilding::EBuildMode> CBuilding::MODES =
  27. {
  28. { "normal", CBuilding::BUILD_NORMAL },
  29. { "auto", CBuilding::BUILD_AUTO },
  30. { "special", CBuilding::BUILD_SPECIAL },
  31. { "grail", CBuilding::BUILD_GRAIL }
  32. };
  33. const std::map<std::string, CBuilding::ETowerHeight> CBuilding::TOWER_TYPES =
  34. {
  35. { "low", CBuilding::HEIGHT_LOW },
  36. { "average", CBuilding::HEIGHT_AVERAGE },
  37. { "high", CBuilding::HEIGHT_HIGH },
  38. { "skyship", CBuilding::HEIGHT_SKYSHIP }
  39. };
  40. const std::string & CBuilding::Name() const
  41. {
  42. return name;
  43. }
  44. const std::string & CBuilding::Description() const
  45. {
  46. return description;
  47. }
  48. BuildingID CBuilding::getBase() const
  49. {
  50. const CBuilding * build = this;
  51. while (build->upgrade >= 0)
  52. {
  53. build = build->town->buildings.at(build->upgrade);
  54. }
  55. return build->bid;
  56. }
  57. si32 CBuilding::getDistance(BuildingID buildID) const
  58. {
  59. const CBuilding * build = town->buildings.at(buildID);
  60. int distance = 0;
  61. while (build->upgrade >= 0 && build != this)
  62. {
  63. build = build->town->buildings.at(build->upgrade);
  64. distance++;
  65. }
  66. if (build == this)
  67. return distance;
  68. return -1;
  69. }
  70. void CBuilding::deserializeFix()
  71. {
  72. //default value for mode was broken, have to fix it here for old saves (v777 and older)
  73. switch(mode)
  74. {
  75. case BUILD_NORMAL:
  76. case BUILD_AUTO:
  77. case BUILD_SPECIAL:
  78. case BUILD_GRAIL:
  79. break;
  80. default:
  81. mode = BUILD_NORMAL;
  82. break;
  83. }
  84. }
  85. void CBuilding::addNewBonus(std::shared_ptr<Bonus> b, BonusList & bonusList)
  86. {
  87. bonusList.push_back(b);
  88. }
  89. const JsonNode & CBuilding::getCurrentFactionForUpdateRoutine() const
  90. {
  91. const auto & faction = town->faction->identifier;
  92. const auto & factionsContent = (*VLC->modh->content)["factions"];
  93. const auto & coreData = factionsContent.modData.at("core");
  94. const auto & coreFactions = coreData.modData;
  95. const auto & currentFaction = coreFactions[faction];
  96. if(currentFaction.isNull())
  97. {
  98. const auto index = faction.find(':');
  99. const std::string factionDir = index == std::string::npos ? faction : faction.substr(0, index);
  100. const auto it = factionsContent.modData.find(factionDir);
  101. if(it == factionsContent.modData.end())
  102. {
  103. logMod->warn("Warning: Update old save failed: Faction: '%s' is not found.", factionDir);
  104. return currentFaction;
  105. }
  106. const std::string modFaction = index == std::string::npos ? faction : faction.substr(index + 1);
  107. return it->second.modData[modFaction];
  108. }
  109. return currentFaction;
  110. }
  111. void CBuilding::update792()
  112. {
  113. subId = BuildingSubID::NONE;
  114. height = ETowerHeight::HEIGHT_NO_TOWER;
  115. if(!bid.IsSpecialOrGrail() || town == nullptr || town->faction == nullptr || town->faction->identifier.empty())
  116. return;
  117. const auto buildingName = CTownHandler::getMappedValue<std::string, BuildingID>(bid, std::string(), MappedKeys::BUILDING_TYPES_TO_NAMES);
  118. if(buildingName.empty())
  119. return;
  120. auto & currentFaction = getCurrentFactionForUpdateRoutine();
  121. if(!currentFaction.isNull() && currentFaction.getType() == JsonNode::JsonType::DATA_STRUCT)
  122. {
  123. const auto & buildings = currentFaction["town"]["buildings"];
  124. const auto & currentBuilding = buildings[buildingName];
  125. subId = CTownHandler::getMappedValue<BuildingSubID::EBuildingSubID>(currentBuilding["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  126. height = subId == BuildingSubID::LOOKOUT_TOWER || bid == BuildingID::GRAIL
  127. ? CTownHandler::getMappedValue<CBuilding::ETowerHeight>(currentBuilding["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES)
  128. : height = CBuilding::HEIGHT_NO_TOWER;
  129. }
  130. }
  131. void CBuilding::update794()
  132. {
  133. if(bid == BuildingID::TAVERN || subId == BuildingSubID::BROTHERHOOD_OF_SWORD)
  134. {
  135. VLC->townh->addBonusesForVanilaBuilding(this);
  136. return;
  137. }
  138. if(!bid.IsSpecialOrGrail())
  139. return;
  140. VLC->townh->addBonusesForVanilaBuilding(this);
  141. if(!buildingBonuses.empty() //addBonusesForVanilaBuilding has done all work
  142. || town->faction == nullptr //or faction data is not valid
  143. || town->faction->identifier.empty())
  144. return;
  145. const auto buildingName = CTownHandler::getMappedValue<std::string, BuildingID>(bid, std::string(), MappedKeys::BUILDING_TYPES_TO_NAMES, false);
  146. if(buildingName.empty())
  147. return;
  148. auto & currentFaction = getCurrentFactionForUpdateRoutine();
  149. if(currentFaction.isNull() || currentFaction.getType() != JsonNode::JsonType::DATA_STRUCT)
  150. return;
  151. const auto & buildings = currentFaction["town"]["buildings"];
  152. const auto & currentBuilding = buildings[buildingName];
  153. CTownHandler::loadSpecialBuildingBonuses(currentBuilding["bonuses"], buildingBonuses, this);
  154. CTownHandler::loadSpecialBuildingBonuses(currentBuilding["onVisitBonuses"], onVisitBonuses, this);
  155. if(!onVisitBonuses.empty())
  156. {
  157. if(subId == BuildingSubID::NONE)
  158. subId = BuildingSubID::CUSTOM_VISITING_BONUS;
  159. for(auto & bonus : onVisitBonuses)
  160. bonus->sid = Bonus::getSid32(town->faction->index, bid);
  161. }
  162. const auto & overriddenBids = currentBuilding["overrides"];
  163. if(overriddenBids.isNull())
  164. return;
  165. auto scope = town->getBuildingScope();
  166. for(auto b : overriddenBids.Vector())
  167. {
  168. auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get());
  169. overrideBids.insert(bid);
  170. }
  171. }
  172. CFaction::CFaction()
  173. {
  174. town = nullptr;
  175. index = 0;
  176. alignment = EAlignment::NEUTRAL;
  177. }
  178. CFaction::~CFaction()
  179. {
  180. delete town;
  181. }
  182. CTown::CTown()
  183. : faction(nullptr), mageLevel(0), primaryRes(0), moatDamage(0), defaultTavernChance(0)
  184. {
  185. }
  186. CTown::~CTown()
  187. {
  188. for(auto & build : buildings)
  189. build.second.dellNull();
  190. for(auto & str : clientInfo.structures)
  191. str.dellNull();
  192. }
  193. std::vector<BattleHex> CTown::defaultMoatHexes()
  194. {
  195. static const std::vector<BattleHex> moatHexes = {11, 28, 44, 61, 77, 111, 129, 146, 164, 181};
  196. return moatHexes;
  197. }
  198. std::string CTown::getLocalizedFactionName() const
  199. {
  200. if(faction == nullptr)
  201. return "Random";
  202. else
  203. return faction->name;
  204. }
  205. std::string CTown::getBuildingScope() const
  206. {
  207. if(faction == nullptr)
  208. //no faction == random faction
  209. return "building";
  210. else
  211. return "building." + faction->identifier;
  212. }
  213. std::set<si32> CTown::getAllBuildings() const
  214. {
  215. std::set<si32> res;
  216. for(const auto & b : buildings)
  217. {
  218. res.insert(b.first.num);
  219. }
  220. return res;
  221. }
  222. const CBuilding * CTown::getSpecialBuilding(BuildingSubID::EBuildingSubID subID) const
  223. {
  224. for(const auto & kvp : buildings)
  225. {
  226. if(kvp.second->subId == subID)
  227. return buildings.at(kvp.first);
  228. }
  229. return nullptr;
  230. }
  231. BuildingID::EBuildingID CTown::getBuildingType(BuildingSubID::EBuildingSubID subID) const
  232. {
  233. auto building = getSpecialBuilding(subID);
  234. return building == nullptr ? BuildingID::NONE : building->bid.num;
  235. }
  236. const std::string CTown::getGreeting(BuildingSubID::EBuildingSubID subID) const
  237. {
  238. return VLC->townh->getMappedValue<const std::string, BuildingSubID::EBuildingSubID>(subID, std::string(), specialMessages, false);
  239. }
  240. void CTown::setGreeting(BuildingSubID::EBuildingSubID subID, const std::string message) const
  241. {
  242. specialMessages.insert(std::pair<BuildingSubID::EBuildingSubID, const std::string>(subID, message));
  243. }
  244. CTownHandler::CTownHandler()
  245. {
  246. VLC->townh = this;
  247. randomTown = new CTown();
  248. }
  249. CTownHandler::~CTownHandler()
  250. {
  251. delete randomTown;
  252. for(auto faction : factions)
  253. faction.dellNull();
  254. }
  255. JsonNode readBuilding(CLegacyConfigParser & parser)
  256. {
  257. JsonNode ret;
  258. JsonNode & cost = ret["cost"];
  259. //note: this code will try to parse mithril as well but wil always return 0 for it
  260. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  261. cost[resID].Float() = parser.readNumber();
  262. cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator
  263. parser.endLine();
  264. return ret;
  265. }
  266. TPropagatorPtr CTownHandler::emptyPropagator = std::make_shared<CPropagatorNodeType>();
  267. std::vector<JsonNode> CTownHandler::loadLegacyData(size_t dataSize)
  268. {
  269. std::vector<JsonNode> dest(dataSize);
  270. factions.resize(dataSize);
  271. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  272. {
  273. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  274. };
  275. CLegacyConfigParser parser("DATA/BUILDING.TXT");
  276. parser.endLine(); // header
  277. parser.endLine();
  278. //Unique buildings
  279. for (size_t town=0; town<dataSize; town++)
  280. {
  281. parser.endLine(); //header
  282. parser.endLine();
  283. int buildID = 17;
  284. do
  285. {
  286. getBuild(town, buildID) = readBuilding(parser);
  287. buildID++;
  288. }
  289. while (!parser.isNextEntryEmpty());
  290. }
  291. // Common buildings
  292. parser.endLine(); // header
  293. parser.endLine();
  294. parser.endLine();
  295. int buildID = 0;
  296. do
  297. {
  298. JsonNode building = readBuilding(parser);
  299. for (size_t town=0; town<dataSize; town++)
  300. getBuild(town, buildID) = building;
  301. buildID++;
  302. }
  303. while (!parser.isNextEntryEmpty());
  304. parser.endLine(); //header
  305. parser.endLine();
  306. //Dwellings
  307. for (size_t town=0; town<dataSize; town++)
  308. {
  309. parser.endLine(); //header
  310. parser.endLine();
  311. for (size_t i=0; i<14; i++)
  312. {
  313. getBuild(town, 30+i) = readBuilding(parser);
  314. }
  315. }
  316. {
  317. CLegacyConfigParser parser("DATA/BLDGNEUT.TXT");
  318. for(int building=0; building<15; building++)
  319. {
  320. std::string name = parser.readString();
  321. std::string descr = parser.readString();
  322. parser.endLine();
  323. for(int j=0; j<dataSize; j++)
  324. {
  325. getBuild(j, building)["name"].String() = name;
  326. getBuild(j, building)["description"].String() = descr;
  327. }
  328. }
  329. parser.endLine(); // silo
  330. parser.endLine(); // blacksmith //unused entries
  331. parser.endLine(); // moat
  332. //shipyard with the ship
  333. std::string name = parser.readString();
  334. std::string descr = parser.readString();
  335. parser.endLine();
  336. for(int town=0; town<dataSize; town++)
  337. {
  338. getBuild(town, 20)["name"].String() = name;
  339. getBuild(town, 20)["description"].String() = descr;
  340. }
  341. //blacksmith
  342. for(int town=0; town<dataSize; town++)
  343. {
  344. getBuild(town, 16)["name"].String() = parser.readString();
  345. getBuild(town, 16)["description"].String() = parser.readString();
  346. parser.endLine();
  347. }
  348. }
  349. {
  350. CLegacyConfigParser parser("DATA/BLDGSPEC.TXT");
  351. for(int town=0; town<dataSize; town++)
  352. {
  353. for(int build=0; build<9; build++)
  354. {
  355. getBuild(town, 17 + build)["name"].String() = parser.readString();
  356. getBuild(town, 17 + build)["description"].String() = parser.readString();
  357. parser.endLine();
  358. }
  359. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  360. getBuild(town, 26)["description"].String() = parser.readString();
  361. parser.endLine();
  362. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  363. getBuild(town, 15)["description"].String() = parser.readString();
  364. parser.endLine();
  365. }
  366. }
  367. {
  368. CLegacyConfigParser parser("DATA/DWELLING.TXT");
  369. for(int town=0; town<dataSize; town++)
  370. {
  371. for(int build=0; build<14; build++)
  372. {
  373. getBuild(town, 30 + build)["name"].String() = parser.readString();
  374. getBuild(town, 30 + build)["description"].String() = parser.readString();
  375. parser.endLine();
  376. }
  377. }
  378. }
  379. {
  380. CLegacyConfigParser typeParser("DATA/TOWNTYPE.TXT");
  381. CLegacyConfigParser nameParser("DATA/TOWNNAME.TXT");
  382. size_t townID=0;
  383. do
  384. {
  385. dest[townID]["name"].String() = typeParser.readString();
  386. for (int i=0; i<NAMES_PER_TOWN; i++)
  387. {
  388. JsonNode name;
  389. name.String() = nameParser.readString();
  390. dest[townID]["town"]["names"].Vector().push_back(name);
  391. nameParser.endLine();
  392. }
  393. townID++;
  394. }
  395. while (typeParser.endLine());
  396. }
  397. return dest;
  398. }
  399. void CTownHandler::loadBuildingRequirements(CBuilding * building, const JsonNode & source, std::vector<BuildingRequirementsHelper> & bidsToLoad)
  400. {
  401. if (source.isNull())
  402. return;
  403. BuildingRequirementsHelper hlp;
  404. hlp.building = building;
  405. hlp.town = building->town;
  406. hlp.json = source;
  407. bidsToLoad.push_back(hlp);
  408. }
  409. template<typename R, typename K>
  410. R CTownHandler::getMappedValue(const K key, const R defval, const std::map<K, R> & map, bool required)
  411. {
  412. auto it = map.find(key);
  413. if(it != map.end())
  414. return it->second;
  415. if(required)
  416. logMod->warn("Warning: Property: '%s' is unknown. Correct the typo or update VCMI.", key);
  417. return defval;
  418. }
  419. template<typename R>
  420. R CTownHandler::getMappedValue(const JsonNode & node, const R defval, const std::map<std::string, R> & map, bool required)
  421. {
  422. if(!node.isNull() && node.getType() == JsonNode::JsonType::DATA_STRING)
  423. return getMappedValue<R, std::string>(node.String(), defval, map, required);
  424. return defval;
  425. }
  426. void CTownHandler::addBonusesForVanilaBuilding(CBuilding * building)
  427. {
  428. std::shared_ptr<Bonus> b;
  429. static TPropagatorPtr playerPropagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ENodeTypes::PLAYER);
  430. if(building->subId == BuildingSubID::NONE)
  431. {
  432. if(building->bid == BuildingID::TAVERN)
  433. b = createBonus(building, Bonus::MORALE, +1);
  434. else if(building->bid == BuildingID::GRAIL
  435. && building->town->faction != nullptr
  436. && boost::algorithm::ends_with(building->town->faction->identifier, ":cove"))
  437. {
  438. static TPropagatorPtr allCreaturesPropagator(new CPropagatorNodeType(CBonusSystemNode::ENodeTypes::ALL_CREATURES));
  439. static auto factionLimiter = std::make_shared<CreatureFactionLimiter>(building->town->faction->index);
  440. b = createBonus(building, Bonus::NO_TERRAIN_PENALTY, 0, allCreaturesPropagator);
  441. b->addLimiter(factionLimiter);
  442. }
  443. }
  444. else
  445. {
  446. switch(building->subId)
  447. {
  448. case BuildingSubID::BROTHERHOOD_OF_SWORD:
  449. b = createBonus(building, Bonus::MORALE, +2);
  450. building->overrideBids.insert(BuildingID::TAVERN);
  451. break;
  452. case BuildingSubID::FOUNTAIN_OF_FORTUNE:
  453. b = createBonus(building, Bonus::LUCK, +2);
  454. break;
  455. case BuildingSubID::SPELL_POWER_GARRISON_BONUS:
  456. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER);
  457. break;
  458. case BuildingSubID::ATTACK_GARRISON_BONUS:
  459. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK);
  460. break;
  461. case BuildingSubID::DEFENSE_GARRISON_BONUS:
  462. b = createBonus(building, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE);
  463. break;
  464. case BuildingSubID::LIGHTHOUSE:
  465. b = createBonus(building, Bonus::SEA_MOVEMENT, +500, playerPropagator);
  466. break;
  467. }
  468. }
  469. if(b)
  470. building->addNewBonus(b, building->buildingBonuses);
  471. }
  472. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, int subtype)
  473. {
  474. return createBonus(build, type, val, emptyPropagator, subtype);
  475. }
  476. std::shared_ptr<Bonus> CTownHandler::createBonus(CBuilding * build, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype)
  477. {
  478. std::ostringstream descr;
  479. descr << build->name;
  480. return createBonusImpl(build->bid, type, val, prop, descr.str(), subtype);
  481. }
  482. std::shared_ptr<Bonus> CTownHandler::createBonusImpl(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, const std::string & description, int subtype)
  483. {
  484. auto b = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, description, subtype);
  485. if(prop)
  486. b->addPropagator(prop);
  487. return b;
  488. }
  489. void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building)
  490. {
  491. for(auto b : source.Vector())
  492. {
  493. auto bonus = JsonUtils::parseBuildingBonus(b, building->bid, building->name);
  494. if(bonus == nullptr)
  495. continue;
  496. if(bonus->limiter != nullptr)
  497. {
  498. auto limPtr = dynamic_cast<CreatureFactionLimiter*>(bonus->limiter.get());
  499. if(limPtr != nullptr && limPtr->faction == (TFaction)-1)
  500. limPtr->faction = building->town->faction->index;
  501. }
  502. //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty.
  503. if(bonus->propagator != nullptr
  504. && bonus->propagator->getPropagatorType() == CBonusSystemNode::ENodeTypes::UNKNOWN)
  505. bonus->addPropagator(emptyPropagator);
  506. building->addNewBonus(bonus, bonusList);
  507. }
  508. }
  509. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  510. {
  511. auto ret = new CBuilding();
  512. ret->bid = getMappedValue<BuildingID, std::string>(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false);
  513. if(ret->bid == BuildingID::NONE)
  514. ret->bid = source["id"].isNull() ? BuildingID(BuildingID::NONE) : BuildingID(source["id"].Float());
  515. if (ret->bid == BuildingID::NONE)
  516. logMod->error("Error: Building '%s' has not internal ID and won't work properly. Correct the typo or update VCMI.", stringID);
  517. ret->mode = ret->bid == BuildingID::GRAIL
  518. ? CBuilding::BUILD_GRAIL
  519. : getMappedValue<CBuilding::EBuildMode>(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES);
  520. ret->subId = getMappedValue<BuildingSubID::EBuildingSubID>(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  521. ret->height = CBuilding::HEIGHT_NO_TOWER;
  522. if(ret->subId == BuildingSubID::LOOKOUT_TOWER
  523. || ret->bid == BuildingID::GRAIL)
  524. ret->height = getMappedValue<CBuilding::ETowerHeight>(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES);
  525. ret->identifier = stringID;
  526. ret->town = town;
  527. ret->name = source["name"].String();
  528. ret->description = source["description"].String();
  529. ret->resources = TResources(source["cost"]);
  530. ret->produce = TResources(source["produce"]);
  531. if(ret->bid == BuildingID::TAVERN)
  532. addBonusesForVanilaBuilding(ret);
  533. else if(ret->bid.IsSpecialOrGrail())
  534. {
  535. loadSpecialBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret);
  536. if(ret->buildingBonuses.empty())
  537. addBonusesForVanilaBuilding(ret);
  538. loadSpecialBuildingBonuses(source["onVisitBonuses"], ret->onVisitBonuses, ret);
  539. if(!ret->onVisitBonuses.empty())
  540. {
  541. if(ret->subId == BuildingSubID::NONE)
  542. ret->subId = BuildingSubID::CUSTOM_VISITING_BONUS;
  543. for(auto & bonus : ret->onVisitBonuses)
  544. bonus->sid = Bonus::getSid32(ret->town->faction->index, ret->bid);
  545. }
  546. }
  547. //MODS COMPATIBILITY FOR 0.96
  548. if(!ret->produce.nonZero())
  549. {
  550. switch (ret->bid) {
  551. break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500;
  552. break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000;
  553. break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000;
  554. break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000;
  555. break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000;
  556. break; case BuildingID::RESOURCE_SILO :
  557. {
  558. switch (ret->town->primaryRes)
  559. {
  560. case Res::GOLD:
  561. ret->produce[ret->town->primaryRes] = 500;
  562. break;
  563. case Res::WOOD_AND_ORE:
  564. ret->produce[Res::WOOD] = 1;
  565. ret->produce[Res::ORE] = 1;
  566. break;
  567. default:
  568. ret->produce[ret->town->primaryRes] = 1;
  569. break;
  570. }
  571. }
  572. }
  573. }
  574. loadBuildingRequirements(ret, source["requires"], requirementsToLoad);
  575. if(ret->bid.IsSpecialOrGrail())
  576. loadBuildingRequirements(ret, source["overrides"], overriddenBidsToLoad);
  577. if (!source["upgrades"].isNull())
  578. {
  579. // building id and upgrades can't be the same
  580. if(stringID == source["upgrades"].String())
  581. {
  582. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  583. stringID % ret->town->getLocalizedFactionName()));
  584. }
  585. VLC->modh->identifiers.requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  586. {
  587. ret->upgrade = BuildingID(identifier);
  588. });
  589. }
  590. else
  591. ret->upgrade = BuildingID::NONE;
  592. ret->town->buildings[ret->bid] = ret;
  593. VLC->modh->identifiers.registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid);
  594. }
  595. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  596. {
  597. for(auto & node : source.Struct())
  598. {
  599. if (!node.second.isNull())
  600. {
  601. loadBuilding(town, node.first, node.second);
  602. }
  603. }
  604. }
  605. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source)
  606. {
  607. auto ret = new CStructure();
  608. ret->building = nullptr;
  609. ret->buildable = nullptr;
  610. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  611. {
  612. ret->building = town.buildings[BuildingID(identifier)];
  613. });
  614. if (source["builds"].isNull())
  615. {
  616. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  617. {
  618. ret->building = town.buildings[BuildingID(identifier)];
  619. });
  620. }
  621. else
  622. {
  623. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable
  624. {
  625. ret->buildable = town.buildings[BuildingID(identifier)];
  626. });
  627. }
  628. ret->identifier = stringID;
  629. ret->pos.x = static_cast<si32>(source["x"].Float());
  630. ret->pos.y = static_cast<si32>(source["y"].Float());
  631. ret->pos.z = static_cast<si32>(source["z"].Float());
  632. ret->hiddenUpgrade = source["hidden"].Bool();
  633. ret->defName = source["animation"].String();
  634. ret->borderName = source["border"].String();
  635. ret->areaName = source["area"].String();
  636. town.clientInfo.structures.push_back(ret);
  637. }
  638. void CTownHandler::loadStructures(CTown &town, const JsonNode & source)
  639. {
  640. for(auto &node : source.Struct())
  641. {
  642. if (!node.second.isNull())
  643. loadStructure(town, node.first, node.second);
  644. }
  645. }
  646. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
  647. {
  648. auto & dstSlots = town.clientInfo.hallSlots;
  649. auto & srcSlots = source.Vector();
  650. dstSlots.resize(srcSlots.size());
  651. for(size_t i=0; i<dstSlots.size(); i++)
  652. {
  653. auto & dstRow = dstSlots[i];
  654. auto & srcRow = srcSlots[i].Vector();
  655. dstRow.resize(srcRow.size());
  656. for(size_t j=0; j < dstRow.size(); j++)
  657. {
  658. auto & dstBox = dstRow[j];
  659. auto & srcBox = srcRow[j].Vector();
  660. dstBox.resize(srcBox.size());
  661. for(size_t k=0; k<dstBox.size(); k++)
  662. {
  663. auto & dst = dstBox[k];
  664. auto & src = srcBox[k];
  665. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier)
  666. {
  667. dst = BuildingID(identifier);
  668. });
  669. }
  670. }
  671. }
  672. }
  673. CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
  674. {
  675. CTown::ClientInfo::Point ret;
  676. ret.x = static_cast<si32>(node["x"].Float());
  677. ret.y = static_cast<si32>(node["y"].Float());
  678. return ret;
  679. }
  680. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source)
  681. {
  682. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  683. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  684. {
  685. auto crId = CreatureID(creature);
  686. if(!VLC->creh->creatures[crId]->animation.missleFrameAngles.size())
  687. 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!"
  688. , town.faction->name
  689. , VLC->creh->creatures[crId]->nameSing);
  690. town.clientInfo.siegeShooter = crId;
  691. });
  692. auto & pos = town.clientInfo.siegePositions;
  693. pos.resize(21);
  694. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  695. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  696. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  697. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  698. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  699. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  700. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  701. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  702. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  703. pos[9] = JsonToPoint(source["gate"]["gate"]);
  704. pos[10] = JsonToPoint(source["gate"]["arch"]);
  705. pos[7] = JsonToPoint(source["walls"]["upper"]);
  706. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  707. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  708. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  709. pos[13] = JsonToPoint(source["moat"]["moat"]);
  710. pos[14] = JsonToPoint(source["moat"]["bank"]);
  711. pos[11] = JsonToPoint(source["static"]["bottom"]);
  712. pos[12] = JsonToPoint(source["static"]["top"]);
  713. pos[1] = JsonToPoint(source["static"]["background"]);
  714. }
  715. static void readIcon(JsonNode source, std::string & small, std::string & large)
  716. {
  717. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  718. {
  719. small = source["small"].String();
  720. large = source["large"].String();
  721. }
  722. }
  723. void CTownHandler::loadClientData(CTown &town, const JsonNode & source)
  724. {
  725. CTown::ClientInfo & info = town.clientInfo;
  726. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  727. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  728. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  729. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  730. info.hallBackground = source["hallBackground"].String();
  731. info.musicTheme = source["musicTheme"].String();
  732. info.townBackground = source["townBackground"].String();
  733. info.guildWindow = source["guildWindow"].String();
  734. info.buildingsIcons = source["buildingsIcons"].String();
  735. //left for back compatibility - will be removed later
  736. if (source["guildBackground"].String() != "")
  737. info.guildBackground = source["guildBackground"].String();
  738. else
  739. info.guildBackground = "TPMAGE.bmp";
  740. if (source["tavernVideo"].String() != "")
  741. info.tavernVideo = source["tavernVideo"].String();
  742. else
  743. info.tavernVideo = "TAVERN.BIK";
  744. //end of legacy assignment
  745. loadTownHall(town, source["hallSlots"]);
  746. loadStructures(town, source["structures"]);
  747. loadSiegeScreen(town, source["siege"]);
  748. }
  749. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  750. {
  751. auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  752. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  753. town->primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
  754. else
  755. town->primaryRes = static_cast<ui16>(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  756. warMachinesToLoad[town] = source["warMachine"];
  757. town->moatDamage = static_cast<si32>(source["moatDamage"].Float());
  758. // Compatibility for <= 0.98f mods
  759. if(source["moatHexes"].isNull())
  760. town->moatHexes = CTown::defaultMoatHexes();
  761. else
  762. town->moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
  763. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  764. town->names = source["names"].convertTo<std::vector<std::string> >();
  765. // Horde building creature level
  766. for(const JsonNode &node : source["horde"].Vector())
  767. town->hordeLvl[(int)town->hordeLvl.size()] = static_cast<int>(node.Float());
  768. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  769. // but anything below 2 must be handled here
  770. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  771. town->hordeLvl[(int)i] = -1;
  772. const JsonVector & creatures = source["creatures"].Vector();
  773. town->creatures.resize(creatures.size());
  774. for (size_t i=0; i< creatures.size(); i++)
  775. {
  776. const JsonVector & level = creatures[i].Vector();
  777. town->creatures[i].resize(level.size());
  778. for (size_t j=0; j<level.size(); j++)
  779. {
  780. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=](si32 creature)
  781. {
  782. town->creatures[i][j] = CreatureID(creature);
  783. });
  784. }
  785. }
  786. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  787. /// set chance of specific hero class to appear in this town
  788. for(auto &node : source["tavern"].Struct())
  789. {
  790. int chance = static_cast<int>(node.second.Float());
  791. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
  792. {
  793. VLC->heroh->classes.heroClasses[classID]->selectionProbability[town->faction->index] = chance;
  794. });
  795. }
  796. for(auto &node : source["guildSpells"].Struct())
  797. {
  798. int chance = static_cast<int>(node.second.Float());
  799. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
  800. {
  801. VLC->spellh->objects.at(spellID)->probabilities[town->faction->index] = chance;
  802. });
  803. }
  804. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  805. {
  806. town->dwellings.push_back(d["graphics"].String());
  807. town->dwellingNames.push_back(d["name"].String());
  808. }
  809. loadBuildings(town, source["buildings"]);
  810. loadClientData(*town, source);
  811. }
  812. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
  813. {
  814. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  815. std::string prefix = source["prefix"].String();
  816. for(const JsonNode &piece : source["pieces"].Vector())
  817. {
  818. size_t index = faction.puzzleMap.size();
  819. SPuzzleInfo spi;
  820. spi.x = static_cast<si16>(piece["x"].Float());
  821. spi.y = static_cast<si16>(piece["y"].Float());
  822. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  823. spi.number = static_cast<ui16>(index);
  824. // filename calculation
  825. std::ostringstream suffix;
  826. suffix << std::setfill('0') << std::setw(2) << index;
  827. spi.filename = prefix + suffix.str();
  828. faction.puzzleMap.push_back(spi);
  829. }
  830. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  831. }
  832. ETerrainType::EETerrainType CTownHandler::getDefaultTerrainForAlignment(EAlignment::EAlignment alignment) const
  833. {
  834. ETerrainType::EETerrainType terrain = defaultGoodTerrain;
  835. switch(alignment)
  836. {
  837. case EAlignment::EAlignment::EVIL:
  838. terrain = defaultEvilTerrain;
  839. break;
  840. case EAlignment::EAlignment::NEUTRAL:
  841. terrain = defaultNeutralTerrain;
  842. break;
  843. }
  844. return terrain;
  845. }
  846. CFaction * CTownHandler::loadFromJson(const JsonNode &source, const std::string & identifier, TFaction index)
  847. {
  848. auto faction = new CFaction();
  849. faction->index = index;
  850. faction->name = source["name"].String();
  851. faction->identifier = identifier;
  852. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  853. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  854. int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String());
  855. if (alignment == -1)
  856. faction->alignment = EAlignment::NEUTRAL;
  857. else
  858. faction->alignment = static_cast<EAlignment::EAlignment>(alignment);
  859. auto nativeTerrain = source["nativeTerrain"];
  860. int terrainNum = nativeTerrain.isNull()
  861. ? -1
  862. : vstd::find_pos(GameConstants::TERRAIN_NAMES, nativeTerrain.String());
  863. //Contructor is not called here, but operator=
  864. faction->nativeTerrain = terrainNum < 0
  865. ? getDefaultTerrainForAlignment(faction->alignment)
  866. : static_cast<ETerrainType::EETerrainType>(terrainNum);
  867. if (!source["town"].isNull())
  868. {
  869. faction->town = new CTown();
  870. faction->town->faction = faction;
  871. loadTown(faction->town, source["town"]);
  872. }
  873. else
  874. faction->town = nullptr;
  875. if (!source["puzzleMap"].isNull())
  876. loadPuzzle(*faction, source["puzzleMap"]);
  877. return faction;
  878. }
  879. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  880. {
  881. auto index = static_cast<TFaction>(factions.size());
  882. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name), index);
  883. factions.push_back(object);
  884. if (object->town)
  885. {
  886. auto & info = object->town->clientInfo;
  887. info.icons[0][0] = 8 + object->index * 4 + 0;
  888. info.icons[0][1] = 8 + object->index * 4 + 1;
  889. info.icons[1][0] = 8 + object->index * 4 + 2;
  890. info.icons[1][1] = 8 + object->index * 4 + 3;
  891. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  892. {
  893. // register town once objects are loaded
  894. JsonNode config = data["town"]["mapObject"];
  895. config["faction"].String() = name;
  896. config["faction"].meta = scope;
  897. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  898. config.meta = scope;
  899. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  900. // MODS COMPATIBILITY FOR 0.96
  901. auto & advMap = data["town"]["adventureMap"];
  902. if (!advMap.isNull())
  903. {
  904. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  905. JsonNode config;
  906. config["animation"] = advMap["castle"];
  907. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  908. }
  909. });
  910. }
  911. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  912. }
  913. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  914. {
  915. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name), static_cast<TFaction>(index));
  916. if (factions.size() > index)
  917. assert(factions[index] == nullptr); // ensure that this id was not loaded before
  918. else
  919. factions.resize(index + 1);
  920. factions[index] = object;
  921. if (object->town)
  922. {
  923. auto & info = object->town->clientInfo;
  924. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  925. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  926. info.icons[1][0] = object->index * 2 + 0;
  927. info.icons[1][1] = object->index * 2 + 1;
  928. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  929. {
  930. // register town once objects are loaded
  931. JsonNode config = data["town"]["mapObject"];
  932. config["faction"].String() = name;
  933. config["faction"].meta = scope;
  934. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  935. });
  936. }
  937. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  938. }
  939. void CTownHandler::loadRandomFaction()
  940. {
  941. static const ResourceID randomFactionPath("config/factions/random.json");
  942. JsonNode randomFactionJson(randomFactionPath);
  943. randomFactionJson.setMeta("core", true);
  944. loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]);
  945. }
  946. void CTownHandler::loadCustom()
  947. {
  948. loadRandomFaction();
  949. }
  950. void CTownHandler::afterLoadFinalization()
  951. {
  952. initializeRequirements();
  953. initializeOverridden();
  954. initializeWarMachines();
  955. }
  956. void CTownHandler::initializeRequirements()
  957. {
  958. // must be done separately after all ID's are known
  959. for (auto & requirement : requirementsToLoad)
  960. {
  961. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  962. {
  963. if (node.Vector().size() > 1)
  964. {
  965. logMod->warn("Unexpected length of town buildings requirements: %d", node.Vector().size());
  966. logMod->warn("Entry contains: ");
  967. logMod->warn(node.toJson());
  968. }
  969. return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get());
  970. });
  971. }
  972. requirementsToLoad.clear();
  973. }
  974. void CTownHandler::initializeOverridden()
  975. {
  976. for(auto & bidHelper : overriddenBidsToLoad)
  977. {
  978. auto jsonNode = bidHelper.json;
  979. auto scope = bidHelper.town->getBuildingScope();
  980. for(auto b : jsonNode.Vector())
  981. {
  982. auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get());
  983. bidHelper.building->overrideBids.insert(bid);
  984. }
  985. }
  986. overriddenBidsToLoad.clear();
  987. }
  988. void CTownHandler::initializeWarMachines()
  989. {
  990. // must be done separately after all objects are loaded
  991. for(auto & p : warMachinesToLoad)
  992. {
  993. CTown * t = p.first;
  994. JsonNode creatureKey = p.second;
  995. auto ret = VLC->modh->identifiers.getIdentifier("creature", creatureKey, false);
  996. if(ret)
  997. {
  998. const CCreature * creature = CreatureID(*ret).toCreature();
  999. t->warMachine = creature->warMachine;
  1000. }
  1001. }
  1002. warMachinesToLoad.clear();
  1003. }
  1004. std::vector<bool> CTownHandler::getDefaultAllowed() const
  1005. {
  1006. std::vector<bool> allowedFactions;
  1007. for(auto town : factions)
  1008. {
  1009. allowedFactions.push_back(town->town != nullptr);
  1010. }
  1011. return allowedFactions;
  1012. }
  1013. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown) const
  1014. {
  1015. std::set<TFaction> allowedFactions;
  1016. std::vector<bool> allowed;
  1017. if (withTown)
  1018. allowed = getDefaultAllowed();
  1019. else
  1020. allowed.resize( factions.size(), true);
  1021. for (size_t i=0; i<allowed.size(); i++)
  1022. if (allowed[i])
  1023. allowedFactions.insert((TFaction)i);
  1024. return allowedFactions;
  1025. }
  1026. si32 CTownHandler::decodeFaction(const std::string & identifier)
  1027. {
  1028. auto rawId = VLC->modh->identifiers.getIdentifier("core", "faction", identifier);
  1029. if(rawId)
  1030. return rawId.get();
  1031. else
  1032. return -1;
  1033. }
  1034. std::string CTownHandler::encodeFaction(const si32 index)
  1035. {
  1036. return VLC->townh->factions[index]->identifier;
  1037. }