CHeroHandler.cpp 15 KB

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