CHeroHandler.cpp 17 KB

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