CHeroHandler.cpp 17 KB

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