CTownHandler.cpp 36 KB

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