CHeroHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createCreatureSpecialty(CreatureID cid, int fixedLevel, int growthPerStep) const
  120. {
  121. std::vector<std::shared_ptr<Bonus>> result;
  122. const auto & specCreature = *cid.toCreature();
  123. if (fixedLevel == 0)
  124. fixedLevel = specCreature.getLevel();
  125. if (fixedLevel == 0)
  126. {
  127. fixedLevel = 5;
  128. logMod->warn("Creature '%s' of level 0 has hero with generic specialty! Please specify level explicitly or give creature non-zero level", specCreature.getJsonKey());
  129. }
  130. if (growthPerStep == 0)
  131. growthPerStep = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_SPECIALTY_CREATURE_GROWTH);
  132. {
  133. auto bonus = std::make_shared<Bonus>();
  134. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  135. bonus->type = BonusType::STACKS_SPEED;
  136. bonus->val = 1;
  137. result.push_back(bonus);
  138. }
  139. for (const auto & skill : { PrimarySkill::ATTACK, PrimarySkill::DEFENSE})
  140. {
  141. auto bonus = std::make_shared<Bonus>();
  142. bonus->type = BonusType::PRIMARY_SKILL;
  143. bonus->subtype = BonusSubtypeID(skill);
  144. bonus->val = growthPerStep;
  145. bonus->valType = BonusValueType::PERCENT_TO_TARGET_TYPE;
  146. bonus->targetSourceType = BonusSource::CREATURE_ABILITY;
  147. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, true));
  148. bonus->updater.reset(new TimesHeroLevelUpdater(fixedLevel));
  149. result.push_back(bonus);
  150. }
  151. return result;
  152. }
  153. std::vector<std::shared_ptr<Bonus>> CHeroHandler::createSecondarySkillSpecialty(SecondarySkill skillID, int growthPerStep) const
  154. {
  155. std::vector<std::shared_ptr<Bonus>> result;
  156. const auto & skillPtr = LIBRARY->skillh->objects[skillID.getNum()];
  157. if (skillPtr->specialtyTargetBonuses.empty())
  158. logMod->warn("Skill '%s' does not supports generic specialties!", skillPtr->getJsonKey());
  159. if (growthPerStep == 0)
  160. growthPerStep = LIBRARY->engineSettings()->getInteger(EGameSettings::HEROES_SPECIALTY_SECONDARY_SKILL_GROWTH);
  161. for (const auto & bonus : skillPtr->specialtyTargetBonuses)
  162. {
  163. auto bonusCopy = std::make_shared<Bonus>(*bonus);
  164. bonusCopy->val = growthPerStep;
  165. result.push_back(bonusCopy);
  166. }
  167. return result;
  168. }
  169. void CHeroHandler::beforeValidate(JsonNode & object)
  170. {
  171. //handle "base" specialty info
  172. JsonNode & specialtyNode = object["specialty"];
  173. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  174. {
  175. if(specialtyNode.Struct().count("base") != 0)
  176. {
  177. const JsonNode & base = specialtyNode["base"];
  178. if(specialtyNode["bonuses"].isNull())
  179. {
  180. logMod->warn("specialty has base without bonuses");
  181. }
  182. else
  183. {
  184. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  185. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  186. JsonUtils::inherit(bonuses[keyValue.first], base);
  187. }
  188. specialtyNode.Struct().erase("base");
  189. }
  190. }
  191. }
  192. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node) const
  193. {
  194. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  195. {
  196. bonus->duration = BonusDuration::PERMANENT;
  197. bonus->source = BonusSource::HERO_SPECIAL;
  198. bonus->sid = BonusSourceID(hero->getId());
  199. return bonus;
  200. };
  201. //new format, using bonus system
  202. const JsonNode & specialtyNode = node["specialty"];
  203. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  204. {
  205. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  206. return;
  207. }
  208. //creature specialty - alias for simplicity
  209. if(!specialtyNode["creature"].isNull())
  210. {
  211. const JsonNode & creatureNode = specialtyNode["creature"];
  212. int targetLevel = specialtyNode["creatureLevel"].Integer();
  213. int stepSize = specialtyNode["stepSize"].Integer();
  214. LIBRARY->identifiers()->requestIdentifier("creature", creatureNode, [this, hero, prepSpec, targetLevel, stepSize](si32 creature)
  215. {
  216. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature), targetLevel, stepSize))
  217. hero->specialty.push_back(prepSpec(bonus));
  218. });
  219. }
  220. //secondary skill specialty - alias for simplicity
  221. if(!specialtyNode["secondary"].isNull())
  222. {
  223. const JsonNode & skillNode = specialtyNode["secondary"];
  224. int stepSize = specialtyNode["stepSize"].Integer();
  225. LIBRARY->identifiers()->requestIdentifier("secondarySkill", skillNode, [this, hero, prepSpec, stepSize](si32 creature)
  226. {
  227. for (const auto & bonus : createSecondarySkillSpecialty(SecondarySkill(creature), stepSize))
  228. hero->specialty.push_back(prepSpec(bonus));
  229. });
  230. }
  231. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  232. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  233. }
  234. void CHeroHandler::loadExperience()
  235. {
  236. expPerLevel.push_back(0);
  237. expPerLevel.push_back(1000);
  238. expPerLevel.push_back(2000);
  239. expPerLevel.push_back(3200);
  240. expPerLevel.push_back(4600);
  241. expPerLevel.push_back(6200);
  242. expPerLevel.push_back(8000);
  243. expPerLevel.push_back(10000);
  244. expPerLevel.push_back(12200);
  245. expPerLevel.push_back(14700);
  246. expPerLevel.push_back(17500);
  247. expPerLevel.push_back(20600);
  248. expPerLevel.push_back(24320);
  249. expPerLevel.push_back(28784);
  250. expPerLevel.push_back(34140);
  251. for (;;)
  252. {
  253. auto i = expPerLevel.size() - 1;
  254. auto currExp = expPerLevel[i];
  255. auto prevExp = expPerLevel[i-1];
  256. auto prevDiff = currExp - prevExp;
  257. auto nextDiff = prevDiff + prevDiff / 5;
  258. auto maxExp = std::numeric_limits<decltype(currExp)>::max();
  259. if (currExp > maxExp - nextDiff)
  260. break; // overflow point reached
  261. expPerLevel.push_back (currExp + nextDiff);
  262. }
  263. }
  264. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  265. static std::string genRefName(std::string input)
  266. {
  267. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  268. input[0] = std::tolower(input[0]); // to camelCase
  269. return input;
  270. }
  271. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  272. {
  273. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_HERO);
  274. objects.resize(dataSize);
  275. std::vector<JsonNode> h3Data;
  276. h3Data.reserve(dataSize);
  277. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  278. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  279. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  280. parser.endLine(); //ignore header
  281. parser.endLine();
  282. specParser.endLine(); //ignore header
  283. specParser.endLine();
  284. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  285. {
  286. JsonNode heroData;
  287. heroData["texts"]["name"].String() = parser.readString();
  288. heroData["texts"]["biography"].String() = bioParser.readString();
  289. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  290. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  291. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  292. for(int x=0;x<3;x++)
  293. {
  294. JsonNode armySlot;
  295. armySlot["min"].Float() = parser.readNumber();
  296. armySlot["max"].Float() = parser.readNumber();
  297. armySlot["creature"].String() = genRefName(parser.readString());
  298. heroData["army"].Vector().push_back(armySlot);
  299. }
  300. parser.endLine();
  301. specParser.endLine();
  302. bioParser.endLine();
  303. h3Data.push_back(heroData);
  304. }
  305. return h3Data;
  306. }
  307. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  308. {
  309. size_t index = objects.size();
  310. static const int specialFramesCount = 2; // reserved for 2 special frames
  311. auto object = loadFromJson(scope, data, name, index);
  312. object->imageIndex = static_cast<si32>(index) + specialFramesCount;
  313. objects.emplace_back(object);
  314. registerObject(scope, "hero", name, object->getIndex());
  315. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  316. registerObject(scope, "hero", compatID.String(), object->getIndex());
  317. }
  318. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  319. {
  320. auto object = loadFromJson(scope, data, name, index);
  321. object->imageIndex = static_cast<si32>(index);
  322. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  323. objects[index] = object;
  324. registerObject(scope, "hero", name, object->getIndex());
  325. for(const auto & compatID : data["compatibilityIdentifiers"].Vector())
  326. registerObject(scope, "hero", compatID.String(), object->getIndex());
  327. }
  328. ui32 CHeroHandler::level (TExpType experience) const
  329. {
  330. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  331. }
  332. TExpType CHeroHandler::reqExp (ui32 level) const
  333. {
  334. if(!level)
  335. return 0;
  336. if (level <= expPerLevel.size())
  337. {
  338. return expPerLevel[level-1];
  339. }
  340. else
  341. {
  342. logGlobal->warn("A hero has reached unsupported amount of experience");
  343. return expPerLevel[expPerLevel.size()-1];
  344. }
  345. }
  346. ui32 CHeroHandler::maxSupportedLevel() const
  347. {
  348. return expPerLevel.size();
  349. }
  350. std::set<HeroTypeID> CHeroHandler::getDefaultAllowed() const
  351. {
  352. std::set<HeroTypeID> result;
  353. for(auto & hero : objects)
  354. if (hero && !hero->special)
  355. result.insert(hero->getId());
  356. return result;
  357. }
  358. VCMI_LIB_NAMESPACE_END