CTownHandler.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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. const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number
  25. const std::map<std::string, CBuilding::EBuildMode> CBuilding::MODES =
  26. {
  27. { "normal", CBuilding::BUILD_NORMAL },
  28. { "auto", CBuilding::BUILD_AUTO },
  29. { "special", CBuilding::BUILD_SPECIAL },
  30. { "grail", CBuilding::BUILD_GRAIL }
  31. };
  32. const std::map<std::string, CBuilding::ETowerHeight> CBuilding::TOWER_TYPES =
  33. {
  34. { "low", CBuilding::HEIGHT_LOW },
  35. { "average", CBuilding::HEIGHT_AVERAGE },
  36. { "high", CBuilding::HEIGHT_HIGH },
  37. { "skyship", CBuilding::HEIGHT_SKYSHIP }
  38. };
  39. const std::string & CBuilding::Name() const
  40. {
  41. return name;
  42. }
  43. const std::string & CBuilding::Description() const
  44. {
  45. return description;
  46. }
  47. BuildingID CBuilding::getBase() const
  48. {
  49. const CBuilding * build = this;
  50. while (build->upgrade >= 0)
  51. {
  52. build = build->town->buildings.at(build->upgrade);
  53. }
  54. return build->bid;
  55. }
  56. si32 CBuilding::getDistance(BuildingID buildID) const
  57. {
  58. const CBuilding * build = town->buildings.at(buildID);
  59. int distance = 0;
  60. while (build->upgrade >= 0 && build != this)
  61. {
  62. build = build->town->buildings.at(build->upgrade);
  63. distance++;
  64. }
  65. if (build == this)
  66. return distance;
  67. return -1;
  68. }
  69. void CBuilding::deserializeFix()
  70. {
  71. //default value for mode was broken, have to fix it here for old saves (v777 and older)
  72. switch(mode)
  73. {
  74. case BUILD_NORMAL:
  75. case BUILD_AUTO:
  76. case BUILD_SPECIAL:
  77. case BUILD_GRAIL:
  78. break;
  79. default:
  80. mode = BUILD_NORMAL;
  81. break;
  82. }
  83. }
  84. void CBuilding::update792(const BuildingID & bid, BuildingSubID::EBuildingSubID & subId, ETowerHeight & height)
  85. {
  86. subId = BuildingSubID::NONE;
  87. height = ETowerHeight::HEIGHT_NO_TOWER;
  88. if(!bid.IsSpecialOrGrail() || town == nullptr || town->faction == nullptr || town->faction->identifier.empty())
  89. return;
  90. const auto buildingName = CTownHandler::getMappedValue<std::string, BuildingID>(bid, std::string(), MappedKeys::BUILDING_TYPES_TO_NAMES);
  91. if(buildingName.empty())
  92. return;
  93. const auto & faction = town->faction->identifier;
  94. auto factionsContent = (*VLC->modh->content)["factions"];
  95. auto & coreData = factionsContent.modData.at("core");
  96. auto & coreFactions = coreData.modData;
  97. auto & currentFaction = coreFactions[faction];
  98. if (currentFaction.isNull())
  99. {
  100. const auto index = faction.find(':');
  101. const std::string factionDir = index == std::string::npos ? faction : faction.substr(0, index);
  102. const auto it = factionsContent.modData.find(factionDir);
  103. if (it == factionsContent.modData.end())
  104. {
  105. logMod->warn("Warning: Update old save failed: Faction: '%s' is not found.", factionDir);
  106. return;
  107. }
  108. const std::string modFaction = index == std::string::npos ? faction : faction.substr(index + 1);
  109. currentFaction = it->second.modData[modFaction];
  110. }
  111. if (!currentFaction.isNull() && currentFaction.getType() == JsonNode::JsonType::DATA_STRUCT)
  112. {
  113. const auto & buildings = currentFaction["town"]["buildings"];
  114. const auto & currentBuilding = buildings[buildingName];
  115. subId = CTownHandler::getMappedValue<BuildingSubID::EBuildingSubID>(currentBuilding["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  116. height = CBuilding::HEIGHT_NO_TOWER;
  117. if (subId == BuildingSubID::LOOKOUT_TOWER || bid == BuildingID::GRAIL)
  118. height = CTownHandler::getMappedValue<CBuilding::ETowerHeight>(currentBuilding["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES);
  119. }
  120. }
  121. CFaction::CFaction()
  122. {
  123. town = nullptr;
  124. index = 0;
  125. alignment = EAlignment::NEUTRAL;
  126. }
  127. CFaction::~CFaction()
  128. {
  129. delete town;
  130. }
  131. CTown::CTown()
  132. : faction(nullptr), mageLevel(0), primaryRes(0), moatDamage(0), defaultTavernChance(0)
  133. {
  134. }
  135. CTown::~CTown()
  136. {
  137. for(auto & build : buildings)
  138. build.second.dellNull();
  139. for(auto & str : clientInfo.structures)
  140. str.dellNull();
  141. }
  142. std::vector<BattleHex> CTown::defaultMoatHexes()
  143. {
  144. static const std::vector<BattleHex> moatHexes = {11, 28, 44, 61, 77, 111, 129, 146, 164, 181};
  145. return moatHexes;
  146. }
  147. std::string CTown::getFactionName() 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. CTownHandler::CTownHandler()
  172. {
  173. VLC->townh = this;
  174. randomTown = new CTown();
  175. }
  176. CTownHandler::~CTownHandler()
  177. {
  178. delete randomTown;
  179. for(auto faction : factions)
  180. faction.dellNull();
  181. }
  182. JsonNode readBuilding(CLegacyConfigParser & parser)
  183. {
  184. JsonNode ret;
  185. JsonNode & cost = ret["cost"];
  186. //note: this code will try to parse mithril as well but wil always return 0 for it
  187. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  188. cost[resID].Float() = parser.readNumber();
  189. cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator
  190. parser.endLine();
  191. return ret;
  192. }
  193. std::vector<JsonNode> CTownHandler::loadLegacyData(size_t dataSize)
  194. {
  195. std::vector<JsonNode> dest(dataSize);
  196. factions.resize(dataSize);
  197. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  198. {
  199. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  200. };
  201. CLegacyConfigParser parser("DATA/BUILDING.TXT");
  202. parser.endLine(); // header
  203. parser.endLine();
  204. //Unique buildings
  205. for (size_t town=0; town<dataSize; town++)
  206. {
  207. parser.endLine(); //header
  208. parser.endLine();
  209. int buildID = 17;
  210. do
  211. {
  212. getBuild(town, buildID) = readBuilding(parser);
  213. buildID++;
  214. }
  215. while (!parser.isNextEntryEmpty());
  216. }
  217. // Common buildings
  218. parser.endLine(); // header
  219. parser.endLine();
  220. parser.endLine();
  221. int buildID = 0;
  222. do
  223. {
  224. JsonNode building = readBuilding(parser);
  225. for (size_t town=0; town<dataSize; town++)
  226. getBuild(town, buildID) = building;
  227. buildID++;
  228. }
  229. while (!parser.isNextEntryEmpty());
  230. parser.endLine(); //header
  231. parser.endLine();
  232. //Dwellings
  233. for (size_t town=0; town<dataSize; town++)
  234. {
  235. parser.endLine(); //header
  236. parser.endLine();
  237. for (size_t i=0; i<14; i++)
  238. {
  239. getBuild(town, 30+i) = readBuilding(parser);
  240. }
  241. }
  242. {
  243. CLegacyConfigParser parser("DATA/BLDGNEUT.TXT");
  244. for(int building=0; building<15; building++)
  245. {
  246. std::string name = parser.readString();
  247. std::string descr = parser.readString();
  248. parser.endLine();
  249. for(int j=0; j<dataSize; j++)
  250. {
  251. getBuild(j, building)["name"].String() = name;
  252. getBuild(j, building)["description"].String() = descr;
  253. }
  254. }
  255. parser.endLine(); // silo
  256. parser.endLine(); // blacksmith //unused entries
  257. parser.endLine(); // moat
  258. //shipyard with the ship
  259. std::string name = parser.readString();
  260. std::string descr = parser.readString();
  261. parser.endLine();
  262. for(int town=0; town<dataSize; town++)
  263. {
  264. getBuild(town, 20)["name"].String() = name;
  265. getBuild(town, 20)["description"].String() = descr;
  266. }
  267. //blacksmith
  268. for(int town=0; town<dataSize; town++)
  269. {
  270. getBuild(town, 16)["name"].String() = parser.readString();
  271. getBuild(town, 16)["description"].String() = parser.readString();
  272. parser.endLine();
  273. }
  274. }
  275. {
  276. CLegacyConfigParser parser("DATA/BLDGSPEC.TXT");
  277. for(int town=0; town<dataSize; town++)
  278. {
  279. for(int build=0; build<9; build++)
  280. {
  281. getBuild(town, 17 + build)["name"].String() = parser.readString();
  282. getBuild(town, 17 + build)["description"].String() = parser.readString();
  283. parser.endLine();
  284. }
  285. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  286. getBuild(town, 26)["description"].String() = parser.readString();
  287. parser.endLine();
  288. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  289. getBuild(town, 15)["description"].String() = parser.readString();
  290. parser.endLine();
  291. }
  292. }
  293. {
  294. CLegacyConfigParser parser("DATA/DWELLING.TXT");
  295. for(int town=0; town<dataSize; town++)
  296. {
  297. for(int build=0; build<14; build++)
  298. {
  299. getBuild(town, 30 + build)["name"].String() = parser.readString();
  300. getBuild(town, 30 + build)["description"].String() = parser.readString();
  301. parser.endLine();
  302. }
  303. }
  304. }
  305. {
  306. CLegacyConfigParser typeParser("DATA/TOWNTYPE.TXT");
  307. CLegacyConfigParser nameParser("DATA/TOWNNAME.TXT");
  308. size_t townID=0;
  309. do
  310. {
  311. dest[townID]["name"].String() = typeParser.readString();
  312. for (int i=0; i<NAMES_PER_TOWN; i++)
  313. {
  314. JsonNode name;
  315. name.String() = nameParser.readString();
  316. dest[townID]["town"]["names"].Vector().push_back(name);
  317. nameParser.endLine();
  318. }
  319. townID++;
  320. }
  321. while (typeParser.endLine());
  322. }
  323. return dest;
  324. }
  325. void CTownHandler::loadBuildingRequirements(CBuilding * building, const JsonNode & source)
  326. {
  327. if (source.isNull())
  328. return;
  329. BuildingRequirementsHelper hlp;
  330. hlp.building = building;
  331. hlp.town = building->town;
  332. hlp.json = source;
  333. requirementsToLoad.push_back(hlp);
  334. }
  335. template<typename R, typename K>
  336. R CTownHandler::getMappedValue(const K key, const R defval, const std::map<K, R> & map, bool required)
  337. {
  338. auto it = map.find(key);
  339. if(it != map.end())
  340. return it->second;
  341. if(required)
  342. logMod->warn("Warning: Property: '%s' is unknown. Correct the typo or update VCMI.", key);
  343. return defval;
  344. }
  345. template<typename R>
  346. R CTownHandler::getMappedValue(const JsonNode & node, const R defval, const std::map<std::string, R> & map, bool required)
  347. {
  348. if(!node.isNull() && node.getType() == JsonNode::JsonType::DATA_STRING)
  349. return getMappedValue<R, std::string>(node.String(), defval, map, required);
  350. return defval;
  351. }
  352. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  353. {
  354. auto ret = new CBuilding();
  355. ret->bid = getMappedValue<BuildingID, std::string>(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false);
  356. if(ret->bid == BuildingID::NONE)
  357. ret->bid = source["id"].isNull() ? BuildingID(BuildingID::NONE) : BuildingID(source["id"].Float());
  358. if (ret->bid == BuildingID::NONE)
  359. logMod->error("Error: Building '%s' has not internal ID and won't work properly. Correct the typo or update VCMI.", stringID);
  360. ret->mode = ret->bid == BuildingID::GRAIL
  361. ? CBuilding::BUILD_GRAIL
  362. : getMappedValue<CBuilding::EBuildMode>(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES);
  363. ret->subId = getMappedValue<BuildingSubID::EBuildingSubID>(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS);
  364. ret->height = CBuilding::HEIGHT_NO_TOWER;
  365. if(ret->subId == BuildingSubID::LOOKOUT_TOWER
  366. || ret->bid == BuildingID::GRAIL)
  367. ret->height = getMappedValue<CBuilding::ETowerHeight>(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES);
  368. ret->identifier = stringID;
  369. ret->town = town;
  370. ret->name = source["name"].String();
  371. ret->description = source["description"].String();
  372. ret->resources = TResources(source["cost"]);
  373. ret->produce = TResources(source["produce"]);
  374. //MODS COMPATIBILITY FOR 0.96
  375. if(!ret->produce.nonZero())
  376. {
  377. switch (ret->bid) {
  378. break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500;
  379. break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000;
  380. break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000;
  381. break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000;
  382. break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000;
  383. break; case BuildingID::RESOURCE_SILO :
  384. {
  385. switch (ret->town->primaryRes)
  386. {
  387. case Res::GOLD:
  388. ret->produce[ret->town->primaryRes] = 500;
  389. break;
  390. case Res::WOOD_AND_ORE:
  391. ret->produce[Res::WOOD] = 1;
  392. ret->produce[Res::ORE] = 1;
  393. break;
  394. default:
  395. ret->produce[ret->town->primaryRes] = 1;
  396. break;
  397. }
  398. }
  399. }
  400. }
  401. loadBuildingRequirements(ret, source["requires"]);
  402. if (!source["upgrades"].isNull())
  403. {
  404. // building id and upgrades can't be the same
  405. if(stringID == source["upgrades"].String())
  406. {
  407. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  408. stringID % ret->town->getFactionName()));
  409. }
  410. VLC->modh->identifiers.requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  411. {
  412. ret->upgrade = BuildingID(identifier);
  413. });
  414. }
  415. else
  416. ret->upgrade = BuildingID::NONE;
  417. ret->town->buildings[ret->bid] = ret;
  418. VLC->modh->identifiers.registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid);
  419. }
  420. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  421. {
  422. for(auto & node : source.Struct())
  423. {
  424. if (!node.second.isNull())
  425. {
  426. loadBuilding(town, node.first, node.second);
  427. }
  428. }
  429. }
  430. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source)
  431. {
  432. auto ret = new CStructure();
  433. ret->building = nullptr;
  434. ret->buildable = nullptr;
  435. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  436. {
  437. ret->building = town.buildings[BuildingID(identifier)];
  438. });
  439. if (source["builds"].isNull())
  440. {
  441. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  442. {
  443. ret->building = town.buildings[BuildingID(identifier)];
  444. });
  445. }
  446. else
  447. {
  448. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable
  449. {
  450. ret->buildable = town.buildings[BuildingID(identifier)];
  451. });
  452. }
  453. ret->identifier = stringID;
  454. ret->pos.x = static_cast<si32>(source["x"].Float());
  455. ret->pos.y = static_cast<si32>(source["y"].Float());
  456. ret->pos.z = static_cast<si32>(source["z"].Float());
  457. ret->hiddenUpgrade = source["hidden"].Bool();
  458. ret->defName = source["animation"].String();
  459. ret->borderName = source["border"].String();
  460. ret->areaName = source["area"].String();
  461. town.clientInfo.structures.push_back(ret);
  462. }
  463. void CTownHandler::loadStructures(CTown &town, const JsonNode & source)
  464. {
  465. for(auto &node : source.Struct())
  466. {
  467. if (!node.second.isNull())
  468. loadStructure(town, node.first, node.second);
  469. }
  470. }
  471. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
  472. {
  473. auto & dstSlots = town.clientInfo.hallSlots;
  474. auto & srcSlots = source.Vector();
  475. dstSlots.resize(srcSlots.size());
  476. for(size_t i=0; i<dstSlots.size(); i++)
  477. {
  478. auto & dstRow = dstSlots[i];
  479. auto & srcRow = srcSlots[i].Vector();
  480. dstRow.resize(srcRow.size());
  481. for(size_t j=0; j < dstRow.size(); j++)
  482. {
  483. auto & dstBox = dstRow[j];
  484. auto & srcBox = srcRow[j].Vector();
  485. dstBox.resize(srcBox.size());
  486. for(size_t k=0; k<dstBox.size(); k++)
  487. {
  488. auto & dst = dstBox[k];
  489. auto & src = srcBox[k];
  490. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier)
  491. {
  492. dst = BuildingID(identifier);
  493. });
  494. }
  495. }
  496. }
  497. }
  498. CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
  499. {
  500. CTown::ClientInfo::Point ret;
  501. ret.x = static_cast<si32>(node["x"].Float());
  502. ret.y = static_cast<si32>(node["y"].Float());
  503. return ret;
  504. }
  505. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source)
  506. {
  507. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  508. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  509. {
  510. town.clientInfo.siegeShooter = CreatureID(creature);
  511. });
  512. auto & pos = town.clientInfo.siegePositions;
  513. pos.resize(21);
  514. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  515. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  516. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  517. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  518. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  519. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  520. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  521. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  522. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  523. pos[9] = JsonToPoint(source["gate"]["gate"]);
  524. pos[10] = JsonToPoint(source["gate"]["arch"]);
  525. pos[7] = JsonToPoint(source["walls"]["upper"]);
  526. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  527. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  528. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  529. pos[13] = JsonToPoint(source["moat"]["moat"]);
  530. pos[14] = JsonToPoint(source["moat"]["bank"]);
  531. pos[11] = JsonToPoint(source["static"]["bottom"]);
  532. pos[12] = JsonToPoint(source["static"]["top"]);
  533. pos[1] = JsonToPoint(source["static"]["background"]);
  534. }
  535. static void readIcon(JsonNode source, std::string & small, std::string & large)
  536. {
  537. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  538. {
  539. small = source["small"].String();
  540. large = source["large"].String();
  541. }
  542. }
  543. void CTownHandler::loadClientData(CTown &town, const JsonNode & source)
  544. {
  545. CTown::ClientInfo & info = town.clientInfo;
  546. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  547. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  548. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  549. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  550. info.hallBackground = source["hallBackground"].String();
  551. info.musicTheme = source["musicTheme"].String();
  552. info.townBackground = source["townBackground"].String();
  553. info.guildWindow = source["guildWindow"].String();
  554. info.buildingsIcons = source["buildingsIcons"].String();
  555. //left for back compatibility - will be removed later
  556. if (source["guildBackground"].String() != "")
  557. info.guildBackground = source["guildBackground"].String();
  558. else
  559. info.guildBackground = "TPMAGE.bmp";
  560. if (source["tavernVideo"].String() != "")
  561. info.tavernVideo = source["tavernVideo"].String();
  562. else
  563. info.tavernVideo = "TAVERN.BIK";
  564. //end of legacy assignment
  565. loadTownHall(town, source["hallSlots"]);
  566. loadStructures(town, source["structures"]);
  567. loadSiegeScreen(town, source["siege"]);
  568. }
  569. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  570. {
  571. auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  572. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  573. town->primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
  574. else
  575. town->primaryRes = static_cast<ui16>(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  576. warMachinesToLoad[town] = source["warMachine"];
  577. town->moatDamage = static_cast<si32>(source["moatDamage"].Float());
  578. // Compatibility for <= 0.98f mods
  579. if(source["moatHexes"].isNull())
  580. town->moatHexes = CTown::defaultMoatHexes();
  581. else
  582. town->moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
  583. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  584. town->names = source["names"].convertTo<std::vector<std::string> >();
  585. // Horde building creature level
  586. for(const JsonNode &node : source["horde"].Vector())
  587. town->hordeLvl[(int)town->hordeLvl.size()] = static_cast<int>(node.Float());
  588. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  589. // but anything below 2 must be handled here
  590. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  591. town->hordeLvl[(int)i] = -1;
  592. const JsonVector & creatures = source["creatures"].Vector();
  593. town->creatures.resize(creatures.size());
  594. for (size_t i=0; i< creatures.size(); i++)
  595. {
  596. const JsonVector & level = creatures[i].Vector();
  597. town->creatures[i].resize(level.size());
  598. for (size_t j=0; j<level.size(); j++)
  599. {
  600. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=](si32 creature)
  601. {
  602. town->creatures[i][j] = CreatureID(creature);
  603. });
  604. }
  605. }
  606. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  607. /// set chance of specific hero class to appear in this town
  608. for(auto &node : source["tavern"].Struct())
  609. {
  610. int chance = static_cast<int>(node.second.Float());
  611. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
  612. {
  613. VLC->heroh->classes.heroClasses[classID]->selectionProbability[town->faction->index] = chance;
  614. });
  615. }
  616. for(auto &node : source["guildSpells"].Struct())
  617. {
  618. int chance = static_cast<int>(node.second.Float());
  619. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
  620. {
  621. VLC->spellh->objects.at(spellID)->probabilities[town->faction->index] = chance;
  622. });
  623. }
  624. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  625. {
  626. town->dwellings.push_back(d["graphics"].String());
  627. town->dwellingNames.push_back(d["name"].String());
  628. }
  629. loadBuildings(town, source["buildings"]);
  630. loadClientData(*town, source);
  631. }
  632. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
  633. {
  634. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  635. std::string prefix = source["prefix"].String();
  636. for(const JsonNode &piece : source["pieces"].Vector())
  637. {
  638. size_t index = faction.puzzleMap.size();
  639. SPuzzleInfo spi;
  640. spi.x = static_cast<si16>(piece["x"].Float());
  641. spi.y = static_cast<si16>(piece["y"].Float());
  642. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  643. spi.number = static_cast<ui16>(index);
  644. // filename calculation
  645. std::ostringstream suffix;
  646. suffix << std::setfill('0') << std::setw(2) << index;
  647. spi.filename = prefix + suffix.str();
  648. faction.puzzleMap.push_back(spi);
  649. }
  650. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  651. }
  652. ETerrainType::EETerrainType CTownHandler::getDefaultTerrainForAlignment(EAlignment::EAlignment alignment) const
  653. {
  654. ETerrainType::EETerrainType terrain = defaultGoodTerrain;
  655. switch(alignment)
  656. {
  657. case EAlignment::EAlignment::EVIL:
  658. terrain = defaultEvilTerrain;
  659. break;
  660. case EAlignment::EAlignment::NEUTRAL:
  661. terrain = defaultNeutralTerrain;
  662. break;
  663. }
  664. return terrain;
  665. }
  666. CFaction * CTownHandler::loadFromJson(const JsonNode &source, const std::string & identifier)
  667. {
  668. auto faction = new CFaction();
  669. faction->name = source["name"].String();
  670. faction->identifier = identifier;
  671. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  672. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  673. int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String());
  674. if (alignment == -1)
  675. faction->alignment = EAlignment::NEUTRAL;
  676. else
  677. faction->alignment = static_cast<EAlignment::EAlignment>(alignment);
  678. auto nativeTerrain = source["nativeTerrain"];
  679. int terrainNum = nativeTerrain.isNull()
  680. ? -1
  681. : vstd::find_pos(GameConstants::TERRAIN_NAMES, nativeTerrain.String());
  682. //Contructor is not called here, but operator=
  683. faction->nativeTerrain = terrainNum < 0
  684. ? getDefaultTerrainForAlignment(faction->alignment)
  685. : static_cast<ETerrainType::EETerrainType>(terrainNum);
  686. if (!source["town"].isNull())
  687. {
  688. faction->town = new CTown();
  689. faction->town->faction = faction;
  690. loadTown(faction->town, source["town"]);
  691. }
  692. else
  693. faction->town = nullptr;
  694. if (!source["puzzleMap"].isNull())
  695. loadPuzzle(*faction, source["puzzleMap"]);
  696. return faction;
  697. }
  698. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  699. {
  700. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  701. object->index = static_cast<TFaction>(factions.size());
  702. factions.push_back(object);
  703. if (object->town)
  704. {
  705. auto & info = object->town->clientInfo;
  706. info.icons[0][0] = 8 + object->index * 4 + 0;
  707. info.icons[0][1] = 8 + object->index * 4 + 1;
  708. info.icons[1][0] = 8 + object->index * 4 + 2;
  709. info.icons[1][1] = 8 + object->index * 4 + 3;
  710. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  711. {
  712. // register town once objects are loaded
  713. JsonNode config = data["town"]["mapObject"];
  714. config["faction"].String() = name;
  715. config["faction"].meta = scope;
  716. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  717. config.meta = scope;
  718. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  719. // MODS COMPATIBILITY FOR 0.96
  720. auto & advMap = data["town"]["adventureMap"];
  721. if (!advMap.isNull())
  722. {
  723. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  724. JsonNode config;
  725. config["animation"] = advMap["castle"];
  726. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  727. }
  728. });
  729. }
  730. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  731. }
  732. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  733. {
  734. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  735. object->index = static_cast<TFaction>(index);
  736. if (factions.size() > index)
  737. assert(factions[index] == nullptr); // ensure that this id was not loaded before
  738. else
  739. factions.resize(index + 1);
  740. factions[index] = object;
  741. if (object->town)
  742. {
  743. auto & info = object->town->clientInfo;
  744. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  745. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  746. info.icons[1][0] = object->index * 2 + 0;
  747. info.icons[1][1] = object->index * 2 + 1;
  748. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  749. {
  750. // register town once objects are loaded
  751. JsonNode config = data["town"]["mapObject"];
  752. config["faction"].String() = name;
  753. config["faction"].meta = scope;
  754. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  755. });
  756. }
  757. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  758. }
  759. void CTownHandler::loadRandomFaction()
  760. {
  761. static const ResourceID randomFactionPath("config/factions/random.json");
  762. JsonNode randomFactionJson(randomFactionPath);
  763. randomFactionJson.setMeta("core", true);
  764. loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]);
  765. }
  766. void CTownHandler::loadCustom()
  767. {
  768. loadRandomFaction();
  769. }
  770. void CTownHandler::afterLoadFinalization()
  771. {
  772. initializeRequirements();
  773. initializeWarMachines();
  774. }
  775. void CTownHandler::initializeRequirements()
  776. {
  777. // must be done separately after all ID's are known
  778. for (auto & requirement : requirementsToLoad)
  779. {
  780. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  781. {
  782. if (node.Vector().size() > 1)
  783. {
  784. logMod->warn("Unexpected length of town buildings requirements: %d", node.Vector().size());
  785. logMod->warn("Entry contains: ");
  786. logMod->warn(node.toJson());
  787. }
  788. return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get());
  789. });
  790. }
  791. requirementsToLoad.clear();
  792. }
  793. void CTownHandler::initializeWarMachines()
  794. {
  795. // must be done separately after all objects are loaded
  796. for(auto & p : warMachinesToLoad)
  797. {
  798. CTown * t = p.first;
  799. JsonNode creatureKey = p.second;
  800. auto ret = VLC->modh->identifiers.getIdentifier("creature", creatureKey, false);
  801. if(ret)
  802. {
  803. const CCreature * creature = CreatureID(*ret).toCreature();
  804. t->warMachine = creature->warMachine;
  805. }
  806. }
  807. warMachinesToLoad.clear();
  808. }
  809. std::vector<bool> CTownHandler::getDefaultAllowed() const
  810. {
  811. std::vector<bool> allowedFactions;
  812. for(auto town : factions)
  813. {
  814. allowedFactions.push_back(town->town != nullptr);
  815. }
  816. return allowedFactions;
  817. }
  818. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown) const
  819. {
  820. std::set<TFaction> allowedFactions;
  821. std::vector<bool> allowed;
  822. if (withTown)
  823. allowed = getDefaultAllowed();
  824. else
  825. allowed.resize( factions.size(), true);
  826. for (size_t i=0; i<allowed.size(); i++)
  827. if (allowed[i])
  828. allowedFactions.insert((TFaction)i);
  829. return allowedFactions;
  830. }
  831. si32 CTownHandler::decodeFaction(const std::string & identifier)
  832. {
  833. auto rawId = VLC->modh->identifiers.getIdentifier("core", "faction", identifier);
  834. if(rawId)
  835. return rawId.get();
  836. else
  837. return -1;
  838. }
  839. std::string CTownHandler::encodeFaction(const si32 index)
  840. {
  841. return VLC->townh->factions[index]->identifier;
  842. }