2
0

CTownHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. #include "StdInc.h"
  2. #include "CTownHandler.h"
  3. #include "VCMI_Lib.h"
  4. #include "CGeneralTextHandler.h"
  5. #include "JsonNode.h"
  6. #include "StringConstants.h"
  7. #include "CCreatureHandler.h"
  8. #include "CModHandler.h"
  9. #include "CHeroHandler.h"
  10. #include "CArtHandler.h"
  11. #include "spells/CSpellHandler.h"
  12. #include "filesystem/Filesystem.h"
  13. #include "mapObjects/CObjectClassesHandler.h"
  14. #include "mapObjects/CObjectHandler.h"
  15. /*
  16. * CTownHandler.cpp, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  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. CFaction::CFaction()
  60. {
  61. town = nullptr;
  62. index = 0;
  63. alignment = EAlignment::NEUTRAL;
  64. }
  65. CFaction::~CFaction()
  66. {
  67. delete town;
  68. }
  69. CTown::CTown()
  70. : faction(nullptr), mageLevel(0), primaryRes(0), moatDamage(0), defaultTavernChance(0)
  71. {
  72. }
  73. CTown::~CTown()
  74. {
  75. for(auto & build : buildings)
  76. build.second.dellNull();
  77. for(auto & str : clientInfo.structures)
  78. str.dellNull();
  79. }
  80. std::vector<BattleHex> CTown::defaultMoatHexes()
  81. {
  82. static const std::vector<BattleHex> moatHexes = {11, 28, 44, 61, 77, 111, 129, 146, 164, 181};
  83. return moatHexes;
  84. }
  85. CTownHandler::CTownHandler()
  86. {
  87. VLC->townh = this;
  88. }
  89. CTownHandler::~CTownHandler()
  90. {
  91. for(auto faction : factions)
  92. faction.dellNull();
  93. }
  94. JsonNode readBuilding(CLegacyConfigParser & parser)
  95. {
  96. JsonNode ret;
  97. JsonNode & cost = ret["cost"];
  98. //note: this code will try to parse mithril as well but wil always return 0 for it
  99. for(const std::string & resID : GameConstants::RESOURCE_NAMES)
  100. cost[resID].Float() = parser.readNumber();
  101. cost.Struct().erase("mithril"); // erase mithril to avoid confusing validator
  102. parser.endLine();
  103. return ret;
  104. }
  105. std::vector<JsonNode> CTownHandler::loadLegacyData(size_t dataSize)
  106. {
  107. std::vector<JsonNode> dest(dataSize);
  108. factions.resize(dataSize);
  109. auto getBuild = [&](size_t town, size_t building) -> JsonNode &
  110. {
  111. return dest[town]["town"]["buildings"][EBuildingType::names[building]];
  112. };
  113. CLegacyConfigParser parser("DATA/BUILDING.TXT");
  114. parser.endLine(); // header
  115. parser.endLine();
  116. //Unique buildings
  117. for (size_t town=0; town<dataSize; town++)
  118. {
  119. parser.endLine(); //header
  120. parser.endLine();
  121. int buildID = 17;
  122. do
  123. {
  124. getBuild(town, buildID) = readBuilding(parser);
  125. buildID++;
  126. }
  127. while (!parser.isNextEntryEmpty());
  128. }
  129. // Common buildings
  130. parser.endLine(); // header
  131. parser.endLine();
  132. parser.endLine();
  133. int buildID = 0;
  134. do
  135. {
  136. JsonNode building = readBuilding(parser);
  137. for (size_t town=0; town<dataSize; town++)
  138. getBuild(town, buildID) = building;
  139. buildID++;
  140. }
  141. while (!parser.isNextEntryEmpty());
  142. parser.endLine(); //header
  143. parser.endLine();
  144. //Dwellings
  145. for (size_t town=0; town<dataSize; town++)
  146. {
  147. parser.endLine(); //header
  148. parser.endLine();
  149. for (size_t i=0; i<14; i++)
  150. {
  151. getBuild(town, 30+i) = readBuilding(parser);
  152. }
  153. }
  154. {
  155. CLegacyConfigParser parser("DATA/BLDGNEUT.TXT");
  156. for(int building=0; building<15; building++)
  157. {
  158. std::string name = parser.readString();
  159. std::string descr = parser.readString();
  160. parser.endLine();
  161. for(int j=0; j<dataSize; j++)
  162. {
  163. getBuild(j, building)["name"].String() = name;
  164. getBuild(j, building)["description"].String() = descr;
  165. }
  166. }
  167. parser.endLine(); // silo
  168. parser.endLine(); // blacksmith //unused entries
  169. parser.endLine(); // moat
  170. //shipyard with the ship
  171. std::string name = parser.readString();
  172. std::string descr = parser.readString();
  173. parser.endLine();
  174. for(int town=0; town<dataSize; town++)
  175. {
  176. getBuild(town, 20)["name"].String() = name;
  177. getBuild(town, 20)["description"].String() = descr;
  178. }
  179. //blacksmith
  180. for(int town=0; town<dataSize; town++)
  181. {
  182. getBuild(town, 16)["name"].String() = parser.readString();
  183. getBuild(town, 16)["description"].String() = parser.readString();
  184. parser.endLine();
  185. }
  186. }
  187. {
  188. CLegacyConfigParser parser("DATA/BLDGSPEC.TXT");
  189. for(int town=0; town<dataSize; town++)
  190. {
  191. for(int build=0; build<9; build++)
  192. {
  193. getBuild(town, 17 + build)["name"].String() = parser.readString();
  194. getBuild(town, 17 + build)["description"].String() = parser.readString();
  195. parser.endLine();
  196. }
  197. getBuild(town, 26)["name"].String() = parser.readString(); // Grail
  198. getBuild(town, 26)["description"].String() = parser.readString();
  199. parser.endLine();
  200. getBuild(town, 15)["name"].String() = parser.readString(); // Resource silo
  201. getBuild(town, 15)["description"].String() = parser.readString();
  202. parser.endLine();
  203. }
  204. }
  205. {
  206. CLegacyConfigParser parser("DATA/DWELLING.TXT");
  207. for(int town=0; town<dataSize; town++)
  208. {
  209. for(int build=0; build<14; build++)
  210. {
  211. getBuild(town, 30 + build)["name"].String() = parser.readString();
  212. getBuild(town, 30 + build)["description"].String() = parser.readString();
  213. parser.endLine();
  214. }
  215. }
  216. }
  217. {
  218. CLegacyConfigParser typeParser("DATA/TOWNTYPE.TXT");
  219. CLegacyConfigParser nameParser("DATA/TOWNNAME.TXT");
  220. size_t townID=0;
  221. do
  222. {
  223. dest[townID]["name"].String() = typeParser.readString();
  224. for (int i=0; i<NAMES_PER_TOWN; i++)
  225. {
  226. JsonNode name;
  227. name.String() = nameParser.readString();
  228. dest[townID]["town"]["names"].Vector().push_back(name);
  229. nameParser.endLine();
  230. }
  231. townID++;
  232. }
  233. while (typeParser.endLine());
  234. }
  235. return dest;
  236. }
  237. void CTownHandler::loadBuildingRequirements(CTown &town, CBuilding & building, const JsonNode & source)
  238. {
  239. if (source.isNull())
  240. return;
  241. BuildingRequirementsHelper hlp;
  242. hlp.building = &building;
  243. hlp.faction = town.faction;
  244. hlp.json = source;
  245. requirementsToLoad.push_back(hlp);
  246. }
  247. void CTownHandler::loadBuilding(CTown &town, const std::string & stringID, const JsonNode & source)
  248. {
  249. auto ret = new CBuilding;
  250. static const std::string modes [] = {"normal", "auto", "special", "grail"};
  251. ret->mode = static_cast<CBuilding::EBuildMode>(boost::find(modes, source["mode"].String()) - modes);
  252. ret->identifier = stringID;
  253. ret->town = &town;
  254. ret->bid = BuildingID(source["id"].Float());
  255. ret->name = source["name"].String();
  256. ret->description = source["description"].String();
  257. ret->resources = TResources(source["cost"]);
  258. ret->produce = TResources(source["produce"]);
  259. //MODS COMPATIBILITY FOR 0.96
  260. if(!ret->produce.nonZero())
  261. {
  262. switch (ret->bid) {
  263. break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500;
  264. break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000;
  265. break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000;
  266. break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000;
  267. break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000;
  268. break; case BuildingID::RESOURCE_SILO :
  269. {
  270. switch (ret->town->primaryRes)
  271. {
  272. case Res::GOLD:
  273. ret->produce[ret->town->primaryRes] = 500;
  274. break;
  275. case Res::WOOD_AND_ORE:
  276. ret->produce[Res::WOOD] = 1;
  277. ret->produce[Res::ORE] = 1;
  278. break;
  279. default:
  280. ret->produce[ret->town->primaryRes] = 1;
  281. break;
  282. }
  283. }
  284. }
  285. }
  286. loadBuildingRequirements(town, *ret, source["requires"]);
  287. if (!source["upgrades"].isNull())
  288. {
  289. // building id and upgrades can't be the same
  290. if(stringID == source["upgrades"].String())
  291. {
  292. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  293. stringID % town.faction->name));
  294. }
  295. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["upgrades"], [=](si32 identifier)
  296. {
  297. ret->upgrade = BuildingID(identifier);
  298. });
  299. }
  300. else
  301. ret->upgrade = BuildingID::NONE;
  302. town.buildings[ret->bid] = ret;
  303. VLC->modh->identifiers.registerObject(source.meta, "building." + town.faction->identifier, ret->identifier, ret->bid);
  304. }
  305. void CTownHandler::loadBuildings(CTown &town, const JsonNode & source)
  306. {
  307. for(auto &node : source.Struct())
  308. {
  309. if (!node.second.isNull())
  310. {
  311. loadBuilding(town, node.first, node.second);
  312. }
  313. }
  314. }
  315. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source)
  316. {
  317. auto ret = new CStructure;
  318. ret->building = nullptr;
  319. ret->buildable = nullptr;
  320. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  321. {
  322. ret->building = town.buildings[BuildingID(identifier)];
  323. });
  324. if (source["builds"].isNull())
  325. {
  326. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  327. {
  328. ret->building = town.buildings[BuildingID(identifier)];
  329. });
  330. }
  331. else
  332. {
  333. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable
  334. {
  335. ret->buildable = town.buildings[BuildingID(identifier)];
  336. });
  337. }
  338. ret->identifier = stringID;
  339. ret->pos.x = source["x"].Float();
  340. ret->pos.y = source["y"].Float();
  341. ret->pos.z = source["z"].Float();
  342. ret->hiddenUpgrade = source["hidden"].Bool();
  343. ret->defName = source["animation"].String();
  344. ret->borderName = source["border"].String();
  345. ret->areaName = source["area"].String();
  346. town.clientInfo.structures.push_back(ret);
  347. }
  348. void CTownHandler::loadStructures(CTown &town, const JsonNode & source)
  349. {
  350. for(auto &node : source.Struct())
  351. {
  352. if (!node.second.isNull())
  353. loadStructure(town, node.first, node.second);
  354. }
  355. }
  356. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
  357. {
  358. auto & dstSlots = town.clientInfo.hallSlots;
  359. auto & srcSlots = source.Vector();
  360. dstSlots.resize(srcSlots.size());
  361. for(size_t i=0; i<dstSlots.size(); i++)
  362. {
  363. auto & dstRow = dstSlots[i];
  364. auto & srcRow = srcSlots[i].Vector();
  365. dstRow.resize(srcRow.size());
  366. for(size_t j=0; j < dstRow.size(); j++)
  367. {
  368. auto & dstBox = dstRow[j];
  369. auto & srcBox = srcRow[j].Vector();
  370. dstBox.resize(srcBox.size());
  371. for(size_t k=0; k<dstBox.size(); k++)
  372. {
  373. auto & dst = dstBox[k];
  374. auto & src = srcBox[k];
  375. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier)
  376. {
  377. dst = BuildingID(identifier);
  378. });
  379. }
  380. }
  381. }
  382. }
  383. CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
  384. {
  385. CTown::ClientInfo::Point ret;
  386. ret.x = node["x"].Float();
  387. ret.y = node["y"].Float();
  388. return ret;
  389. }
  390. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source)
  391. {
  392. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  393. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  394. {
  395. town.clientInfo.siegeShooter = CreatureID(creature);
  396. });
  397. auto & pos = town.clientInfo.siegePositions;
  398. pos.resize(21);
  399. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  400. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  401. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  402. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  403. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  404. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  405. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  406. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  407. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  408. pos[9] = JsonToPoint(source["gate"]["gate"]);
  409. pos[10] = JsonToPoint(source["gate"]["arch"]);
  410. pos[7] = JsonToPoint(source["walls"]["upper"]);
  411. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  412. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  413. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  414. pos[13] = JsonToPoint(source["moat"]["moat"]);
  415. pos[14] = JsonToPoint(source["moat"]["bank"]);
  416. pos[11] = JsonToPoint(source["static"]["bottom"]);
  417. pos[12] = JsonToPoint(source["static"]["top"]);
  418. pos[1] = JsonToPoint(source["static"]["background"]);
  419. }
  420. static void readIcon(JsonNode source, std::string & small, std::string & large)
  421. {
  422. if (source.getType() == JsonNode::DATA_STRUCT) // don't crash on old format
  423. {
  424. small = source["small"].String();
  425. large = source["large"].String();
  426. }
  427. }
  428. void CTownHandler::loadClientData(CTown &town, const JsonNode & source)
  429. {
  430. CTown::ClientInfo & info = town.clientInfo;
  431. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  432. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  433. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  434. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  435. info.hallBackground = source["hallBackground"].String();
  436. info.musicTheme = source["musicTheme"].String();
  437. info.townBackground = source["townBackground"].String();
  438. info.guildWindow = source["guildWindow"].String();
  439. info.buildingsIcons = source["buildingsIcons"].String();
  440. //left for back compatibility - will be removed later
  441. if (source["guildBackground"].String() != "")
  442. info.guildBackground = source["guildBackground"].String();
  443. else
  444. info.guildBackground = "TPMAGE.bmp";
  445. if (source["tavernVideo"].String() != "")
  446. info.tavernVideo = source["tavernVideo"].String();
  447. else
  448. info.tavernVideo = "TAVERN.BIK";
  449. //end of legacy assignment
  450. loadTownHall(town, source["hallSlots"]);
  451. loadStructures(town, source["structures"]);
  452. loadSiegeScreen(town, source["siege"]);
  453. }
  454. void CTownHandler::loadTown(CTown &town, const JsonNode & source)
  455. {
  456. auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  457. if (resIter == std::end(GameConstants::RESOURCE_NAMES))
  458. town.primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
  459. else
  460. town.primaryRes = resIter - std::begin(GameConstants::RESOURCE_NAMES);
  461. VLC->modh->identifiers.requestIdentifier("creature", source["warMachine"],
  462. [&town](si32 creature)
  463. {
  464. town.warMachine = CArtHandler::creatureToMachineID(CreatureID(creature));
  465. });
  466. town.moatDamage = source["moatDamage"].Float();
  467. // Compatability for <= 0.98f mods
  468. if(source["moatHexes"].isNull())
  469. {
  470. town.moatHexes = CTown::defaultMoatHexes();
  471. }
  472. else
  473. town.moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
  474. town.mageLevel = source["mageGuild"].Float();
  475. town.names = source["names"].convertTo<std::vector<std::string> >();
  476. // Horde building creature level
  477. for(const JsonNode &node : source["horde"].Vector())
  478. town.hordeLvl[town.hordeLvl.size()] = node.Float();
  479. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  480. // but anything below 2 must be handled here
  481. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  482. town.hordeLvl[i] = -1;
  483. const JsonVector & creatures = source["creatures"].Vector();
  484. town.creatures.resize(creatures.size());
  485. for (size_t i=0; i< creatures.size(); i++)
  486. {
  487. const JsonVector & level = creatures[i].Vector();
  488. town.creatures[i].resize(level.size());
  489. for (size_t j=0; j<level.size(); j++)
  490. {
  491. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=, &town](si32 creature)
  492. {
  493. town.creatures[i][j] = CreatureID(creature);
  494. });
  495. }
  496. }
  497. town.defaultTavernChance = source["defaultTavern"].Float();
  498. /// set chance of specific hero class to appear in this town
  499. for(auto &node : source["tavern"].Struct())
  500. {
  501. int chance = node.second.Float();
  502. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=, &town](si32 classID)
  503. {
  504. VLC->heroh->classes.heroClasses[classID]->selectionProbability[town.faction->index] = chance;
  505. });
  506. }
  507. for(auto &node : source["guildSpells"].Struct())
  508. {
  509. int chance = node.second.Float();
  510. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=, &town](si32 spellID)
  511. {
  512. VLC->spellh->objects.at(spellID)->probabilities[town.faction->index] = chance;
  513. });
  514. }
  515. for (const JsonNode &d : source["adventureMap"]["dwellings"].Vector())
  516. {
  517. town.dwellings.push_back (d["graphics"].String());
  518. town.dwellingNames.push_back (d["name"].String());
  519. }
  520. loadBuildings(town, source["buildings"]);
  521. loadClientData(town,source);
  522. }
  523. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
  524. {
  525. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  526. std::string prefix = source["prefix"].String();
  527. for(const JsonNode &piece : source["pieces"].Vector())
  528. {
  529. size_t index = faction.puzzleMap.size();
  530. SPuzzleInfo spi;
  531. spi.x = piece["x"].Float();
  532. spi.y = piece["y"].Float();
  533. spi.whenUncovered = piece["index"].Float();
  534. spi.number = index;
  535. // filename calculation
  536. std::ostringstream suffix;
  537. suffix << std::setfill('0') << std::setw(2) << index;
  538. spi.filename = prefix + suffix.str();
  539. faction.puzzleMap.push_back(spi);
  540. }
  541. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  542. }
  543. CFaction * CTownHandler::loadFromJson(const JsonNode &source, const std::string & identifier)
  544. {
  545. auto faction = new CFaction();
  546. faction->name = source["name"].String();
  547. faction->identifier = identifier;
  548. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  549. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  550. faction->nativeTerrain = ETerrainType(vstd::find_pos(GameConstants::TERRAIN_NAMES,
  551. source["nativeTerrain"].String()));
  552. int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String());
  553. if (alignment == -1)
  554. faction->alignment = EAlignment::NEUTRAL;
  555. else
  556. faction->alignment = static_cast<EAlignment::EAlignment>(alignment);
  557. if (!source["town"].isNull())
  558. {
  559. faction->town = new CTown;
  560. faction->town->faction = faction;
  561. loadTown(*faction->town, source["town"]);
  562. }
  563. else
  564. faction->town = nullptr;
  565. if (!source["puzzleMap"].isNull())
  566. loadPuzzle(*faction, source["puzzleMap"]);
  567. return faction;
  568. }
  569. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  570. {
  571. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  572. object->index = factions.size();
  573. factions.push_back(object);
  574. if (object->town)
  575. {
  576. auto & info = object->town->clientInfo;
  577. info.icons[0][0] = 8 + object->index * 4 + 0;
  578. info.icons[0][1] = 8 + object->index * 4 + 1;
  579. info.icons[1][0] = 8 + object->index * 4 + 2;
  580. info.icons[1][1] = 8 + object->index * 4 + 3;
  581. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  582. {
  583. // register town once objects are loaded
  584. JsonNode config = data["town"]["mapObject"];
  585. config["faction"].String() = name;
  586. config["faction"].meta = scope;
  587. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  588. config.meta = scope;
  589. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  590. // MODS COMPATIBILITY FOR 0.96
  591. auto & advMap = data["town"]["adventureMap"];
  592. if (!advMap.isNull())
  593. {
  594. logGlobal->warnStream() << "Outdated town mod. Will try to generate valid templates out of fort";
  595. JsonNode config;
  596. config["animation"] = advMap["castle"];
  597. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  598. }
  599. });
  600. }
  601. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  602. }
  603. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  604. {
  605. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  606. object->index = index;
  607. assert(factions[index] == nullptr); // ensure that this id was not loaded before
  608. factions[index] = object;
  609. if (object->town)
  610. {
  611. auto & info = object->town->clientInfo;
  612. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  613. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  614. info.icons[1][0] = object->index * 2 + 0;
  615. info.icons[1][1] = object->index * 2 + 1;
  616. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  617. {
  618. // register town once objects are loaded
  619. JsonNode config = data["town"]["mapObject"];
  620. config["faction"].String() = name;
  621. config["faction"].meta = scope;
  622. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  623. });
  624. }
  625. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  626. }
  627. void CTownHandler::afterLoadFinalization()
  628. {
  629. initializeRequirements();
  630. }
  631. void CTownHandler::initializeRequirements()
  632. {
  633. // must be done separately after all ID's are known
  634. for (auto & requirement : requirementsToLoad)
  635. {
  636. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  637. {
  638. if (node.Vector().size() > 1)
  639. {
  640. logGlobal->warnStream() << "Unexpected length of town buildings requirements: " << node.Vector().size();
  641. logGlobal->warnStream() << "Entry contains " << node;
  642. }
  643. return BuildingID(VLC->modh->identifiers.getIdentifier("building." + requirement.faction->identifier, node.Vector()[0]).get());
  644. });
  645. }
  646. requirementsToLoad.clear();
  647. }
  648. std::vector<bool> CTownHandler::getDefaultAllowed() const
  649. {
  650. std::vector<bool> allowedFactions;
  651. for(auto town : factions)
  652. {
  653. allowedFactions.push_back(town->town != nullptr);
  654. }
  655. return allowedFactions;
  656. }
  657. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown /*=true*/) const
  658. {
  659. std::set<TFaction> allowedFactions;
  660. std::vector<bool> allowed;
  661. if (withTown)
  662. allowed = getDefaultAllowed();
  663. else
  664. allowed.resize( factions.size(), true);
  665. for (size_t i=0; i<allowed.size(); i++)
  666. if (allowed[i])
  667. allowedFactions.insert(i);
  668. return allowedFactions;
  669. }
  670. si32 CTownHandler::decodeFaction(const std::string & identifier)
  671. {
  672. auto rawId = VLC->modh->identifiers.getIdentifier("core", "faction", identifier);
  673. if(rawId)
  674. return rawId.get();
  675. else
  676. return -1;
  677. }
  678. std::string CTownHandler::encodeFaction(const si32 index)
  679. {
  680. return VLC->townh->factions[index]->identifier;
  681. }