CHeroHandler.cpp 16 KB

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