CHeroHandler.cpp 17 KB

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