CHeroHandler.cpp 15 KB

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