CHeroHandler.cpp 24 KB

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