CTownHandler.cpp 31 KB

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