CTownHandler.cpp 38 KB

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