CTownHandler.cpp 36 KB

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