CHeroHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 "CGeneralTextHandler.h"
  13. #include "filesystem/Filesystem.h"
  14. #include "VCMI_Lib.h"
  15. #include "JsonNode.h"
  16. #include "constants/StringConstants.h"
  17. #include "battle/BattleHex.h"
  18. #include "CCreatureHandler.h"
  19. #include "GameSettings.h"
  20. #include "CTownHandler.h"
  21. #include "CSkillHandler.h"
  22. #include "BattleFieldHandler.h"
  23. #include "bonuses/Limiters.h"
  24. #include "bonuses/Updaters.h"
  25. #include "mapObjectConstructors/AObjectTypeHandler.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.h"
  27. #include "modding/IdentifierStorage.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. CHero::CHero() = default;
  30. CHero::~CHero() = default;
  31. int32_t CHero::getIndex() const
  32. {
  33. return ID.getNum();
  34. }
  35. int32_t CHero::getIconIndex() const
  36. {
  37. return imageIndex;
  38. }
  39. std::string CHero::getJsonKey() const
  40. {
  41. return modScope + ':' + identifier;;
  42. }
  43. HeroTypeID CHero::getId() const
  44. {
  45. return ID;
  46. }
  47. std::string CHero::getNameTranslated() const
  48. {
  49. return VLC->generaltexth->translate(getNameTextID());
  50. }
  51. std::string CHero::getBiographyTranslated() const
  52. {
  53. return VLC->generaltexth->translate(getBiographyTextID());
  54. }
  55. std::string CHero::getSpecialtyNameTranslated() const
  56. {
  57. return VLC->generaltexth->translate(getSpecialtyNameTextID());
  58. }
  59. std::string CHero::getSpecialtyDescriptionTranslated() const
  60. {
  61. return VLC->generaltexth->translate(getSpecialtyDescriptionTextID());
  62. }
  63. std::string CHero::getSpecialtyTooltipTranslated() const
  64. {
  65. return VLC->generaltexth->translate(getSpecialtyTooltipTextID());
  66. }
  67. std::string CHero::getNameTextID() const
  68. {
  69. return TextIdentifier("hero", modScope, identifier, "name").get();
  70. }
  71. std::string CHero::getBiographyTextID() const
  72. {
  73. return TextIdentifier("hero", modScope, identifier, "biography").get();
  74. }
  75. std::string CHero::getSpecialtyNameTextID() const
  76. {
  77. return TextIdentifier("hero", modScope, identifier, "specialty", "name").get();
  78. }
  79. std::string CHero::getSpecialtyDescriptionTextID() const
  80. {
  81. return TextIdentifier("hero", modScope, identifier, "specialty", "description").get();
  82. }
  83. std::string CHero::getSpecialtyTooltipTextID() const
  84. {
  85. return TextIdentifier("hero", modScope, identifier, "specialty", "tooltip").get();
  86. }
  87. void CHero::registerIcons(const IconRegistar & cb) const
  88. {
  89. cb(getIconIndex(), 0, "UN32", iconSpecSmall);
  90. cb(getIconIndex(), 0, "UN44", iconSpecLarge);
  91. cb(getIconIndex(), 0, "PORTRAITSLARGE", portraitLarge);
  92. cb(getIconIndex(), 0, "PORTRAITSSMALL", portraitSmall);
  93. }
  94. void CHero::updateFrom(const JsonNode & data)
  95. {
  96. //todo: CHero::updateFrom
  97. }
  98. void CHero::serializeJson(JsonSerializeFormat & handler)
  99. {
  100. }
  101. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  102. {
  103. assert(!possibles.empty());
  104. if (possibles.size() == 1)
  105. return *possibles.begin();
  106. int totalProb = 0;
  107. for(const auto & possible : possibles)
  108. if (secSkillProbability.count(possible) != 0)
  109. totalProb += secSkillProbability.at(possible);
  110. if (totalProb == 0) // may trigger if set contains only banned skills (0 probability)
  111. return *RandomGeneratorUtil::nextItem(possibles, rand);
  112. auto ran = rand.nextInt(totalProb - 1);
  113. for(const auto & possible : possibles)
  114. {
  115. if (secSkillProbability.count(possible) != 0)
  116. ran -= secSkillProbability.at(possible);
  117. if(ran < 0)
  118. return possible;
  119. }
  120. assert(0); // should not be possible
  121. return *possibles.begin();
  122. }
  123. bool CHeroClass::isMagicHero() const
  124. {
  125. return affinity == MAGIC;
  126. }
  127. EAlignment CHeroClass::getAlignment() const
  128. {
  129. return VLC->factions()->getById(faction)->getAlignment();
  130. }
  131. int32_t CHeroClass::getIndex() const
  132. {
  133. return id.getNum();
  134. }
  135. int32_t CHeroClass::getIconIndex() const
  136. {
  137. return getIndex();
  138. }
  139. std::string CHeroClass::getJsonKey() const
  140. {
  141. return modScope + ':' + identifier;;
  142. }
  143. HeroClassID CHeroClass::getId() const
  144. {
  145. return id;
  146. }
  147. void CHeroClass::registerIcons(const IconRegistar & cb) const
  148. {
  149. }
  150. std::string CHeroClass::getNameTranslated() const
  151. {
  152. return VLC->generaltexth->translate(getNameTextID());
  153. }
  154. std::string CHeroClass::getNameTextID() const
  155. {
  156. return TextIdentifier("heroClass", modScope, identifier, "name").get();
  157. }
  158. void CHeroClass::updateFrom(const JsonNode & data)
  159. {
  160. //TODO: CHeroClass::updateFrom
  161. }
  162. void CHeroClass::serializeJson(JsonSerializeFormat & handler)
  163. {
  164. }
  165. CHeroClass::CHeroClass():
  166. faction(0),
  167. affinity(0),
  168. defaultTavernChance(0),
  169. commander(nullptr)
  170. {
  171. }
  172. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill pSkill) const
  173. {
  174. const auto & skillName = NPrimarySkill::names[pSkill.getNum()];
  175. auto currentPrimarySkillValue = static_cast<int>(node["primarySkills"][skillName].Integer());
  176. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  177. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  178. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  179. {
  180. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  181. heroClass->getNameTranslated(), currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  182. currentPrimarySkillValue = primarySkillLegalMinimum;
  183. }
  184. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  185. heroClass->primarySkillLowLevel.push_back(static_cast<int>(node["lowLevelChance"][skillName].Float()));
  186. heroClass->primarySkillHighLevel.push_back(static_cast<int>(node["highLevelChance"][skillName].Float()));
  187. }
  188. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  189. {
  190. static const std::vector<std::string> typeNames = { "heroClass" };
  191. return typeNames;
  192. }
  193. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  194. {
  195. assert(identifier.find(':') == std::string::npos);
  196. assert(!scope.empty());
  197. std::string affinityStr[2] = { "might", "magic" };
  198. auto * heroClass = new CHeroClass();
  199. heroClass->id = HeroClassID(index);
  200. heroClass->identifier = identifier;
  201. heroClass->modScope = scope;
  202. heroClass->imageBattleFemale = AnimationPath::fromJson(node["animation"]["battle"]["female"]);
  203. heroClass->imageBattleMale = AnimationPath::fromJson(node["animation"]["battle"]["male"]);
  204. //MODS COMPATIBILITY FOR 0.96
  205. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  206. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  207. VLC->generaltexth->registerString(scope, heroClass->getNameTextID(), node["name"].String());
  208. if (vstd::contains(affinityStr, node["affinity"].String()))
  209. {
  210. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  211. }
  212. else
  213. {
  214. logGlobal->error("Mod '%s', hero class '%s': invalid affinity '%s'! Expected 'might' or 'magic'!", scope, identifier, node["affinity"].String());
  215. heroClass->affinity = CHeroClass::MIGHT;
  216. }
  217. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  218. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  219. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  220. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  221. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  222. if(percentSumm != 100)
  223. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  224. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  225. if(percentSumm != 100)
  226. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  227. for(auto skillPair : node["secondarySkills"].Struct())
  228. {
  229. int probability = static_cast<int>(skillPair.second.Integer());
  230. VLC->identifiers()->requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  231. {
  232. heroClass->secSkillProbability[skillID] = probability;
  233. });
  234. }
  235. VLC->identifiers()->requestIdentifier ("creature", node["commander"],
  236. [=](si32 commanderID)
  237. {
  238. heroClass->commander = VLC->creh->objects[commanderID];
  239. });
  240. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  241. for(const auto & tavern : node["tavern"].Struct())
  242. {
  243. int value = static_cast<int>(tavern.second.Float());
  244. VLC->identifiers()->requestIdentifier(tavern.second.meta, "faction", tavern.first,
  245. [=](si32 factionID)
  246. {
  247. heroClass->selectionProbability[FactionID(factionID)] = value;
  248. });
  249. }
  250. VLC->identifiers()->requestIdentifier("faction", node["faction"],
  251. [=](si32 factionID)
  252. {
  253. heroClass->faction.setNum(factionID);
  254. });
  255. VLC->identifiers()->requestIdentifier(scope, "object", "hero", [=](si32 index)
  256. {
  257. JsonNode classConf = node["mapObject"];
  258. classConf["heroClass"].String() = identifier;
  259. classConf.setMeta(scope);
  260. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  261. });
  262. return heroClass;
  263. }
  264. std::vector<JsonNode> CHeroClassHandler::loadLegacyData()
  265. {
  266. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO_CLASS);
  267. objects.resize(dataSize);
  268. std::vector<JsonNode> h3Data;
  269. h3Data.reserve(dataSize);
  270. CLegacyConfigParser parser(TextPath::builtin("DATA/HCTRAITS.TXT"));
  271. parser.endLine(); // header
  272. parser.endLine();
  273. for (size_t i=0; i<dataSize; i++)
  274. {
  275. JsonNode entry;
  276. entry["name"].String() = parser.readString();
  277. parser.readNumber(); // unused aggression
  278. for(const auto & name : NPrimarySkill::names)
  279. entry["primarySkills"][name].Float() = parser.readNumber();
  280. for(const auto & name : NPrimarySkill::names)
  281. entry["lowLevelChance"][name].Float() = parser.readNumber();
  282. for(const auto & name : NPrimarySkill::names)
  283. entry["highLevelChance"][name].Float() = parser.readNumber();
  284. for(const auto & name : NSecondarySkill::names)
  285. entry["secondarySkills"][name].Float() = parser.readNumber();
  286. for(const auto & name : NFaction::names)
  287. entry["tavern"][name].Float() = parser.readNumber();
  288. parser.endLine();
  289. h3Data.push_back(entry);
  290. }
  291. return h3Data;
  292. }
  293. void CHeroClassHandler::afterLoadFinalization()
  294. {
  295. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  296. for(CHeroClass * heroClass : objects)
  297. {
  298. for(CFaction * faction : VLC->townh->objects)
  299. {
  300. if (!faction->town)
  301. continue;
  302. if (heroClass->selectionProbability.count(faction->getId()))
  303. continue;
  304. auto chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  305. heroClass->selectionProbability[faction->getId()] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  306. }
  307. // set default probabilities for gaining secondary skills where not loaded previously
  308. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  309. {
  310. if(heroClass->secSkillProbability.count(skillID) == 0)
  311. {
  312. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  313. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->getJsonKey());
  314. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  315. }
  316. }
  317. }
  318. for(CHeroClass * hc : objects)
  319. {
  320. if (!hc->imageMapMale.empty())
  321. {
  322. JsonNode templ;
  323. templ["animation"].String() = hc->imageMapMale;
  324. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  325. }
  326. }
  327. }
  328. CHeroClassHandler::~CHeroClassHandler() = default;
  329. CHeroHandler::~CHeroHandler() = default;
  330. CHeroHandler::CHeroHandler()
  331. {
  332. loadExperience();
  333. }
  334. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  335. {
  336. static const std::vector<std::string> typeNames = { "hero" };
  337. return typeNames;
  338. }
  339. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  340. {
  341. assert(identifier.find(':') == std::string::npos);
  342. assert(!scope.empty());
  343. auto * hero = new CHero();
  344. hero->ID = HeroTypeID(index);
  345. hero->identifier = identifier;
  346. hero->modScope = scope;
  347. hero->gender = node["female"].Bool() ? EHeroGender::FEMALE : EHeroGender::MALE;
  348. hero->special = node["special"].Bool();
  349. //Default - both false
  350. hero->onlyOnWaterMap = node["onlyOnWaterMap"].Bool();
  351. hero->onlyOnMapWithoutWater = node["onlyOnMapWithoutWater"].Bool();
  352. VLC->generaltexth->registerString(scope, hero->getNameTextID(), node["texts"]["name"].String());
  353. VLC->generaltexth->registerString(scope, hero->getBiographyTextID(), node["texts"]["biography"].String());
  354. VLC->generaltexth->registerString(scope, hero->getSpecialtyNameTextID(), node["texts"]["specialty"]["name"].String());
  355. VLC->generaltexth->registerString(scope, hero->getSpecialtyTooltipTextID(), node["texts"]["specialty"]["tooltip"].String());
  356. VLC->generaltexth->registerString(scope, hero->getSpecialtyDescriptionTextID(), node["texts"]["specialty"]["description"].String());
  357. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  358. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  359. hero->portraitSmall = node["images"]["small"].String();
  360. hero->portraitLarge = node["images"]["large"].String();
  361. hero->battleImage = AnimationPath::fromJson(node["battleImage"]);
  362. loadHeroArmy(hero, node);
  363. loadHeroSkills(hero, node);
  364. loadHeroSpecialty(hero, node);
  365. VLC->identifiers()->requestIdentifier("heroClass", node["class"],
  366. [=](si32 classID)
  367. {
  368. hero->heroClass = classes[HeroClassID(classID)];
  369. });
  370. return hero;
  371. }
  372. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node) const
  373. {
  374. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  375. hero->initialArmy.resize(node["army"].Vector().size());
  376. for (size_t i=0; i< hero->initialArmy.size(); i++)
  377. {
  378. const JsonNode & source = node["army"].Vector()[i];
  379. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  380. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  381. if (hero->initialArmy[i].minAmount > hero->initialArmy[i].maxAmount)
  382. {
  383. logMod->error("Hero %s has minimal army size (%d) greater than maximal size (%d)!", hero->getJsonKey(), hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  384. std::swap(hero->initialArmy[i].minAmount, hero->initialArmy[i].maxAmount);
  385. }
  386. VLC->identifiers()->requestIdentifier("creature", source["creature"], [=](si32 creature)
  387. {
  388. hero->initialArmy[i].creature = CreatureID(creature);
  389. });
  390. }
  391. }
  392. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node) const
  393. {
  394. for(const JsonNode &set : node["skills"].Vector())
  395. {
  396. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  397. if (skillLevel < MasteryLevel::LEVELS_SIZE)
  398. {
  399. size_t currentIndex = hero->secSkillsInit.size();
  400. hero->secSkillsInit.emplace_back(SecondarySkill(-1), skillLevel);
  401. VLC->identifiers()->requestIdentifier("skill", set["skill"], [=](si32 id)
  402. {
  403. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  404. });
  405. }
  406. else
  407. {
  408. logMod->error("Unknown skill level: %s", set["level"].String());
  409. }
  410. }
  411. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  412. hero->haveSpellBook = !node["spellbook"].isNull();
  413. for(const JsonNode & spell : node["spellbook"].Vector())
  414. {
  415. VLC->identifiers()->requestIdentifier("spell", spell,
  416. [=](si32 spellID)
  417. {
  418. hero->spells.insert(SpellID(spellID));
  419. });
  420. }
  421. }
  422. /// creates standard H3 hero specialty for creatures
  423. static std::vector<std::shared_ptr<Bonus>> createCreatureSpecialty(CreatureID baseCreatureID)
  424. {
  425. std::vector<std::shared_ptr<Bonus>> result;
  426. std::set<CreatureID> targets;
  427. targets.insert(baseCreatureID);
  428. // go through entire upgrade chain and collect all creatures to which baseCreatureID can be upgraded
  429. for (;;)
  430. {
  431. std::set<CreatureID> oldTargets = targets;
  432. for (auto const & upgradeSourceID : oldTargets)
  433. {
  434. const CCreature * upgradeSource = upgradeSourceID.toCreature();
  435. targets.insert(upgradeSource->upgrades.begin(), upgradeSource->upgrades.end());
  436. }
  437. if (oldTargets.size() == targets.size())
  438. break;
  439. }
  440. for(CreatureID cid : targets)
  441. {
  442. auto const & specCreature = *cid.toCreature();
  443. int stepSize = specCreature.getLevel() ? specCreature.getLevel() : 5;
  444. {
  445. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  446. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  447. bonus->type = BonusType::STACKS_SPEED;
  448. bonus->val = 1;
  449. result.push_back(bonus);
  450. }
  451. {
  452. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  453. bonus->type = BonusType::PRIMARY_SKILL;
  454. bonus->subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  455. bonus->val = 0;
  456. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  457. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  458. result.push_back(bonus);
  459. }
  460. {
  461. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  462. bonus->type = BonusType::PRIMARY_SKILL;
  463. bonus->subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  464. bonus->val = 0;
  465. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  466. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  467. result.push_back(bonus);
  468. }
  469. }
  470. return result;
  471. }
  472. void CHeroHandler::beforeValidate(JsonNode & object)
  473. {
  474. //handle "base" specialty info
  475. JsonNode & specialtyNode = object["specialty"];
  476. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  477. {
  478. const JsonNode & base = specialtyNode["base"];
  479. if(!base.isNull())
  480. {
  481. if(specialtyNode["bonuses"].isNull())
  482. {
  483. logMod->warn("specialty has base without bonuses");
  484. }
  485. else
  486. {
  487. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  488. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  489. JsonUtils::inherit(bonuses[keyValue.first], base);
  490. }
  491. }
  492. }
  493. }
  494. void CHeroHandler::afterLoadFinalization()
  495. {
  496. for (auto const & functor : callAfterLoadFinalization)
  497. functor();
  498. callAfterLoadFinalization.clear();
  499. }
  500. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  501. {
  502. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  503. {
  504. bonus->duration = BonusDuration::PERMANENT;
  505. bonus->source = BonusSource::HERO_SPECIAL;
  506. bonus->sid = BonusSourceID(hero->getId());
  507. return bonus;
  508. };
  509. //new format, using bonus system
  510. const JsonNode & specialtyNode = node["specialty"];
  511. if(specialtyNode.getType() != JsonNode::JsonType::DATA_STRUCT)
  512. {
  513. logMod->error("Unsupported speciality format for hero %s!", hero->getNameTranslated());
  514. return;
  515. }
  516. //creature specialty - alias for simplicity
  517. if(!specialtyNode["creature"].isNull())
  518. {
  519. JsonNode creatureNode = specialtyNode["creature"];
  520. std::function<void()> specialtyLoader = [creatureNode, hero, prepSpec]
  521. {
  522. VLC->identifiers()->requestIdentifier("creature", creatureNode, [hero, prepSpec](si32 creature)
  523. {
  524. for (const auto & bonus : createCreatureSpecialty(CreatureID(creature)))
  525. hero->specialty.push_back(prepSpec(bonus));
  526. });
  527. };
  528. callAfterLoadFinalization.push_back(specialtyLoader);
  529. }
  530. for(const auto & keyValue : specialtyNode["bonuses"].Struct())
  531. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  532. }
  533. void CHeroHandler::loadExperience()
  534. {
  535. expPerLevel.push_back(0);
  536. expPerLevel.push_back(1000);
  537. expPerLevel.push_back(2000);
  538. expPerLevel.push_back(3200);
  539. expPerLevel.push_back(4600);
  540. expPerLevel.push_back(6200);
  541. expPerLevel.push_back(8000);
  542. expPerLevel.push_back(10000);
  543. expPerLevel.push_back(12200);
  544. expPerLevel.push_back(14700);
  545. expPerLevel.push_back(17500);
  546. expPerLevel.push_back(20600);
  547. expPerLevel.push_back(24320);
  548. expPerLevel.push_back(28784);
  549. expPerLevel.push_back(34140);
  550. for (;;)
  551. {
  552. auto i = expPerLevel.size() - 1;
  553. auto currExp = expPerLevel[i];
  554. auto prevExp = expPerLevel[i-1];
  555. auto prevDiff = currExp - prevExp;
  556. auto nextDiff = prevDiff + prevDiff / 5;
  557. auto maxExp = std::numeric_limits<decltype(currExp)>::max();
  558. if (currExp > maxExp - nextDiff)
  559. break; // overflow point reached
  560. expPerLevel.push_back (currExp + nextDiff);
  561. }
  562. }
  563. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  564. static std::string genRefName(std::string input)
  565. {
  566. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  567. input[0] = std::tolower(input[0]); // to camelCase
  568. return input;
  569. }
  570. std::vector<JsonNode> CHeroHandler::loadLegacyData()
  571. {
  572. size_t dataSize = VLC->settings()->getInteger(EGameSettings::TEXTS_HERO);
  573. objects.resize(dataSize);
  574. std::vector<JsonNode> h3Data;
  575. h3Data.reserve(dataSize);
  576. CLegacyConfigParser specParser(TextPath::builtin("DATA/HEROSPEC.TXT"));
  577. CLegacyConfigParser bioParser(TextPath::builtin("DATA/HEROBIOS.TXT"));
  578. CLegacyConfigParser parser(TextPath::builtin("DATA/HOTRAITS.TXT"));
  579. parser.endLine(); //ignore header
  580. parser.endLine();
  581. specParser.endLine(); //ignore header
  582. specParser.endLine();
  583. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  584. {
  585. JsonNode heroData;
  586. heroData["texts"]["name"].String() = parser.readString();
  587. heroData["texts"]["biography"].String() = bioParser.readString();
  588. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  589. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  590. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  591. for(int x=0;x<3;x++)
  592. {
  593. JsonNode armySlot;
  594. armySlot["min"].Float() = parser.readNumber();
  595. armySlot["max"].Float() = parser.readNumber();
  596. armySlot["creature"].String() = genRefName(parser.readString());
  597. heroData["army"].Vector().push_back(armySlot);
  598. }
  599. parser.endLine();
  600. specParser.endLine();
  601. bioParser.endLine();
  602. h3Data.push_back(heroData);
  603. }
  604. return h3Data;
  605. }
  606. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  607. {
  608. size_t index = objects.size();
  609. static const int specialFramesCount = 2; // reserved for 2 special frames
  610. auto * object = loadFromJson(scope, data, name, index);
  611. object->imageIndex = static_cast<si32>(index) + specialFramesCount;
  612. objects.emplace_back(object);
  613. registerObject(scope, "hero", name, object->getIndex());
  614. }
  615. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  616. {
  617. auto * object = loadFromJson(scope, data, name, index);
  618. object->imageIndex = static_cast<si32>(index);
  619. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  620. objects[index] = object;
  621. registerObject(scope, "hero", name, object->getIndex());
  622. }
  623. ui32 CHeroHandler::level (TExpType experience) const
  624. {
  625. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  626. }
  627. TExpType CHeroHandler::reqExp (ui32 level) const
  628. {
  629. if(!level)
  630. return 0;
  631. if (level <= expPerLevel.size())
  632. {
  633. return expPerLevel[level-1];
  634. }
  635. else
  636. {
  637. logGlobal->warn("A hero has reached unsupported amount of experience");
  638. return expPerLevel[expPerLevel.size()-1];
  639. }
  640. }
  641. ui32 CHeroHandler::maxSupportedLevel() const
  642. {
  643. return expPerLevel.size();
  644. }
  645. std::set<HeroTypeID> CHeroHandler::getDefaultAllowed() const
  646. {
  647. std::set<HeroTypeID> result;
  648. for(const CHero * hero : objects)
  649. if (hero && !hero->special)
  650. result.insert(hero->getId());
  651. return result;
  652. }
  653. VCMI_LIB_NAMESPACE_END