CHeroHandler.cpp 15 KB

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