CTownHandler.cpp 31 KB

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