CTownHandler.cpp 34 KB

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