CHeroHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. #include "StdInc.h"
  2. #include "CHeroHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "VCMI_Lib.h"
  6. #include "JsonNode.h"
  7. #include "StringConstants.h"
  8. #include "BattleHex.h"
  9. #include "CModHandler.h"
  10. #include "CTownHandler.h"
  11. #include "CObjectHandler.h" //for hero specialty
  12. #include <math.h>
  13. /*
  14. * CHeroHandler.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, std::minstd_rand & distr) const //picks secondary skill out from given possibilities
  23. {
  24. int totalProb = 0;
  25. for(auto & possible : possibles)
  26. {
  27. totalProb += secSkillProbability[possible];
  28. }
  29. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  30. {
  31. int ran = distr()%totalProb;
  32. for(auto & possible : possibles)
  33. {
  34. ran -= secSkillProbability[possible];
  35. if(ran<0)
  36. return possible;
  37. }
  38. }
  39. // FIXME: select randomly? How H3 handles such rare situation?
  40. return *possibles.begin();
  41. }
  42. bool CHeroClass::isMagicHero() const
  43. {
  44. return id % 2; // 0 - might, 1 - magic
  45. }
  46. EAlignment::EAlignment CHeroClass::getAlignment() const
  47. {
  48. return EAlignment::EAlignment(VLC->townh->factions[faction]->alignment);
  49. }
  50. std::vector<BattleHex> CObstacleInfo::getBlocked(BattleHex hex) const
  51. {
  52. std::vector<BattleHex> ret;
  53. if(isAbsoluteObstacle)
  54. {
  55. assert(!hex.isValid());
  56. range::copy(blockedTiles, std::back_inserter(ret));
  57. return ret;
  58. }
  59. for(int offset : blockedTiles)
  60. {
  61. BattleHex toBlock = hex + offset;
  62. if((hex.getY() & 1) && !(toBlock.getY() & 1))
  63. toBlock += BattleHex::LEFT;
  64. if(!toBlock.isValid())
  65. logGlobal->errorStream() << "Misplaced obstacle!";
  66. else
  67. ret.push_back(toBlock);
  68. }
  69. return ret;
  70. }
  71. bool CObstacleInfo::isAppropriate(ETerrainType terrainType, int specialBattlefield /*= -1*/) const
  72. {
  73. if(specialBattlefield != -1)
  74. return vstd::contains(allowedSpecialBfields, specialBattlefield);
  75. return vstd::contains(allowedTerrains, terrainType);
  76. }
  77. CHeroClass *CHeroClassHandler::loadFromJson(const JsonNode & node)
  78. {
  79. auto heroClass = new CHeroClass();
  80. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  81. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  82. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  83. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  84. heroClass->name = node["name"].String();
  85. for(const std::string & pSkill : PrimarySkill::names)
  86. {
  87. heroClass->primarySkillInitial.push_back(node["primarySkills"][pSkill].Float());
  88. heroClass->primarySkillLowLevel.push_back(node["lowLevelChance"][pSkill].Float());
  89. heroClass->primarySkillHighLevel.push_back(node["highLevelChance"][pSkill].Float());
  90. }
  91. for(const std::string & secSkill : NSecondarySkill::names)
  92. {
  93. heroClass->secSkillProbability.push_back(node["secondarySkills"][secSkill].Float());
  94. }
  95. heroClass->defaultTavernChance = node["defaultTavern"].Float();
  96. for(auto & tavern : node["tavern"].Struct())
  97. {
  98. int value = tavern.second.Float();
  99. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  100. [=](si32 factionID)
  101. {
  102. heroClass->selectionProbability[factionID] = value;
  103. });
  104. }
  105. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  106. [=](si32 factionID)
  107. {
  108. heroClass->faction = factionID;
  109. });
  110. return heroClass;
  111. }
  112. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  113. {
  114. heroClasses.resize(dataSize);
  115. std::vector<JsonNode> h3Data;
  116. h3Data.reserve(dataSize);
  117. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  118. parser.endLine(); // header
  119. parser.endLine();
  120. for (size_t i=0; i<dataSize; i++)
  121. {
  122. JsonNode entry;
  123. entry["name"].String() = parser.readString();
  124. parser.readNumber(); // unused aggression
  125. for (auto & name : PrimarySkill::names)
  126. entry["primarySkills"][name].Float() = parser.readNumber();
  127. for (auto & name : PrimarySkill::names)
  128. entry["lowLevelChance"][name].Float() = parser.readNumber();
  129. for (auto & name : PrimarySkill::names)
  130. entry["highLevelChance"][name].Float() = parser.readNumber();
  131. for (auto & name : NSecondarySkill::names)
  132. entry["secondarySkills"][name].Float() = parser.readNumber();
  133. for(auto & name : ETownType::names)
  134. entry["tavern"][name].Float() = parser.readNumber();
  135. parser.endLine();
  136. h3Data.push_back(entry);
  137. }
  138. return h3Data;
  139. }
  140. void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  141. {
  142. auto object = loadFromJson(data);
  143. object->id = heroClasses.size();
  144. heroClasses.push_back(object);
  145. VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
  146. }
  147. void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  148. {
  149. auto object = loadFromJson(data);
  150. object->id = index;
  151. assert(heroClasses[index] == nullptr); // ensure that this id was not loaded before
  152. heroClasses[index] = object;
  153. VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
  154. }
  155. void CHeroClassHandler::afterLoadFinalization()
  156. {
  157. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  158. for (CHeroClass * heroClass : heroClasses)
  159. {
  160. for (CFaction * faction : VLC->townh->factions)
  161. {
  162. if (!faction->town)
  163. continue;
  164. if (heroClass->selectionProbability.count(faction->index))
  165. continue;
  166. float chance = heroClass->defaultTavernChance * faction->town->defaultTavernChance;
  167. heroClass->selectionProbability[faction->index] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  168. }
  169. }
  170. }
  171. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  172. {
  173. return std::vector<bool>(heroClasses.size(), true);
  174. }
  175. CHeroClassHandler::~CHeroClassHandler()
  176. {
  177. for(auto heroClass : heroClasses)
  178. {
  179. delete heroClass.get();
  180. }
  181. }
  182. CHeroHandler::~CHeroHandler()
  183. {
  184. for(auto hero : heroes)
  185. delete hero.get();
  186. }
  187. CHeroHandler::CHeroHandler()
  188. {
  189. VLC->heroh = this;
  190. for (int i = 0; i < GameConstants::SKILL_QUANTITY; ++i)
  191. {
  192. VLC->modh->identifiers.registerObject("core", "skill", NSecondarySkill::names[i], i);
  193. }
  194. loadObstacles();
  195. loadTerrains();
  196. loadBallistics();
  197. loadExperience();
  198. }
  199. CHero * CHeroHandler::loadFromJson(const JsonNode & node)
  200. {
  201. auto hero = new CHero;
  202. hero->sex = node["female"].Bool();
  203. hero->special = node["special"].Bool();
  204. hero->name = node["texts"]["name"].String();
  205. hero->biography = node["texts"]["biography"].String();
  206. hero->specName = node["texts"]["specialty"]["name"].String();
  207. hero->specTooltip = node["texts"]["specialty"]["tooltip"].String();
  208. hero->specDescr = node["texts"]["specialty"]["description"].String();
  209. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  210. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  211. hero->portraitSmall = node["images"]["small"].String();
  212. hero->portraitLarge = node["images"]["large"].String();
  213. loadHeroArmy(hero, node);
  214. loadHeroSkills(hero, node);
  215. loadHeroSpecialty(hero, node);
  216. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  217. [=](si32 classID)
  218. {
  219. hero->heroClass = classes.heroClasses[classID];
  220. });
  221. return hero;
  222. }
  223. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  224. {
  225. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  226. hero->initialArmy.resize(node["army"].Vector().size());
  227. for (size_t i=0; i< hero->initialArmy.size(); i++)
  228. {
  229. const JsonNode & source = node["army"].Vector()[i];
  230. hero->initialArmy[i].minAmount = source["min"].Float();
  231. hero->initialArmy[i].maxAmount = source["max"].Float();
  232. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  233. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  234. {
  235. hero->initialArmy[i].creature = CreatureID(creature);
  236. });
  237. }
  238. }
  239. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  240. {
  241. for(const JsonNode &set : node["skills"].Vector())
  242. {
  243. int skillLevel = boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels);
  244. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  245. {
  246. size_t currentIndex = hero->secSkillsInit.size();
  247. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  248. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  249. {
  250. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  251. });
  252. }
  253. else
  254. {
  255. logGlobal->errorStream() << "Unknown skill level: " <<set["level"].String();
  256. }
  257. }
  258. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  259. hero->haveSpellBook = !node["spellbook"].isNull();
  260. for(const JsonNode & spell : node["spellbook"].Vector())
  261. {
  262. VLC->modh->identifiers.requestIdentifier("spell", spell,
  263. [=](si32 spellID)
  264. {
  265. hero->spells.insert(SpellID(spellID));
  266. });
  267. }
  268. }
  269. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  270. {
  271. //deprecated, used only for original spciealties
  272. for(const JsonNode &specialty : node["specialties"].Vector())
  273. {
  274. SSpecialtyInfo spec;
  275. spec.type = specialty["type"].Float();
  276. spec.val = specialty["val"].Float();
  277. spec.subtype = specialty["subtype"].Float();
  278. spec.additionalinfo = specialty["info"].Float();
  279. hero->spec.push_back(spec); //put a copy of dummy
  280. }
  281. //new format, using bonus system
  282. for(const JsonNode &specialty : node["specialty"].Vector())
  283. {
  284. SSpecialtyBonus hs;
  285. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  286. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  287. {
  288. auto b = JsonUtils::parseBonus(bonus);
  289. hs.bonuses.push_back (b);
  290. }
  291. hero->specialty.push_back (hs); //now, how to get CGHeroInstance from it?
  292. }
  293. }
  294. void CHeroHandler::loadExperience()
  295. {
  296. expPerLevel.push_back(0);
  297. expPerLevel.push_back(1000);
  298. expPerLevel.push_back(2000);
  299. expPerLevel.push_back(3200);
  300. expPerLevel.push_back(4600);
  301. expPerLevel.push_back(6200);
  302. expPerLevel.push_back(8000);
  303. expPerLevel.push_back(10000);
  304. expPerLevel.push_back(12200);
  305. expPerLevel.push_back(14700);
  306. expPerLevel.push_back(17500);
  307. expPerLevel.push_back(20600);
  308. expPerLevel.push_back(24320);
  309. expPerLevel.push_back(28784);
  310. expPerLevel.push_back(34140);
  311. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  312. {
  313. int i = expPerLevel.size() - 1;
  314. expPerLevel.push_back (expPerLevel[i] + (expPerLevel[i] - expPerLevel[i-1]) * 1.2);
  315. }
  316. expPerLevel.pop_back();//last value is broken
  317. }
  318. void CHeroHandler::loadObstacles()
  319. {
  320. auto loadObstacles = [](const JsonNode &node, bool absolute, std::map<int, CObstacleInfo> &out)
  321. {
  322. for(const JsonNode &obs : node.Vector())
  323. {
  324. int ID = obs["id"].Float();
  325. CObstacleInfo & obi = out[ID];
  326. obi.ID = ID;
  327. obi.defName = obs["defname"].String();
  328. obi.width = obs["width"].Float();
  329. obi.height = obs["height"].Float();
  330. obi.allowedTerrains = obs["allowedTerrain"].convertTo<std::vector<ETerrainType> >();
  331. obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo<std::vector<BFieldType> >();
  332. obi.blockedTiles = obs["blockedTiles"].convertTo<std::vector<si16> >();
  333. obi.isAbsoluteObstacle = absolute;
  334. }
  335. };
  336. const JsonNode config(ResourceID("config/obstacles.json"));
  337. loadObstacles(config["obstacles"], false, obstacles);
  338. loadObstacles(config["absoluteObstacles"], true, absoluteObstacles);
  339. //loadObstacles(config["moats"], true, moats);
  340. }
  341. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  342. static std::string genRefName(std::string input)
  343. {
  344. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  345. input[0] = std::tolower(input[0]); // to camelCase
  346. return input;
  347. }
  348. void CHeroHandler::loadBallistics()
  349. {
  350. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  351. ballParser.endLine(); //header
  352. ballParser.endLine();
  353. do
  354. {
  355. ballParser.readString();
  356. ballParser.readString();
  357. CHeroHandler::SBallisticsLevelInfo bli;
  358. bli.keep = ballParser.readNumber();
  359. bli.tower = ballParser.readNumber();
  360. bli.gate = ballParser.readNumber();
  361. bli.wall = ballParser.readNumber();
  362. bli.shots = ballParser.readNumber();
  363. bli.noDmg = ballParser.readNumber();
  364. bli.oneDmg = ballParser.readNumber();
  365. bli.twoDmg = ballParser.readNumber();
  366. bli.sum = ballParser.readNumber();
  367. ballistics.push_back(bli);
  368. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  369. }
  370. while (ballParser.endLine());
  371. }
  372. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  373. {
  374. heroes.resize(dataSize);
  375. std::vector<JsonNode> h3Data;
  376. h3Data.reserve(dataSize);
  377. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  378. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  379. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  380. parser.endLine(); //ignore header
  381. parser.endLine();
  382. specParser.endLine(); //ignore header
  383. specParser.endLine();
  384. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  385. {
  386. JsonNode heroData;
  387. heroData["texts"]["name"].String() = parser.readString();
  388. heroData["texts"]["biography"].String() = bioParser.readString();
  389. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  390. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  391. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  392. for(int x=0;x<3;x++)
  393. {
  394. JsonNode armySlot;
  395. armySlot["min"].Float() = parser.readNumber();
  396. armySlot["max"].Float() = parser.readNumber();
  397. armySlot["creature"].String() = genRefName(parser.readString());
  398. heroData["army"].Vector().push_back(armySlot);
  399. }
  400. parser.endLine();
  401. specParser.endLine();
  402. bioParser.endLine();
  403. h3Data.push_back(heroData);
  404. }
  405. return h3Data;
  406. }
  407. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  408. {
  409. auto object = loadFromJson(data);
  410. object->ID = HeroTypeID(heroes.size());
  411. object->imageIndex = heroes.size() + 30; // 2 special frames + some extra portraits
  412. heroes.push_back(object);
  413. VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
  414. }
  415. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  416. {
  417. auto object = loadFromJson(data);
  418. object->ID = HeroTypeID(index);
  419. object->imageIndex = index;
  420. assert(heroes[index] == nullptr); // ensure that this id was not loaded before
  421. heroes[index] = object;
  422. VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
  423. }
  424. ui32 CHeroHandler::level (ui64 experience) const
  425. {
  426. return boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel);
  427. }
  428. ui64 CHeroHandler::reqExp (ui32 level) const
  429. {
  430. if(!level)
  431. return 0;
  432. if (level <= expPerLevel.size())
  433. {
  434. return expPerLevel[level-1];
  435. }
  436. else
  437. {
  438. logGlobal->warnStream() << "A hero has reached unsupported amount of experience";
  439. return expPerLevel[expPerLevel.size()-1];
  440. }
  441. }
  442. void CHeroHandler::loadTerrains()
  443. {
  444. const JsonNode config(ResourceID("config/terrains.json"));
  445. terrCosts.reserve(GameConstants::TERRAIN_TYPES);
  446. for(const std::string & name : GameConstants::TERRAIN_NAMES)
  447. terrCosts.push_back(config[name]["moveCost"].Float());
  448. }
  449. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  450. {
  451. // Look Data/HOTRAITS.txt for reference
  452. std::vector<bool> allowedHeroes;
  453. allowedHeroes.reserve(heroes.size());
  454. for(const CHero * hero : heroes)
  455. {
  456. allowedHeroes.push_back(!hero->special);
  457. }
  458. return allowedHeroes;
  459. }
  460. std::vector<bool> CHeroHandler::getDefaultAllowedAbilities() const
  461. {
  462. std::vector<bool> allowedAbilities;
  463. allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);
  464. return allowedAbilities;
  465. }