CTownHandler.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 "CTown.h"
  13. #include "CFaction.h"
  14. #include "../building/CBuilding.h"
  15. #include "../hero/CHeroClassHandler.h"
  16. #include "../../CCreatureHandler.h"
  17. #include "../../IGameSettings.h"
  18. #include "../../TerrainHandler.h"
  19. #include "../../GameLibrary.h"
  20. #include "../../bonuses/Propagators.h"
  21. #include "../../constants/StringConstants.h"
  22. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  23. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  24. #include "../../modding/IdentifierStorage.h"
  25. #include "../../modding/ModScope.h"
  26. #include "../../spells/CSpellHandler.h"
  27. #include "../../texts/CGeneralTextHandler.h"
  28. #include "../../texts/CLegacyConfigParser.h"
  29. #include "../../json/JsonBonus.h"
  30. #include "../../json/JsonUtils.h"
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number
  33. CTownHandler::CTownHandler()
  34. : buildingsLibrary(JsonPath::builtin("config/buildingsLibrary"))
  35. , randomFaction(std::make_unique<CFaction>())
  36. {
  37. randomFaction->town = std::make_unique<CTown>();
  38. randomFaction->town->faction = randomFaction.get();
  39. randomFaction->identifier = "random";
  40. randomFaction->modScope = "core";
  41. }
  42. CTownHandler::~CTownHandler() = default;
  43. JsonNode readBuilding(CLegacyConfigParser & parser)
  44. {
  45. JsonNode ret;
  46. JsonNode & cost = ret["cost"];
  47. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  48. cost[resID].Float() = parser.readNumber();
  49. parser.endLine();
  50. return ret;
  51. }
  52. const TPropagatorPtr & CTownHandler::emptyPropagator()
  53. {
  54. static const TPropagatorPtr emptyProp(nullptr);
  55. return emptyProp;
  56. }
  57. std::vector<JsonNode> CTownHandler::loadLegacyData()
  58. {
  59. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_FACTION);
  60. std::vector<JsonNode> dest(dataSize);
  61. objects.resize(dataSize);
  62. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  63. {
  64. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  65. };
  66. CLegacyConfigParser parser(TextPath::builtin("DATA/BUILDING.TXT"));
  67. parser.endLine(); // header
  68. parser.endLine();
  69. //Unique buildings
  70. for (size_t town=0; town<dataSize; town++)
  71. {
  72. parser.endLine(); //header
  73. parser.endLine();
  74. int buildID = 17;
  75. do
  76. {
  77. getBuild(town, buildID) = readBuilding(parser);
  78. buildID++;
  79. }
  80. while (!parser.isNextEntryEmpty());
  81. }
  82. // Common buildings
  83. parser.endLine(); // header
  84. parser.endLine();
  85. parser.endLine();
  86. int buildID = 0;
  87. do
  88. {
  89. JsonNode building = readBuilding(parser);
  90. for (size_t town=0; town<dataSize; town++)
  91. getBuild(town, buildID) = building;
  92. buildID++;
  93. }
  94. while (!parser.isNextEntryEmpty());
  95. parser.endLine(); //header
  96. parser.endLine();
  97. //Dwellings
  98. for (size_t town=0; town<dataSize; town++)
  99. {
  100. parser.endLine(); //header
  101. parser.endLine();
  102. for (size_t i=0; i<14; i++)
  103. {
  104. getBuild(town, 30+i) = readBuilding(parser);
  105. }
  106. }
  107. {
  108. CLegacyConfigParser parser(TextPath::builtin("DATA/BLDGNEUT.TXT"));
  109. for(int building=0; building<15; building++)
  110. {
  111. std::string name = parser.readString();
  112. std::string descr = parser.readString();
  113. parser.endLine();
  114. for(int j=0; j<dataSize; j++)
  115. {
  116. getBuild(j, building)["name"].String() = name;
  117. getBuild(j, building)["description"].String() = descr;
  118. }
  119. }
  120. parser.endLine(); // silo
  121. parser.endLine(); // blacksmith //unused entries
  122. parser.endLine(); // moat
  123. //shipyard with the ship
  124. std::string name = parser.readString();
  125. std::string descr = parser.readString();
  126. parser.endLine();
  127. for(int town=0; town<dataSize; town++)
  128. {
  129. getBuild(town, 20)["name"].String() = name;
  130. getBuild(town, 20)["description"].String() = descr;
  131. }
  132. //blacksmith
  133. for(int town=0; town<dataSize; town++)
  134. {
  135. getBuild(town, 16)["name"].String() = parser.readString();
  136. getBuild(town, 16)["description"].String() = parser.readString();
  137. parser.endLine();
  138. }
  139. }
  140. {
  141. CLegacyConfigParser parser(TextPath::builtin("DATA/BLDGSPEC.TXT"));
  142. for(int town=0; town<dataSize; town++)
  143. {
  144. for(int build=0; build<9; build++)
  145. {
  146. getBuild(town, 17 + build)["name"].String() = parser.readString();
  147. getBuild(town, 17 + build)["description"].String() = parser.readString();
  148. parser.endLine();
  149. }
  150. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  151. getBuild(town, 26)["description"].String() = parser.readString();
  152. parser.endLine();
  153. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  154. getBuild(town, 15)["description"].String() = parser.readString();
  155. parser.endLine();
  156. }
  157. }
  158. {
  159. CLegacyConfigParser parser(TextPath::builtin("DATA/DWELLING.TXT"));
  160. for(int town=0; town<dataSize; town++)
  161. {
  162. for(int build=0; build<14; build++)
  163. {
  164. getBuild(town, 30 + build)["name"].String() = parser.readString();
  165. getBuild(town, 30 + build)["description"].String() = parser.readString();
  166. parser.endLine();
  167. }
  168. }
  169. }
  170. {
  171. CLegacyConfigParser typeParser(TextPath::builtin("DATA/TOWNTYPE.TXT"));
  172. CLegacyConfigParser nameParser(TextPath::builtin("DATA/TOWNNAME.TXT"));
  173. size_t townID=0;
  174. do
  175. {
  176. dest[townID]["name"].String() = typeParser.readString();
  177. for (int i=0; i<NAMES_PER_TOWN; i++)
  178. {
  179. JsonNode name;
  180. name.String() = nameParser.readString();
  181. dest[townID]["town"]["names"].Vector().push_back(name);
  182. nameParser.endLine();
  183. }
  184. townID++;
  185. }
  186. while (typeParser.endLine());
  187. }
  188. return dest;
  189. }
  190. void CTownHandler::loadBuildingRequirements(CBuilding * building, const JsonNode & source, std::vector<BuildingRequirementsHelper> & bidsToLoad) const
  191. {
  192. if (source.isNull())
  193. return;
  194. BuildingRequirementsHelper hlp;
  195. hlp.building = building;
  196. hlp.town = building->town;
  197. hlp.json = source;
  198. bidsToLoad.push_back(hlp);
  199. }
  200. void CTownHandler::loadBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building) const
  201. {
  202. for(const auto & b : source.Vector())
  203. {
  204. auto bonus = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::NONE, BonusSource::TOWN_STRUCTURE, 0, BonusSourceID(building->getUniqueTypeID()));
  205. if(!JsonUtils::parseBonus(b, bonus.get()))
  206. continue;
  207. if (bonus->description.empty() && (bonus->type == BonusType::MORALE || bonus->type == BonusType::LUCK))
  208. bonus->description.appendTextID(building->getNameTextID());
  209. //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty.
  210. assert(bonus->propagator == nullptr || bonus->propagator->getPropagatorType() != BonusNodeType::UNKNOWN);
  211. if(bonus->propagator != nullptr
  212. && bonus->propagator->getPropagatorType() == BonusNodeType::UNKNOWN)
  213. bonus->addPropagator(emptyPropagator());
  214. building->addNewBonus(bonus, bonusList);
  215. }
  216. }
  217. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  218. {
  219. assert(stringID.find(':') == std::string::npos);
  220. assert(!source.getModScope().empty());
  221. auto * ret = new CBuilding();
  222. ret->bid = BuildingID(source["id"].Integer());
  223. ret->subId = BuildingSubID::NONE;
  224. if (ret->bid == BuildingID::NONE)
  225. logMod->error("Building '%s' isn't recognized and won't work properly. Correct the typo or update VCMI.", stringID);
  226. ret->mode = ret->bid == BuildingID::GRAIL
  227. ? CBuilding::BUILD_GRAIL
  228. : vstd::find_or(CBuilding::MODES, source["mode"].String(), CBuilding::BUILD_NORMAL);
  229. ret->identifier = stringID;
  230. ret->modScope = source.getModScope();
  231. ret->town = town;
  232. LIBRARY->generaltexth->registerString(source.getModScope(), ret->getNameTextID(), source["name"]);
  233. LIBRARY->generaltexth->registerString(source.getModScope(), ret->getDescriptionTextID(), source["description"]);
  234. ret->subId = vstd::find_or(MappedKeys::SPECIAL_BUILDINGS, source["type"].String(), BuildingSubID::NONE);
  235. ret->resources.resolveFromJson(source["cost"]);
  236. //MODS COMPATIBILITY FOR pre-1.6
  237. bool produceEmpty = true;
  238. for(auto & res : source["produce"].Struct())
  239. if(res.second.Integer() != 0)
  240. produceEmpty = false;
  241. if(!produceEmpty)
  242. ret->produce.resolveFromJson(source["produce"]); // non legacy
  243. else if(ret->bid == BuildingID::RESOURCE_SILO)
  244. {
  245. logGlobal->warn("Resource silo in town '%s' does not produce any resources!", ret->town->faction->getJsonKey());
  246. switch (ret->town->primaryRes.toEnum())
  247. {
  248. case EGameResID::GOLD:
  249. ret->produce[ret->town->primaryRes] = 500;
  250. break;
  251. case EGameResID::WOOD_AND_ORE:
  252. ret->produce[EGameResID::WOOD] = 1;
  253. ret->produce[EGameResID::ORE] = 1;
  254. break;
  255. default:
  256. ret->produce[ret->town->primaryRes] = 1;
  257. break;
  258. }
  259. }
  260. ret->manualHeroVisit = source["manualHeroVisit"].Bool();
  261. ret->upgradeReplacesBonuses = source["upgradeReplacesBonuses"].Bool();
  262. const JsonNode & fortifications = source["fortifications"];
  263. if (!fortifications.isNull())
  264. {
  265. LIBRARY->identifiers()->requestIdentifierIfNotNull("creature", fortifications["citadelShooter"], [=](si32 identifier)
  266. {
  267. ret->fortifications.citadelShooter = CreatureID(identifier);
  268. });
  269. LIBRARY->identifiers()->requestIdentifierIfNotNull("creature", fortifications["upperTowerShooter"], [=](si32 identifier)
  270. {
  271. ret->fortifications.upperTowerShooter = CreatureID(identifier);
  272. });
  273. LIBRARY->identifiers()->requestIdentifierIfNotNull("creature", fortifications["lowerTowerShooter"], [=](si32 identifier)
  274. {
  275. ret->fortifications.lowerTowerShooter = CreatureID(identifier);
  276. });
  277. ret->fortifications.wallsHealth = fortifications["wallsHealth"].Integer();
  278. ret->fortifications.citadelHealth = fortifications["citadelHealth"].Integer();
  279. ret->fortifications.upperTowerHealth = fortifications["upperTowerHealth"].Integer();
  280. ret->fortifications.lowerTowerHealth = fortifications["lowerTowerHealth"].Integer();
  281. ret->fortifications.hasMoat = fortifications["hasMoat"].Bool();
  282. }
  283. loadBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret);
  284. if(!source["mapObjectLikeBonuses"].isNull())
  285. {
  286. LIBRARY->identifiers()->requestIdentifierIfNotNull("object", source["mapObjectLikeBonuses"], [ret](si32 identifier)
  287. {
  288. ret->mapObjectLikeBonuses = MapObjectID(identifier);
  289. });
  290. }
  291. if(!source["configuration"].isNull())
  292. ret->rewardableObjectInfo.init(source["configuration"], ret->getBaseTextID());
  293. loadBuildingRequirements(ret, source["requires"], requirementsToLoad);
  294. if (!source["warMachine"].isNull())
  295. {
  296. LIBRARY->identifiers()->requestIdentifier("artifact", source["warMachine"], [=](si32 identifier)
  297. {
  298. ret->warMachine = ArtifactID(identifier);
  299. });
  300. }
  301. if (!source["upgrades"].isNull())
  302. {
  303. // building id and upgrades can't be the same
  304. if(stringID == source["upgrades"].String())
  305. {
  306. auto townName = ret->town->faction->getNameTranslated();
  307. logMod->error("Building with ID '%s' of town '%s' can't be an upgrade of the same building.", stringID, townName);
  308. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.")
  309. % stringID % townName));
  310. }
  311. else
  312. {
  313. LIBRARY->identifiers()->requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  314. {
  315. ret->upgrade = BuildingID(identifier);
  316. });
  317. }
  318. }
  319. else
  320. ret->upgrade = BuildingID::NONE;
  321. if (ret->town->buildings[ret->bid] != nullptr)
  322. logMod->error("Mod %s, faction %s: detected multiple town buildings with ID %d", source.getModScope(), stringID, ret->bid.getNum());
  323. ret->town->buildings[ret->bid].reset(ret);
  324. for(const auto & element : source["marketModes"].Vector())
  325. {
  326. if(MappedKeys::MARKET_NAMES_TO_TYPES.count(element.String()))
  327. {
  328. auto mode = MappedKeys::MARKET_NAMES_TO_TYPES.at(element.String());
  329. ret->marketModes.insert(mode);
  330. if (mode == EMarketMode::RESOURCE_SKILL)
  331. {
  332. const auto & items = source["marketOffer"].Vector();
  333. ret->marketOffer.resize(items.size());
  334. for (int i = 0; i < items.size(); ++i)
  335. {
  336. LIBRARY->identifiers()->requestIdentifier("secondarySkill", items[i], [ret, i](si32 identifier)
  337. {
  338. ret->marketOffer[i] = SecondarySkill(identifier);
  339. });
  340. }
  341. }
  342. }
  343. }
  344. registerObject(source.getModScope(), ret->town->getBuildingScope(), ret->identifier, source, ret->bid.getNum());
  345. }
  346. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  347. {
  348. for(const auto & node : source.Struct())
  349. {
  350. if (!node.second.isNull())
  351. loadBuilding(town, node.first, node.second);
  352. }
  353. }
  354. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source) const
  355. {
  356. auto * ret = new CStructure();
  357. ret->building = nullptr;
  358. ret->buildable = nullptr;
  359. LIBRARY->identifiers()->tryRequestIdentifier( source.getModScope(), "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  360. {
  361. ret->building = town.buildings[BuildingID(identifier)].get();
  362. });
  363. if (source["builds"].isNull())
  364. {
  365. LIBRARY->identifiers()->tryRequestIdentifier( source.getModScope(), "building." + town.faction->getJsonKey(), stringID, [=, &town](si32 identifier) mutable
  366. {
  367. ret->building = town.buildings[BuildingID(identifier)].get();
  368. });
  369. }
  370. else
  371. {
  372. LIBRARY->identifiers()->requestIdentifier("building." + town.faction->getJsonKey(), source["builds"], [=, &town](si32 identifier) mutable
  373. {
  374. ret->buildable = town.buildings[BuildingID(identifier)].get();
  375. });
  376. }
  377. ret->identifier = stringID;
  378. ret->pos.x = static_cast<si32>(source["x"].Float());
  379. ret->pos.y = static_cast<si32>(source["y"].Float());
  380. ret->pos.z = static_cast<si32>(source["z"].Float());
  381. ret->hiddenUpgrade = source["hidden"].Bool();
  382. ret->defName = AnimationPath::fromJson(source["animation"]);
  383. ret->borderName = ImagePath::fromJson(source["border"]);
  384. ret->campaignBonus = ImagePath::fromJson(source["campaignBonus"]);
  385. ret->areaName = ImagePath::fromJson(source["area"]);
  386. town.clientInfo.structures.emplace_back(ret);
  387. }
  388. void CTownHandler::loadStructures(CTown &town, const JsonNode & source) const
  389. {
  390. for(const auto & node : source.Struct())
  391. {
  392. if (!node.second.isNull())
  393. loadStructure(town, node.first, node.second);
  394. }
  395. }
  396. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source) const
  397. {
  398. auto & dstSlots = town.clientInfo.hallSlots;
  399. const auto & srcSlots = source.Vector();
  400. dstSlots.resize(srcSlots.size());
  401. for(size_t i=0; i<dstSlots.size(); i++)
  402. {
  403. auto & dstRow = dstSlots[i];
  404. const auto & srcRow = srcSlots[i].Vector();
  405. dstRow.resize(srcRow.size());
  406. for(size_t j=0; j < dstRow.size(); j++)
  407. {
  408. auto & dstBox = dstRow[j];
  409. const auto & srcBox = srcRow[j].Vector();
  410. dstBox.resize(srcBox.size());
  411. for(size_t k=0; k<dstBox.size(); k++)
  412. {
  413. auto & dst = dstBox[k];
  414. const auto & src = srcBox[k];
  415. LIBRARY->identifiers()->requestIdentifier("building." + town.faction->getJsonKey(), src, [&](si32 identifier)
  416. {
  417. dst = BuildingID(identifier);
  418. });
  419. }
  420. }
  421. }
  422. }
  423. Point JsonToPoint(const JsonNode & node)
  424. {
  425. if(!node.isStruct())
  426. return Point::makeInvalid();
  427. Point ret;
  428. ret.x = static_cast<si32>(node["x"].Float());
  429. ret.y = static_cast<si32>(node["y"].Float());
  430. return ret;
  431. }
  432. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source) const
  433. {
  434. if(source["imagePrefix"].isString())
  435. town.clientInfo.siegePrefix = {
  436. { MapLayerId::SURFACE, source["imagePrefix"].String() },
  437. { MapLayerId::UNDERGROUND, source["imagePrefix"].String() },
  438. { MapLayerId::UNKNOWN, source["imagePrefix"].String() }
  439. };
  440. else
  441. {
  442. auto layers = source["imagePrefix"].Struct();
  443. for(auto & layer : layers)
  444. {
  445. auto text = layer.second.String();
  446. LIBRARY->identifiers()->requestIdentifier(layer.second.getModScope(), "mapLayer", layer.first, [&town, text](int32_t idx)
  447. {
  448. town.clientInfo.siegePrefix[MapLayerId(idx)] = text;
  449. });
  450. }
  451. }
  452. town.clientInfo.towerIconSmall = source["towerIconSmall"].String();
  453. town.clientInfo.towerIconLarge = source["towerIconLarge"].String();
  454. LIBRARY->identifiers()->requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  455. {
  456. auto crId = CreatureID(creature);
  457. if((*LIBRARY->creh)[crId]->animation.missileFrameAngles.empty())
  458. 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!"
  459. , town.faction->getNameTranslated()
  460. , (*LIBRARY->creh)[crId]->getNameSingularTranslated());
  461. town.fortifications.citadelShooter = crId;
  462. town.fortifications.upperTowerShooter = crId;
  463. town.fortifications.lowerTowerShooter = crId;
  464. });
  465. auto & pos = town.clientInfo.siegePositions;
  466. pos.resize(21);
  467. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  468. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  469. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  470. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  471. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  472. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  473. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  474. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  475. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  476. pos[9] = JsonToPoint(source["gate"]["gate"]);
  477. pos[10] = JsonToPoint(source["gate"]["arch"]);
  478. pos[7] = JsonToPoint(source["walls"]["upper"]);
  479. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  480. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  481. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  482. pos[13] = JsonToPoint(source["moat"]["moat"]);
  483. pos[14] = JsonToPoint(source["moat"]["bank"]);
  484. pos[11] = JsonToPoint(source["static"]["bottom"]);
  485. pos[12] = JsonToPoint(source["static"]["top"]);
  486. pos[1] = JsonToPoint(source["static"]["background"]);
  487. }
  488. static void readIcon(JsonNode source, std::string & small, std::string & large)
  489. {
  490. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  491. {
  492. small = source["small"].String();
  493. large = source["large"].String();
  494. }
  495. }
  496. void CTownHandler::loadClientData(CTown &town, const JsonNode & source) const
  497. {
  498. CTown::ClientInfo & info = town.clientInfo;
  499. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  500. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  501. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  502. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  503. info.hallBackground = ImagePath::fromJson(source["hallBackground"]);
  504. info.townBackground = ImagePath::fromJson(source["townBackground"]);
  505. info.buildingsIcons = AnimationPath::fromJson(source["buildingsIcons"]);
  506. info.tavernVideo = VideoPath::fromJson(source["tavernVideo"]);
  507. info.guildWindowPosition = Point(source["guildWindowPosition"]["x"].Integer(), source["guildWindowPosition"]["y"].Integer());
  508. info.guildSpellPositions.clear();
  509. for(auto & level : source["guildSpellPositions"].Vector())
  510. {
  511. std::vector<Point> points;
  512. for(auto & item : level.Vector())
  513. points.push_back(Point(item["x"].Integer(), item["y"].Integer()));
  514. info.guildSpellPositions.push_back(points);
  515. }
  516. auto loadStringOrVector = [](auto & target, auto & node, auto fromJsonFunc){
  517. if(node.isVector())
  518. {
  519. target.clear();
  520. for(auto & background : node.Vector())
  521. target.push_back(fromJsonFunc(background));
  522. }
  523. else
  524. target = {fromJsonFunc(node)};
  525. };
  526. loadStringOrVector(info.musicTheme, source["musicTheme"], AudioPath::fromJson);
  527. loadStringOrVector(info.guildBackground, source["guildBackground"], ImagePath::fromJson);
  528. loadStringOrVector(info.guildWindow, source["guildWindow"], ImagePath::fromJson);
  529. loadTownHall(town, source["hallSlots"]);
  530. loadStructures(town, source["structures"]);
  531. loadSiegeScreen(town, source["siege"]);
  532. }
  533. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  534. {
  535. const auto * resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  536. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  537. town->primaryRes = GameResID(EGameResID::WOOD_AND_ORE); //Wood + Ore
  538. else
  539. town->primaryRes = GameResID(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  540. if (!source["warMachine"].isNull())
  541. {
  542. LIBRARY->identifiers()->requestIdentifier( "creature", source["warMachine"], [=](si32 creatureID)
  543. {
  544. town->warMachineDeprecated = creatureID;
  545. });
  546. }
  547. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  548. town->namesCount = 0;
  549. for(const auto & name : source["names"].Vector())
  550. {
  551. LIBRARY->generaltexth->registerString(town->faction->modScope, town->getRandomNameTextID(town->namesCount), name);
  552. town->namesCount += 1;
  553. }
  554. if (!source["moatAbility"].isNull()) // VCMI 1.2 compatibility code
  555. {
  556. LIBRARY->identifiers()->requestIdentifier( "spell", source["moatAbility"], [=](si32 ability)
  557. {
  558. town->fortifications.moatSpell = SpellID(ability);
  559. });
  560. }
  561. else
  562. {
  563. LIBRARY->identifiers()->requestIdentifier( source.getModScope(), "spell", "castleMoat", [=](si32 ability)
  564. {
  565. town->fortifications.moatSpell = SpellID(ability);
  566. });
  567. }
  568. // Horde building creature level
  569. for(const JsonNode &node : source["horde"].Vector())
  570. town->hordeLvl[static_cast<int>(town->hordeLvl.size())] = static_cast<int>(node.Float());
  571. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  572. // but anything below 2 must be handled here
  573. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  574. town->hordeLvl[static_cast<int>(i)] = -1;
  575. const JsonVector & creatures = source["creatures"].Vector();
  576. town->creatures.resize(creatures.size());
  577. for (size_t i=0; i< creatures.size(); i++)
  578. {
  579. const JsonVector & level = creatures[i].Vector();
  580. town->creatures[i].resize(level.size());
  581. for (size_t j=0; j<level.size(); j++)
  582. {
  583. LIBRARY->identifiers()->requestIdentifier("creature", level[j], [=](si32 creature)
  584. {
  585. town->creatures[i][j] = CreatureID(creature);
  586. });
  587. }
  588. }
  589. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  590. /// set chance of specific hero class to appear in this town
  591. for(const auto & node : source["tavern"].Struct())
  592. {
  593. int chance = static_cast<int>(node.second.Float());
  594. LIBRARY->identifiers()->requestIdentifierIfFound(node.second.getModScope(), "heroClass", node.first, [=](si32 classID)
  595. {
  596. LIBRARY->heroclassesh->objects[classID]->selectionProbability[town->faction->getId()] = chance;
  597. });
  598. }
  599. for(const auto & node : source["guildSpells"].Struct())
  600. {
  601. int chance = static_cast<int>(node.second.Float());
  602. LIBRARY->identifiers()->requestIdentifierIfFound(node.second.getModScope(), "spell", node.first, [=](si32 spellID)
  603. {
  604. LIBRARY->spellh->objects.at(spellID)->probabilities[town->faction->getId()] = chance;
  605. });
  606. }
  607. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  608. {
  609. town->dwellings.push_back(d["graphics"].String());
  610. town->dwellingNames.push_back(d["name"].String());
  611. }
  612. loadBuildings(town, source["buildings"]);
  613. loadClientData(*town, source);
  614. }
  615. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source) const
  616. {
  617. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  618. std::string prefix = source["prefix"].String();
  619. for(const JsonNode &piece : source["pieces"].Vector())
  620. {
  621. size_t index = faction.puzzleMap.size();
  622. SPuzzleInfo spi;
  623. spi.position.x = static_cast<si16>(piece["x"].Float());
  624. spi.position.y = static_cast<si16>(piece["y"].Float());
  625. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  626. spi.number = static_cast<ui16>(index);
  627. // filename calculation
  628. std::ostringstream suffix;
  629. suffix << std::setfill('0') << std::setw(2) << index;
  630. spi.filename = ImagePath::builtinTODO(prefix + suffix.str());
  631. faction.puzzleMap.push_back(spi);
  632. }
  633. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  634. }
  635. std::shared_ptr<CFaction> CTownHandler::loadFromJson(const std::string & scope, const JsonNode & source, const std::string & identifier, size_t index)
  636. {
  637. assert(identifier.find(':') == std::string::npos);
  638. auto faction = std::make_shared<CFaction>();
  639. faction->index = static_cast<FactionID>(index);
  640. faction->modScope = scope;
  641. faction->identifier = identifier;
  642. LIBRARY->generaltexth->registerString(scope, faction->getNameTextID(), source["name"]);
  643. LIBRARY->generaltexth->registerString(scope, faction->getDescriptionTextID(), source["description"]);
  644. faction->creatureBg120 = ImagePath::fromJson(source["creatureBackground"]["120px"]);
  645. faction->creatureBg130 = ImagePath::fromJson(source["creatureBackground"]["130px"]);
  646. faction->boatType = BoatId::CASTLE; //Do not crash
  647. if (!source["boat"].isNull())
  648. {
  649. LIBRARY->identifiers()->requestIdentifier("core:boat", source["boat"], [=](int32_t boatTypeID)
  650. {
  651. faction->boatType = BoatId(boatTypeID);
  652. });
  653. }
  654. int alignment = vstd::find_pos(GameConstants::ALIGNMENT_NAMES, source["alignment"].String());
  655. if (alignment == -1)
  656. faction->alignment = EAlignment::NEUTRAL;
  657. else
  658. faction->alignment = static_cast<EAlignment>(alignment);
  659. auto preferUndergound = source["preferUndergroundPlacement"];
  660. faction->preferUndergroundPlacement = preferUndergound.isNull() ? false : preferUndergound.Bool();
  661. faction->special = source["special"].Bool();
  662. // NOTE: semi-workaround - normally, towns are supposed to have native terrains.
  663. // Towns without one are exceptions. So, vcmi requires nativeTerrain to be defined
  664. // But allows it to be defined with explicit value of "none" if town should not have native terrain
  665. // This is better than allowing such terrain-less towns silently, leading to issues with RMG
  666. faction->nativeTerrain = ETerrainId::NONE;
  667. if (!source["nativeTerrain"].isNull() && source["nativeTerrain"].String() != "none")
  668. {
  669. LIBRARY->identifiers()->requestIdentifier("terrain", source["nativeTerrain"], [=](int32_t index){
  670. faction->nativeTerrain = TerrainId(index);
  671. });
  672. }
  673. if (!source["town"].isNull())
  674. {
  675. faction->town = std::make_unique<CTown>();
  676. faction->town->faction = faction.get();
  677. loadTown(faction->town.get(), source["town"]);
  678. }
  679. else
  680. faction->town = nullptr;
  681. if (!source["puzzleMap"].isNull())
  682. loadPuzzle(*faction, source["puzzleMap"]);
  683. return faction;
  684. }
  685. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  686. {
  687. auto object = loadFromJson(scope, data, name, objects.size());
  688. objects.emplace_back(object);
  689. if (object->town)
  690. {
  691. auto & info = object->town->clientInfo;
  692. info.icons[0][0] = 8 + object->index.getNum() * 4 + 0;
  693. info.icons[0][1] = 8 + object->index.getNum() * 4 + 1;
  694. info.icons[1][0] = 8 + object->index.getNum() * 4 + 2;
  695. info.icons[1][1] = 8 + object->index.getNum() * 4 + 3;
  696. LIBRARY->identifiers()->requestIdentifier(scope, "object", "town", [=](si32 index)
  697. {
  698. // register town once objects are loaded
  699. JsonNode config = data["town"]["mapObject"];
  700. config["faction"].String() = name;
  701. config["faction"].setModScope(scope, false);
  702. if (config.getModScope().empty())// MODS COMPATIBILITY FOR 0.96
  703. config.setModScope(scope, false);
  704. LIBRARY->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  705. // MODS COMPATIBILITY FOR 0.96
  706. const auto & advMap = data["town"]["adventureMap"];
  707. if (!advMap.isNull())
  708. {
  709. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  710. JsonNode config;
  711. config["animation"] = advMap["castle"];
  712. LIBRARY->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  713. }
  714. });
  715. }
  716. registerObject(scope, "faction", name, data, object->index.getNum());
  717. }
  718. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  719. {
  720. auto object = loadFromJson(scope, data, name, index);
  721. if (objects.size() > index)
  722. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  723. else
  724. objects.resize(index + 1);
  725. objects[index] = object;
  726. if (object->town)
  727. {
  728. auto & info = object->town->clientInfo;
  729. info.icons[0][0] = (GameConstants::F_NUMBER + object->index.getNum()) * 2 + 0;
  730. info.icons[0][1] = (GameConstants::F_NUMBER + object->index.getNum()) * 2 + 1;
  731. info.icons[1][0] = object->index.getNum() * 2 + 0;
  732. info.icons[1][1] = object->index.getNum() * 2 + 1;
  733. LIBRARY->identifiers()->requestIdentifier(scope, "object", "town", [=](si32 index)
  734. {
  735. // register town once objects are loaded
  736. JsonNode config = data["town"]["mapObject"];
  737. config["faction"].String() = name;
  738. config["faction"].setModScope(scope, false);
  739. LIBRARY->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  740. });
  741. }
  742. registerObject(scope, "faction", name, data, object->index.getNum());
  743. }
  744. void CTownHandler::loadRandomFaction()
  745. {
  746. JsonNode randomFactionJson(JsonPath::builtin("config/factions/random.json"));
  747. randomFactionJson.setModScope(ModScope::scopeBuiltin(), true);
  748. loadBuildings(randomFaction->town.get(), randomFactionJson["random"]["town"]["buildings"]);
  749. }
  750. void CTownHandler::loadCustom()
  751. {
  752. loadRandomFaction();
  753. }
  754. void CTownHandler::beforeValidate(JsonNode & object)
  755. {
  756. if (object.Struct().count("town") == 0)
  757. return;
  758. const auto & inheritBuilding = [this](const std::string & name, JsonNode & target)
  759. {
  760. if(buildingsLibrary.Struct().count(name) == 0)
  761. {
  762. if(!target.Struct().count("id"))
  763. logMod->warn("Mod '%s': Town building '%s' lack ID.", target.getModScope(), name);
  764. return;
  765. }
  766. JsonNode baseCopy(buildingsLibrary[name]);
  767. if (target.Struct().count("id") && baseCopy.Struct().count("id"))
  768. {
  769. logMod->warn("Mod '%s': Town building '%s' has specified 'id' field for a predefined building! Ignoring this field.", target["id"].getModScope(), name);
  770. target.Struct().erase("id");
  771. }
  772. baseCopy.setModScope(target.getModScope());
  773. JsonUtils::inherit(target, baseCopy);
  774. };
  775. for (auto & building : object["town"]["buildings"].Struct())
  776. {
  777. if (building.second.isNull())
  778. continue;
  779. inheritBuilding(building.first, building.second);
  780. if (building.second.Struct().count("type"))
  781. inheritBuilding(building.second["type"].String(), building.second);
  782. // MODS COMPATIBILITY FOR pre-1.6
  783. // convert old buildigns with onVisitBonuses into configurable building
  784. if (building.second.Struct().count("onVisitBonuses"))
  785. {
  786. building.second["configuration"]["visitMode"] = JsonNode("bonus");
  787. building.second["configuration"]["rewards"][0]["message"] = building.second["description"];
  788. building.second["configuration"]["rewards"][0]["bonuses"] = building.second["onVisitBonuses"];
  789. }
  790. }
  791. }
  792. void CTownHandler::afterLoadFinalization()
  793. {
  794. initializeRequirements();
  795. }
  796. void CTownHandler::initializeRequirements()
  797. {
  798. // must be done separately after all ID's are known
  799. for (auto & requirement : requirementsToLoad)
  800. {
  801. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  802. {
  803. if (node.Vector().size() > 1)
  804. {
  805. logMod->error("Unexpected length of town buildings requirements: %d", node.Vector().size());
  806. logMod->error("Entry contains: ");
  807. logMod->error(node.toString());
  808. }
  809. auto index = LIBRARY->identifiers()->getIdentifier(requirement.town->getBuildingScope(), node[0]);
  810. if (!index.has_value())
  811. {
  812. logMod->error("Unknown building in town buildings: %s", node[0].String());
  813. return BuildingID::NONE;
  814. }
  815. return BuildingID(index.value());
  816. });
  817. }
  818. requirementsToLoad.clear();
  819. }
  820. std::set<FactionID> CTownHandler::getDefaultAllowed() const
  821. {
  822. std::set<FactionID> allowedFactions;
  823. for(const auto & town : objects)
  824. if (town->town != nullptr && !town->special)
  825. allowedFactions.insert(town->getId());
  826. return allowedFactions;
  827. }
  828. std::set<FactionID> CTownHandler::getAllowedFactions(bool withTown) const
  829. {
  830. if (withTown)
  831. return getDefaultAllowed();
  832. std::set<FactionID> result;
  833. for(const auto & town : objects)
  834. result.insert(town->getId());
  835. return result;
  836. }
  837. const std::vector<std::string> & CTownHandler::getTypeNames() const
  838. {
  839. static const std::vector<std::string> typeNames = { "faction", "town" };
  840. return typeNames;
  841. }
  842. VCMI_LIB_NAMESPACE_END