CTownHandler.cpp 34 KB

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