CTownHandler.cpp 29 KB

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