CHeroHandler.cpp 12 KB

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