CTownHandler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, const JsonNode & source)
  289. {
  290. auto ret = new CBuilding();
  291. static const std::vector<std::string> MODES =
  292. {
  293. "normal", "auto", "special", "grail"
  294. };
  295. ret->mode = CBuilding::BUILD_NORMAL;
  296. {
  297. if(source["mode"].getType() == JsonNode::JsonType::DATA_STRING)
  298. {
  299. auto rawMode = vstd::find_pos(MODES, source["mode"].String());
  300. if(rawMode > 0)
  301. ret->mode = static_cast<CBuilding::EBuildMode>(rawMode);
  302. }
  303. }
  304. ret->identifier = stringID;
  305. ret->town = town;
  306. ret->bid = BuildingID((si32)source["id"].Float());
  307. ret->name = source["name"].String();
  308. ret->description = source["description"].String();
  309. ret->resources = TResources(source["cost"]);
  310. ret->produce = TResources(source["produce"]);
  311. //MODS COMPATIBILITY FOR 0.96
  312. if(!ret->produce.nonZero())
  313. {
  314. switch (ret->bid) {
  315. break; case BuildingID::VILLAGE_HALL: ret->produce[Res::GOLD] = 500;
  316. break; case BuildingID::TOWN_HALL : ret->produce[Res::GOLD] = 1000;
  317. break; case BuildingID::CITY_HALL : ret->produce[Res::GOLD] = 2000;
  318. break; case BuildingID::CAPITOL : ret->produce[Res::GOLD] = 4000;
  319. break; case BuildingID::GRAIL : ret->produce[Res::GOLD] = 5000;
  320. break; case BuildingID::RESOURCE_SILO :
  321. {
  322. switch (ret->town->primaryRes)
  323. {
  324. case Res::GOLD:
  325. ret->produce[ret->town->primaryRes] = 500;
  326. break;
  327. case Res::WOOD_AND_ORE:
  328. ret->produce[Res::WOOD] = 1;
  329. ret->produce[Res::ORE] = 1;
  330. break;
  331. default:
  332. ret->produce[ret->town->primaryRes] = 1;
  333. break;
  334. }
  335. }
  336. }
  337. }
  338. loadBuildingRequirements(ret, source["requires"]);
  339. if (!source["upgrades"].isNull())
  340. {
  341. // building id and upgrades can't be the same
  342. if(stringID == source["upgrades"].String())
  343. {
  344. throw std::runtime_error(boost::str(boost::format("Building with ID '%s' of town '%s' can't be an upgrade of the same building.") %
  345. stringID % ret->town->getFactionName()));
  346. }
  347. VLC->modh->identifiers.requestIdentifier(ret->town->getBuildingScope(), source["upgrades"], [=](si32 identifier)
  348. {
  349. ret->upgrade = BuildingID(identifier);
  350. });
  351. }
  352. else
  353. ret->upgrade = BuildingID::NONE;
  354. ret->town->buildings[ret->bid] = ret;
  355. VLC->modh->identifiers.registerObject(source.meta, ret->town->getBuildingScope(), ret->identifier, ret->bid);
  356. }
  357. void CTownHandler::loadBuildings(CTown * town, const JsonNode & source)
  358. {
  359. for(auto & node : source.Struct())
  360. {
  361. if (!node.second.isNull())
  362. {
  363. loadBuilding(town, node.first, node.second);
  364. }
  365. }
  366. }
  367. void CTownHandler::loadStructure(CTown &town, const std::string & stringID, const JsonNode & source)
  368. {
  369. auto ret = new CStructure();
  370. ret->building = nullptr;
  371. ret->buildable = nullptr;
  372. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  373. {
  374. ret->building = town.buildings[BuildingID(identifier)];
  375. });
  376. if (source["builds"].isNull())
  377. {
  378. VLC->modh->identifiers.tryRequestIdentifier( source.meta, "building." + town.faction->identifier, stringID, [=, &town](si32 identifier) mutable
  379. {
  380. ret->building = town.buildings[BuildingID(identifier)];
  381. });
  382. }
  383. else
  384. {
  385. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, source["builds"], [=, &town](si32 identifier) mutable
  386. {
  387. ret->buildable = town.buildings[BuildingID(identifier)];
  388. });
  389. }
  390. ret->identifier = stringID;
  391. ret->pos.x = static_cast<si32>(source["x"].Float());
  392. ret->pos.y = static_cast<si32>(source["y"].Float());
  393. ret->pos.z = static_cast<si32>(source["z"].Float());
  394. ret->hiddenUpgrade = source["hidden"].Bool();
  395. ret->defName = source["animation"].String();
  396. ret->borderName = source["border"].String();
  397. ret->areaName = source["area"].String();
  398. town.clientInfo.structures.push_back(ret);
  399. }
  400. void CTownHandler::loadStructures(CTown &town, const JsonNode & source)
  401. {
  402. for(auto &node : source.Struct())
  403. {
  404. if (!node.second.isNull())
  405. loadStructure(town, node.first, node.second);
  406. }
  407. }
  408. void CTownHandler::loadTownHall(CTown &town, const JsonNode & source)
  409. {
  410. auto & dstSlots = town.clientInfo.hallSlots;
  411. auto & srcSlots = source.Vector();
  412. dstSlots.resize(srcSlots.size());
  413. for(size_t i=0; i<dstSlots.size(); i++)
  414. {
  415. auto & dstRow = dstSlots[i];
  416. auto & srcRow = srcSlots[i].Vector();
  417. dstRow.resize(srcRow.size());
  418. for(size_t j=0; j < dstRow.size(); j++)
  419. {
  420. auto & dstBox = dstRow[j];
  421. auto & srcBox = srcRow[j].Vector();
  422. dstBox.resize(srcBox.size());
  423. for(size_t k=0; k<dstBox.size(); k++)
  424. {
  425. auto & dst = dstBox[k];
  426. auto & src = srcBox[k];
  427. VLC->modh->identifiers.requestIdentifier("building." + town.faction->identifier, src, [&](si32 identifier)
  428. {
  429. dst = BuildingID(identifier);
  430. });
  431. }
  432. }
  433. }
  434. }
  435. CTown::ClientInfo::Point JsonToPoint(const JsonNode & node)
  436. {
  437. CTown::ClientInfo::Point ret;
  438. ret.x = static_cast<si32>(node["x"].Float());
  439. ret.y = static_cast<si32>(node["y"].Float());
  440. return ret;
  441. }
  442. void CTownHandler::loadSiegeScreen(CTown &town, const JsonNode & source)
  443. {
  444. town.clientInfo.siegePrefix = source["imagePrefix"].String();
  445. VLC->modh->identifiers.requestIdentifier("creature", source["shooter"], [&town](si32 creature)
  446. {
  447. town.clientInfo.siegeShooter = CreatureID(creature);
  448. });
  449. auto & pos = town.clientInfo.siegePositions;
  450. pos.resize(21);
  451. pos[8] = JsonToPoint(source["towers"]["top"]["tower"]);
  452. pos[17] = JsonToPoint(source["towers"]["top"]["battlement"]);
  453. pos[20] = JsonToPoint(source["towers"]["top"]["creature"]);
  454. pos[2] = JsonToPoint(source["towers"]["keep"]["tower"]);
  455. pos[15] = JsonToPoint(source["towers"]["keep"]["battlement"]);
  456. pos[18] = JsonToPoint(source["towers"]["keep"]["creature"]);
  457. pos[3] = JsonToPoint(source["towers"]["bottom"]["tower"]);
  458. pos[16] = JsonToPoint(source["towers"]["bottom"]["battlement"]);
  459. pos[19] = JsonToPoint(source["towers"]["bottom"]["creature"]);
  460. pos[9] = JsonToPoint(source["gate"]["gate"]);
  461. pos[10] = JsonToPoint(source["gate"]["arch"]);
  462. pos[7] = JsonToPoint(source["walls"]["upper"]);
  463. pos[6] = JsonToPoint(source["walls"]["upperMid"]);
  464. pos[5] = JsonToPoint(source["walls"]["bottomMid"]);
  465. pos[4] = JsonToPoint(source["walls"]["bottom"]);
  466. pos[13] = JsonToPoint(source["moat"]["moat"]);
  467. pos[14] = JsonToPoint(source["moat"]["bank"]);
  468. pos[11] = JsonToPoint(source["static"]["bottom"]);
  469. pos[12] = JsonToPoint(source["static"]["top"]);
  470. pos[1] = JsonToPoint(source["static"]["background"]);
  471. }
  472. static void readIcon(JsonNode source, std::string & small, std::string & large)
  473. {
  474. if (source.getType() == JsonNode::JsonType::DATA_STRUCT) // don't crash on old format
  475. {
  476. small = source["small"].String();
  477. large = source["large"].String();
  478. }
  479. }
  480. void CTownHandler::loadClientData(CTown &town, const JsonNode & source)
  481. {
  482. CTown::ClientInfo & info = town.clientInfo;
  483. readIcon(source["icons"]["village"]["normal"], info.iconSmall[0][0], info.iconLarge[0][0]);
  484. readIcon(source["icons"]["village"]["built"], info.iconSmall[0][1], info.iconLarge[0][1]);
  485. readIcon(source["icons"]["fort"]["normal"], info.iconSmall[1][0], info.iconLarge[1][0]);
  486. readIcon(source["icons"]["fort"]["built"], info.iconSmall[1][1], info.iconLarge[1][1]);
  487. info.hallBackground = source["hallBackground"].String();
  488. info.musicTheme = source["musicTheme"].String();
  489. info.townBackground = source["townBackground"].String();
  490. info.guildWindow = source["guildWindow"].String();
  491. info.buildingsIcons = source["buildingsIcons"].String();
  492. //left for back compatibility - will be removed later
  493. if (source["guildBackground"].String() != "")
  494. info.guildBackground = source["guildBackground"].String();
  495. else
  496. info.guildBackground = "TPMAGE.bmp";
  497. if (source["tavernVideo"].String() != "")
  498. info.tavernVideo = source["tavernVideo"].String();
  499. else
  500. info.tavernVideo = "TAVERN.BIK";
  501. //end of legacy assignment
  502. loadTownHall(town, source["hallSlots"]);
  503. loadStructures(town, source["structures"]);
  504. loadSiegeScreen(town, source["siege"]);
  505. }
  506. void CTownHandler::loadTown(CTown * town, const JsonNode & source)
  507. {
  508. auto resIter = boost::find(GameConstants::RESOURCE_NAMES, source["primaryResource"].String());
  509. if(resIter == std::end(GameConstants::RESOURCE_NAMES))
  510. town->primaryRes = Res::WOOD_AND_ORE; //Wood + Ore
  511. else
  512. town->primaryRes = static_cast<ui16>(resIter - std::begin(GameConstants::RESOURCE_NAMES));
  513. warMachinesToLoad[town] = source["warMachine"];
  514. town->moatDamage = static_cast<si32>(source["moatDamage"].Float());
  515. // Compatibility for <= 0.98f mods
  516. if(source["moatHexes"].isNull())
  517. town->moatHexes = CTown::defaultMoatHexes();
  518. else
  519. town->moatHexes = source["moatHexes"].convertTo<std::vector<BattleHex> >();
  520. town->mageLevel = static_cast<ui32>(source["mageGuild"].Float());
  521. town->names = source["names"].convertTo<std::vector<std::string> >();
  522. // Horde building creature level
  523. for(const JsonNode &node : source["horde"].Vector())
  524. town->hordeLvl[(int)town->hordeLvl.size()] = static_cast<int>(node.Float());
  525. // town needs to have exactly 2 horde entries. Validation will take care of 2+ entries
  526. // but anything below 2 must be handled here
  527. for (size_t i=source["horde"].Vector().size(); i<2; i++)
  528. town->hordeLvl[(int)i] = -1;
  529. const JsonVector & creatures = source["creatures"].Vector();
  530. town->creatures.resize(creatures.size());
  531. for (size_t i=0; i< creatures.size(); i++)
  532. {
  533. const JsonVector & level = creatures[i].Vector();
  534. town->creatures[i].resize(level.size());
  535. for (size_t j=0; j<level.size(); j++)
  536. {
  537. VLC->modh->identifiers.requestIdentifier("creature", level[j], [=](si32 creature)
  538. {
  539. town->creatures[i][j] = CreatureID(creature);
  540. });
  541. }
  542. }
  543. town->defaultTavernChance = static_cast<ui32>(source["defaultTavern"].Float());
  544. /// set chance of specific hero class to appear in this town
  545. for(auto &node : source["tavern"].Struct())
  546. {
  547. int chance = static_cast<int>(node.second.Float());
  548. VLC->modh->identifiers.requestIdentifier(node.second.meta, "heroClass",node.first, [=](si32 classID)
  549. {
  550. VLC->heroh->classes.heroClasses[classID]->selectionProbability[town->faction->index] = chance;
  551. });
  552. }
  553. for(auto &node : source["guildSpells"].Struct())
  554. {
  555. int chance = static_cast<int>(node.second.Float());
  556. VLC->modh->identifiers.requestIdentifier(node.second.meta, "spell", node.first, [=](si32 spellID)
  557. {
  558. VLC->spellh->objects.at(spellID)->probabilities[town->faction->index] = chance;
  559. });
  560. }
  561. for(const JsonNode & d : source["adventureMap"]["dwellings"].Vector())
  562. {
  563. town->dwellings.push_back(d["graphics"].String());
  564. town->dwellingNames.push_back(d["name"].String());
  565. }
  566. loadBuildings(town, source["buildings"]);
  567. loadClientData(*town, source);
  568. }
  569. void CTownHandler::loadPuzzle(CFaction &faction, const JsonNode &source)
  570. {
  571. faction.puzzleMap.reserve(GameConstants::PUZZLE_MAP_PIECES);
  572. std::string prefix = source["prefix"].String();
  573. for(const JsonNode &piece : source["pieces"].Vector())
  574. {
  575. size_t index = faction.puzzleMap.size();
  576. SPuzzleInfo spi;
  577. spi.x = static_cast<si16>(piece["x"].Float());
  578. spi.y = static_cast<si16>(piece["y"].Float());
  579. spi.whenUncovered = static_cast<ui16>(piece["index"].Float());
  580. spi.number = static_cast<ui16>(index);
  581. // filename calculation
  582. std::ostringstream suffix;
  583. suffix << std::setfill('0') << std::setw(2) << index;
  584. spi.filename = prefix + suffix.str();
  585. faction.puzzleMap.push_back(spi);
  586. }
  587. assert(faction.puzzleMap.size() == GameConstants::PUZZLE_MAP_PIECES);
  588. }
  589. ETerrainType::EETerrainType CTownHandler::getDefaultTerrainForAlignment(EAlignment::EAlignment alignment) const
  590. {
  591. ETerrainType::EETerrainType terrain = defaultGoodTerrain;
  592. switch(alignment)
  593. {
  594. case EAlignment::EAlignment::EVIL:
  595. terrain = defaultEvilTerrain;
  596. break;
  597. case EAlignment::EAlignment::NEUTRAL:
  598. terrain = defaultNeutralTerrain;
  599. break;
  600. }
  601. return terrain;
  602. }
  603. CFaction * CTownHandler::loadFromJson(const JsonNode &source, const std::string & identifier)
  604. {
  605. auto faction = new CFaction();
  606. faction->name = source["name"].String();
  607. faction->identifier = identifier;
  608. faction->creatureBg120 = source["creatureBackground"]["120px"].String();
  609. faction->creatureBg130 = source["creatureBackground"]["130px"].String();
  610. int alignment = vstd::find_pos(EAlignment::names, source["alignment"].String());
  611. if (alignment == -1)
  612. faction->alignment = EAlignment::NEUTRAL;
  613. else
  614. faction->alignment = static_cast<EAlignment::EAlignment>(alignment);
  615. auto nativeTerrain = source["nativeTerrain"];
  616. int terrainNum = nativeTerrain.isNull()
  617. ? -1
  618. : vstd::find_pos(GameConstants::TERRAIN_NAMES, nativeTerrain.String());
  619. //Contructor is not called here, but operator=
  620. faction->nativeTerrain = terrainNum < 0
  621. ? getDefaultTerrainForAlignment(faction->alignment)
  622. : static_cast<ETerrainType::EETerrainType>(terrainNum);
  623. if (!source["town"].isNull())
  624. {
  625. faction->town = new CTown();
  626. faction->town->faction = faction;
  627. loadTown(faction->town, source["town"]);
  628. }
  629. else
  630. faction->town = nullptr;
  631. if (!source["puzzleMap"].isNull())
  632. loadPuzzle(*faction, source["puzzleMap"]);
  633. return faction;
  634. }
  635. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  636. {
  637. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  638. object->index = static_cast<TFaction>(factions.size());
  639. factions.push_back(object);
  640. if (object->town)
  641. {
  642. auto & info = object->town->clientInfo;
  643. info.icons[0][0] = 8 + object->index * 4 + 0;
  644. info.icons[0][1] = 8 + object->index * 4 + 1;
  645. info.icons[1][0] = 8 + object->index * 4 + 2;
  646. info.icons[1][1] = 8 + object->index * 4 + 3;
  647. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  648. {
  649. // register town once objects are loaded
  650. JsonNode config = data["town"]["mapObject"];
  651. config["faction"].String() = name;
  652. config["faction"].meta = scope;
  653. if (config.meta.empty())// MODS COMPATIBILITY FOR 0.96
  654. config.meta = scope;
  655. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  656. // MODS COMPATIBILITY FOR 0.96
  657. auto & advMap = data["town"]["adventureMap"];
  658. if (!advMap.isNull())
  659. {
  660. logMod->warn("Outdated town mod. Will try to generate valid templates out of fort");
  661. JsonNode config;
  662. config["animation"] = advMap["castle"];
  663. VLC->objtypeh->getHandlerFor(index, object->index)->addTemplate(config);
  664. }
  665. });
  666. }
  667. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  668. }
  669. void CTownHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  670. {
  671. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  672. object->index = static_cast<TFaction>(index);
  673. if (factions.size() > index)
  674. assert(factions[index] == nullptr); // ensure that this id was not loaded before
  675. else
  676. factions.resize(index + 1);
  677. factions[index] = object;
  678. if (object->town)
  679. {
  680. auto & info = object->town->clientInfo;
  681. info.icons[0][0] = (GameConstants::F_NUMBER + object->index) * 2 + 0;
  682. info.icons[0][1] = (GameConstants::F_NUMBER + object->index) * 2 + 1;
  683. info.icons[1][0] = object->index * 2 + 0;
  684. info.icons[1][1] = object->index * 2 + 1;
  685. VLC->modh->identifiers.requestIdentifier(scope, "object", "town", [=](si32 index)
  686. {
  687. // register town once objects are loaded
  688. JsonNode config = data["town"]["mapObject"];
  689. config["faction"].String() = name;
  690. config["faction"].meta = scope;
  691. VLC->objtypeh->loadSubObject(object->identifier, config, index, object->index);
  692. });
  693. }
  694. VLC->modh->identifiers.registerObject(scope, "faction", name, object->index);
  695. }
  696. void CTownHandler::loadRandomFaction()
  697. {
  698. static const ResourceID randomFactionPath("config/factions/random.json");
  699. JsonNode randomFactionJson(randomFactionPath);
  700. randomFactionJson.setMeta("core", true);
  701. loadBuildings(randomTown, randomFactionJson["random"]["town"]["buildings"]);
  702. }
  703. void CTownHandler::loadCustom()
  704. {
  705. loadRandomFaction();
  706. }
  707. void CTownHandler::afterLoadFinalization()
  708. {
  709. initializeRequirements();
  710. initializeWarMachines();
  711. }
  712. void CTownHandler::initializeRequirements()
  713. {
  714. // must be done separately after all ID's are known
  715. for (auto & requirement : requirementsToLoad)
  716. {
  717. requirement.building->requirements = CBuilding::TRequired(requirement.json, [&](const JsonNode & node) -> BuildingID
  718. {
  719. if (node.Vector().size() > 1)
  720. {
  721. logMod->warn("Unexpected length of town buildings requirements: %d", node.Vector().size());
  722. logMod->warn("Entry contains: ");
  723. logMod->warn(node.toJson());
  724. }
  725. return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get());
  726. });
  727. }
  728. requirementsToLoad.clear();
  729. }
  730. void CTownHandler::initializeWarMachines()
  731. {
  732. // must be done separately after all objects are loaded
  733. for(auto & p : warMachinesToLoad)
  734. {
  735. CTown * t = p.first;
  736. JsonNode creatureKey = p.second;
  737. auto ret = VLC->modh->identifiers.getIdentifier("creature", creatureKey, false);
  738. if(ret)
  739. {
  740. const CCreature * creature = CreatureID(*ret).toCreature();
  741. t->warMachine = creature->warMachine;
  742. }
  743. }
  744. warMachinesToLoad.clear();
  745. }
  746. std::vector<bool> CTownHandler::getDefaultAllowed() const
  747. {
  748. std::vector<bool> allowedFactions;
  749. for(auto town : factions)
  750. {
  751. allowedFactions.push_back(town->town != nullptr);
  752. }
  753. return allowedFactions;
  754. }
  755. std::set<TFaction> CTownHandler::getAllowedFactions(bool withTown) const
  756. {
  757. std::set<TFaction> allowedFactions;
  758. std::vector<bool> allowed;
  759. if (withTown)
  760. allowed = getDefaultAllowed();
  761. else
  762. allowed.resize( factions.size(), true);
  763. for (size_t i=0; i<allowed.size(); i++)
  764. if (allowed[i])
  765. allowedFactions.insert((TFaction)i);
  766. return allowedFactions;
  767. }
  768. si32 CTownHandler::decodeFaction(const std::string & identifier)
  769. {
  770. auto rawId = VLC->modh->identifiers.getIdentifier("core", "faction", identifier);
  771. if(rawId)
  772. return rawId.get();
  773. else
  774. return -1;
  775. }
  776. std::string CTownHandler::encodeFaction(const si32 index)
  777. {
  778. return VLC->townh->factions[index]->identifier;
  779. }