CTownHandler.cpp 38 KB

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