CHeroHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. * CHeroHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CHeroHandler.h"
  12. #include "CHero.h"
  13. #include "../../GameLibrary.h"
  14. #include "../../constants/StringConstants.h"
  15. #include "../../CCreatureHandler.h"
  16. #include "../../IGameSettings.h"
  17. #include "../../bonuses/Limiters.h"
  18. #include "../../bonuses/Updaters.h"
  19. #include "../../json/JsonBonus.h"
  20. #include "../../json/JsonUtils.h"
  21. #include "../../modding/IdentifierStorage.h"
  22. #include "../../CSkillHandler.h"
  23. #include "../../texts/CGeneralTextHandler.h"
  24. #include "../../texts/CLegacyConfigParser.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. CHeroHandler::~CHeroHandler() = default;
  27. CHeroHandler::CHeroHandler()
  28. {
  29. loadExperience();
  30. }
  31. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  32. {
  33. static const std::vector<std::string> typeNames = { "hero" };
  34. return typeNames;
  35. }
  36. std::shared_ptr<CHero> CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  37. {
  38. assert(identifier.find(':') == std::string::npos);
  39. assert(!scope.empty());
  40. auto hero = std::make_shared<CHero>();
  41. hero->ID = HeroTypeID(index);
  42. hero->identifier = identifier;
  43. hero->modScope = scope;
  44. hero->gender = node["female"].Bool() ? EHeroGender::FEMALE : EHeroGender::MALE;
  45. hero->special = node["special"].Bool();
  46. //Default - both false
  47. hero->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  48. hero->onlyOnMapWithoutWater = node["onlyOnMapWithoutWater"].Bool();
  49. LIBRARY->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"]);
  50. LIBRARY->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"]);
  51. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"]);
  52. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"]);
  53. LIBRARY->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"]);
  54. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  55. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  56. hero->portraitSmall = node["images"]["small"].String();
  57. hero->portraitLarge = node["images"]["large"].String();
  58. hero->battleImage = AnimationPath::fromJson(node["battleImage"]);
  59. loadHeroArmy(hero.get(), node);
  60. loadHeroSkills(hero.get(), node);
  61. loadHeroSpecialty(hero.get(), node);
  62. LIBRARY->identifiers()->requestIdentifier("heroClass", node["class"],
  63. [=](si32 classID)
  64. {
  65. hero->heroClass = HeroClassID(classID).toHeroClass();
  66. });
  67. return hero;
  68. }
  69. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node) const
  70. {
  71. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  72. hero->initialArmy.resize(node["army"].Vector().size());
  73. for (size_t i=0; i< hero->initialArmy.size(); i++)
  74. {
  75. const JsonNode & source = node["army"].Vector()[i];
  76. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  77. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  78. if (hero->initialArmy[i].minAmount > hero->initialArmy[i].maxAmount)
  79. {
  80. logMod->error("Hero %s has minimal army size (%d) greater than maximal size (%d)!", hero->getJsonKey(), hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  81. std::swap(hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  82. }
  83. LIBRARY->identifiers()->requestIdentifier("creature", source["creature"], [=](si32 creature)
  84. {
  85. hero->initialArmy[i].creature = CreatureID(creature);
  86. });
  87. }
  88. }
  89. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node) const
  90. {
  91. for(const JsonNode &set : node["skills"].Vector())
  92. {
  93. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  94. if (skillLevel < MasteryLevel::LEVELS_SIZE)
  95. {
  96. size_t currentIndex = hero->secSkillsInit.size();
  97. hero->secSkillsInit.emplace_back(SecondarySkill(-1), skillLevel);
  98. LIBRARY->identifiers()->requestIdentifier("skill", set["skill"], [=](si32 id)
  99. {
  100. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  101. });
  102. }
  103. else
  104. {
  105. logMod->error("Unknown skill level: %s", set["level"].String());
  106. }
  107. }
  108. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  109. hero->haveSpellBook = !node["spellbook"].isNull();
  110. for(const JsonNode & spell : node["spellbook"].Vector())
  111. {
  112. LIBRARY->identifiers()->requestIdentifier("spell", spell,
  113. [=](si32 spellID)
  114. {
  115. hero->spells.insert(SpellID(spellID));
  116. });
  117. }
  118. }
  119. /// creates standard H3 hero specialty for creatures
  120. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createCreatureSpecialty(CreatureID cid) const
  121. {
  122. std::vector<std::shared_ptr<Bonus>> result;
  123. const auto & specCreature = *cid.toCreature();
  124. int level = specCreature.hasBonusOfType(BonusType::SIEGE_WEAPON) ? 5 : specCreature.getLevel();
  125. {
  126. auto bonus = std::make_shared<Bonus>();
  127. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  128. bonus->type = BonusType::STACKS_SPEED;
  129. bonus->val = 1;
  130. result.push_back(bonus);
  131. }
  132. for (const auto & skill : { PrimarySkill::ATTACK, PrimarySkill::DEFENSE})
  133. {
  134. auto bonus = std::make_shared<Bonus>();
  135. bonus->type = BonusType::PRIMARY_SKILL;
  136. bonus->subtype = BonusSubtypeID(skill);
  137. bonus->val = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_SPECIALTY_CREATURE_GROWTH);
  138. bonus->valType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  139. bonus->targetSourceType = BonusSource::CREATURE_ABILITY;
  140. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  141. bonus->updater.reset(new TimesHeroLevelUpdater(level));
  142. result.push_back(bonus);
  143. }
  144. return result;
  145. }
  146. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createSecondarySkillSpecialty(SecondarySkill skillID) const
  147. {
  148. std::vector<std::shared_ptr<Bonus>> result;
  149. const auto & skillPtr = LIBRARY->skillh->objects[skillID.getNum()];
  150. if (skillPtr->specialtyTargetBonuses.empty())
  151. logMod->warn("Skill '%s' does not supports generic specialties!", skillPtr->getJsonKey());
  152. for (const auto & bonus : skillPtr->specialtyTargetBonuses)
  153. result.push_back(std::make_shared<Bonus>(*bonus));
  154. return result;
  155. }
  156. void CHeroHandler::beforeValidate(JsonNode & object)
  157. {
  158. //handle "base" specialty info
  159. JsonNode & specialtyNode = object["specialty"];
  160. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  161. {
  162. const JsonNode & base = specialtyNode["base"];
  163. if(!base.isNull())
  164. {
  165. if(specialtyNode["bonuses"].isNull())
  166. {
  167. logMod->warn("specialty has base without bonuses");
  168. }
  169. else
  170. {
  171. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  172. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  173. JsonUtils::inherit(bonuses[keyValue.first], base);
  174. }
  175. }
  176. }
  177. }
  178. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node) const
  179. {
  180. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  181. {
  182. bonus->duration = BonusDuration::PERMANENT;
  183. bonus->source = BonusSource::HERO_SPECIAL;
  184. bonus->sid = BonusSourceID(hero->getId());
  185. return bonus;
  186. };
  187. //new format, using bonus system
  188. const JsonNode & specialtyNode = node["specialty"];
  189. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  190. {
  191. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  192. return;
  193. }
  194. //creature specialty - alias for simplicity
  195. if(!specialtyNode["creature"].isNull())
  196. {
  197. LIBRARY->identifiers()->requestIdentifier("creature", specialtyNode["creature"], [this, hero, prepSpec](si32 creature)
  198. {
  199. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature)))
  200. hero->specialty.push_back(prepSpec(bonus));
  201. });
  202. }
  203. //secondary skill specialty - alias for simplicity
  204. if(!specialtyNode["secondary"].isNull())
  205. {
  206. LIBRARY->identifiers()->requestIdentifier("secondarySkill", specialtyNode["secondary"], [this, hero, prepSpec](si32 creature)
  207. {
  208. for (const auto & bonus : createSecondarySkillSpecialty(SecondarySkill(creature)))
  209. hero->specialty.push_back(prepSpec(bonus));
  210. });
  211. }
  212. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  213. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  214. }
  215. void CHeroHandler::loadExperience()
  216. {
  217. expPerLevel.push_back(0);
  218. expPerLevel.push_back(1000);
  219. expPerLevel.push_back(2000);
  220. expPerLevel.push_back(3200);
  221. expPerLevel.push_back(4600);
  222. expPerLevel.push_back(6200);
  223. expPerLevel.push_back(8000);
  224. expPerLevel.push_back(10000);
  225. expPerLevel.push_back(12200);
  226. expPerLevel.push_back(14700);
  227. expPerLevel.push_back(17500);
  228. expPerLevel.push_back(20600);
  229. expPerLevel.push_back(24320);
  230. expPerLevel.push_back(28784);
  231. expPerLevel.push_back(34140);
  232. for (;;)
  233. {
  234. auto i = expPerLevel.size() - 1;
  235. auto currExp = expPerLevel[i];
  236. auto prevExp = expPerLevel[i-1];
  237. auto prevDiff = currExp - prevExp;
  238. auto nextDiff = prevDiff + prevDiff / 5;
  239. auto maxExp = std::numeric_limits<decltype(currExp)>::max();
  240. if (currExp > maxExp - nextDiff)
  241. break; // overflow point reached
  242. expPerLevel.push_back (currExp + nextDiff);
  243. }
  244. }
  245. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  246. static std::string genRefName(std::string input)
  247. {
  248. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  249. input[0] = std::tolower(input[0]); // to camelCase
  250. return input;
  251. }
  252. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  253. {
  254. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_HERO);
  255. objects.resize(dataSize);
  256. std::vector<JsonNode> h3Data;
  257. h3Data.reserve(dataSize);
  258. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  259. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  260. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  261. parser.endLine(); //ignore header
  262. parser.endLine();
  263. specParser.endLine(); //ignore header
  264. specParser.endLine();
  265. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  266. {
  267. JsonNode heroData;
  268. heroData["texts"]["name"].String() = parser.readString();
  269. heroData["texts"]["biography"].String() = bioParser.readString();
  270. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  271. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  272. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  273. for(int x=0;x<3;x++)
  274. {
  275. JsonNode armySlot;
  276. armySlot["min"].Float() = parser.readNumber();
  277. armySlot["max"].Float() = parser.readNumber();
  278. armySlot["creature"].String() = genRefName(parser.readString());
  279. heroData["army"].Vector().push_back(armySlot);
  280. }
  281. parser.endLine();
  282. specParser.endLine();
  283. bioParser.endLine();
  284. h3Data.push_back(heroData);
  285. }
  286. return h3Data;
  287. }
  288. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  289. {
  290. size_t index = objects.size();
  291. static const int specialFramesCount = 2; // reserved for 2 special frames
  292. auto object = loadFromJson(scope, data, name, index);
  293. object->imageIndex = static_cast<si32>(index) + specialFramesCount;
  294. objects.emplace_back(object);
  295. registerObject(scope, "hero", name, object->getIndex());
  296. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  297. registerObject(scope, "hero", compatID.String(), object->getIndex());
  298. }
  299. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  300. {
  301. auto object = loadFromJson(scope, data, name, index);
  302. object->imageIndex = static_cast<si32>(index);
  303. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  304. objects[index] = object;
  305. registerObject(scope, "hero", name, object->getIndex());
  306. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  307. registerObject(scope, "hero", compatID.String(), object->getIndex());
  308. }
  309. ui32 CHeroHandler::level (TExpType experience) const
  310. {
  311. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  312. }
  313. TExpType CHeroHandler::reqExp (ui32 level) const
  314. {
  315. if(!level)
  316. return 0;
  317. if (level <= expPerLevel.size())
  318. {
  319. return expPerLevel[level-1];
  320. }
  321. else
  322. {
  323. logGlobal->warn("A hero has reached unsupported amount of experience");
  324. return expPerLevel[expPerLevel.size()-1];
  325. }
  326. }
  327. ui32 CHeroHandler::maxSupportedLevel() const
  328. {
  329. return expPerLevel.size();
  330. }
  331. std::set<HeroTypeID> CHeroHandler::getDefaultAllowed() const
  332. {
  333. std::set<HeroTypeID> result;
  334. for(auto & hero : objects)
  335. if (hero && !hero->special)
  336. result.insert(hero->getId());
  337. return result;
  338. }
  339. VCMI_LIB_NAMESPACE_END