CTownHandler.cpp 34 KB

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