CHeroHandler.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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 "StringConstants.h"
  17. #include "battle/BattleHex.h"
  18. #include "CCreatureHandler.h"
  19. #include "CModHandler.h"
  20. #include "CTownHandler.h"
  21. #include "mapObjects/CObjectHandler.h" //for hero specialty
  22. #include "CSkillHandler.h"
  23. #include <math.h>
  24. #include "mapObjects/CObjectClassesHandler.h"
  25. #include "BattleFieldHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. CHero::CHero() = default;
  28. CHero::~CHero() = default;
  29. int32_t CHero::getIndex() const
  30. {
  31. return ID.getNum();
  32. }
  33. int32_t CHero::getIconIndex() const
  34. {
  35. return imageIndex;
  36. }
  37. const std::string & CHero::getName() const
  38. {
  39. return name;
  40. }
  41. const std::string & CHero::getJsonKey() const
  42. {
  43. return identifier;
  44. }
  45. HeroTypeID CHero::getId() const
  46. {
  47. return ID;
  48. }
  49. void CHero::registerIcons(const IconRegistar & cb) const
  50. {
  51. cb(getIconIndex(), 0, "UN32", iconSpecSmall);
  52. cb(getIconIndex(), 0, "UN44", iconSpecLarge);
  53. cb(getIconIndex(), 0, "PORTRAITSLARGE", portraitLarge);
  54. cb(getIconIndex(), 0, "PORTRAITSSMALL", portraitSmall);
  55. }
  56. void CHero::updateFrom(const JsonNode & data)
  57. {
  58. //todo: CHero::updateFrom
  59. }
  60. void CHero::serializeJson(JsonSerializeFormat & handler)
  61. {
  62. }
  63. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  64. {
  65. int totalProb = 0;
  66. for(auto & possible : possibles)
  67. {
  68. totalProb += secSkillProbability[possible];
  69. }
  70. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  71. {
  72. auto ran = rand.nextInt(totalProb - 1);
  73. for(auto & possible : possibles)
  74. {
  75. ran -= secSkillProbability[possible];
  76. if(ran < 0)
  77. {
  78. return possible;
  79. }
  80. }
  81. }
  82. // FIXME: select randomly? How H3 handles such rare situation?
  83. return *possibles.begin();
  84. }
  85. bool CHeroClass::isMagicHero() const
  86. {
  87. return affinity == MAGIC;
  88. }
  89. EAlignment::EAlignment CHeroClass::getAlignment() const
  90. {
  91. return EAlignment::EAlignment((*VLC->townh)[faction]->alignment);
  92. }
  93. int32_t CHeroClass::getIndex() const
  94. {
  95. return id.getNum();
  96. }
  97. int32_t CHeroClass::getIconIndex() const
  98. {
  99. return getIndex();
  100. }
  101. const std::string & CHeroClass::getName() const
  102. {
  103. return name;
  104. }
  105. const std::string & CHeroClass::getJsonKey() const
  106. {
  107. return identifier;
  108. }
  109. HeroClassID CHeroClass::getId() const
  110. {
  111. return id;
  112. }
  113. void CHeroClass::registerIcons(const IconRegistar & cb) const
  114. {
  115. }
  116. void CHeroClass::updateFrom(const JsonNode & data)
  117. {
  118. //TODO: CHeroClass::updateFrom
  119. }
  120. void CHeroClass::serializeJson(JsonSerializeFormat & handler)
  121. {
  122. }
  123. CHeroClass::CHeroClass()
  124. : faction(0), id(), affinity(0), defaultTavernChance(0), commander(nullptr)
  125. {
  126. }
  127. void CHeroClassHandler::fillPrimarySkillData(const JsonNode & node, CHeroClass * heroClass, PrimarySkill::PrimarySkill pSkill)
  128. {
  129. const auto & skillName = PrimarySkill::names[pSkill];
  130. auto currentPrimarySkillValue = (int)node["primarySkills"][skillName].Integer();
  131. //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  132. auto primarySkillLegalMinimum = (pSkill == PrimarySkill::ATTACK || pSkill == PrimarySkill::DEFENSE) ? 0 : 1;
  133. if(currentPrimarySkillValue < primarySkillLegalMinimum)
  134. {
  135. logMod->error("Hero class '%s' has incorrect initial value '%d' for skill '%s'. Value '%d' will be used instead.",
  136. heroClass->identifier, currentPrimarySkillValue, skillName, primarySkillLegalMinimum);
  137. currentPrimarySkillValue = primarySkillLegalMinimum;
  138. }
  139. heroClass->primarySkillInitial.push_back(currentPrimarySkillValue);
  140. heroClass->primarySkillLowLevel.push_back((int)node["lowLevelChance"][skillName].Float());
  141. heroClass->primarySkillHighLevel.push_back((int)node["highLevelChance"][skillName].Float());
  142. }
  143. const std::vector<std::string> & CHeroClassHandler::getTypeNames() const
  144. {
  145. static const std::vector<std::string> typeNames = { "heroClass" };
  146. return typeNames;
  147. }
  148. CHeroClass * CHeroClassHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  149. {
  150. std::string affinityStr[2] = { "might", "magic" };
  151. auto heroClass = new CHeroClass();
  152. heroClass->id = HeroClassID(index);
  153. heroClass->identifier = identifier;
  154. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  155. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  156. //MODS COMPATIBILITY FOR 0.96
  157. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  158. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  159. heroClass->name = node["name"].String();
  160. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  161. fillPrimarySkillData(node, heroClass, PrimarySkill::ATTACK);
  162. fillPrimarySkillData(node, heroClass, PrimarySkill::DEFENSE);
  163. fillPrimarySkillData(node, heroClass, PrimarySkill::SPELL_POWER);
  164. fillPrimarySkillData(node, heroClass, PrimarySkill::KNOWLEDGE);
  165. auto percentSumm = std::accumulate(heroClass->primarySkillLowLevel.begin(), heroClass->primarySkillLowLevel.end(), 0);
  166. if(percentSumm != 100)
  167. logMod->error("Hero class %s has wrong lowLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  168. percentSumm = std::accumulate(heroClass->primarySkillHighLevel.begin(), heroClass->primarySkillHighLevel.end(), 0);
  169. if(percentSumm != 100)
  170. logMod->error("Hero class %s has wrong highLevelChance values: summ should be 100, but %d instead", heroClass->identifier, percentSumm);
  171. for(auto skillPair : node["secondarySkills"].Struct())
  172. {
  173. int probability = static_cast<int>(skillPair.second.Integer());
  174. VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
  175. {
  176. if(heroClass->secSkillProbability.size() <= skillID)
  177. heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
  178. heroClass->secSkillProbability[skillID] = probability;
  179. });
  180. }
  181. VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
  182. [=](si32 commanderID)
  183. {
  184. heroClass->commander = VLC->creh->objects[commanderID];
  185. });
  186. heroClass->defaultTavernChance = static_cast<ui32>(node["defaultTavern"].Float());
  187. for(auto & tavern : node["tavern"].Struct())
  188. {
  189. int value = static_cast<int>(tavern.second.Float());
  190. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  191. [=](si32 factionID)
  192. {
  193. heroClass->selectionProbability[factionID] = value;
  194. });
  195. }
  196. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  197. [=](si32 factionID)
  198. {
  199. heroClass->faction = factionID;
  200. });
  201. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  202. {
  203. JsonNode classConf = node["mapObject"];
  204. classConf["heroClass"].String() = identifier;
  205. classConf.setMeta(scope);
  206. VLC->objtypeh->loadSubObject(identifier, classConf, index, heroClass->getIndex());
  207. });
  208. return heroClass;
  209. }
  210. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  211. {
  212. objects.resize(dataSize);
  213. std::vector<JsonNode> h3Data;
  214. h3Data.reserve(dataSize);
  215. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  216. parser.endLine(); // header
  217. parser.endLine();
  218. for (size_t i=0; i<dataSize; i++)
  219. {
  220. JsonNode entry;
  221. entry["name"].String() = parser.readString();
  222. parser.readNumber(); // unused aggression
  223. for (auto & name : PrimarySkill::names)
  224. entry["primarySkills"][name].Float() = parser.readNumber();
  225. for (auto & name : PrimarySkill::names)
  226. entry["lowLevelChance"][name].Float() = parser.readNumber();
  227. for (auto & name : PrimarySkill::names)
  228. entry["highLevelChance"][name].Float() = parser.readNumber();
  229. for (auto & name : NSecondarySkill::names)
  230. entry["secondarySkills"][name].Float() = parser.readNumber();
  231. for(auto & name : ETownType::names)
  232. entry["tavern"][name].Float() = parser.readNumber();
  233. parser.endLine();
  234. h3Data.push_back(entry);
  235. }
  236. return h3Data;
  237. }
  238. void CHeroClassHandler::afterLoadFinalization()
  239. {
  240. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  241. for(CHeroClass * heroClass : objects)
  242. {
  243. for(CFaction * faction : VLC->townh->objects)
  244. {
  245. if (!faction->town)
  246. continue;
  247. if (heroClass->selectionProbability.count(faction->index))
  248. continue;
  249. float chance = static_cast<float>(heroClass->defaultTavernChance * faction->town->defaultTavernChance);
  250. heroClass->selectionProbability[faction->index] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  251. }
  252. // set default probabilities for gaining secondary skills where not loaded previously
  253. heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
  254. for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
  255. {
  256. if(heroClass->secSkillProbability[skillID] < 0)
  257. {
  258. const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
  259. logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->identifier);
  260. heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
  261. }
  262. }
  263. }
  264. for(CHeroClass * hc : objects)
  265. {
  266. if (!hc->imageMapMale.empty())
  267. {
  268. JsonNode templ;
  269. templ["animation"].String() = hc->imageMapMale;
  270. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->getIndex())->addTemplate(templ);
  271. }
  272. }
  273. }
  274. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  275. {
  276. return std::vector<bool>(size(), true);
  277. }
  278. CHeroClassHandler::~CHeroClassHandler() = default;
  279. CHeroHandler::~CHeroHandler() = default;
  280. CHeroHandler::CHeroHandler()
  281. {
  282. loadBallistics();
  283. loadExperience();
  284. }
  285. const std::vector<std::string> & CHeroHandler::getTypeNames() const
  286. {
  287. static const std::vector<std::string> typeNames = { "hero" };
  288. return typeNames;
  289. }
  290. CHero * CHeroHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  291. {
  292. auto hero = new CHero();
  293. hero->ID = HeroTypeID(index);
  294. hero->identifier = identifier;
  295. hero->sex = node["female"].Bool();
  296. hero->special = node["special"].Bool();
  297. hero->name = node["texts"]["name"].String();
  298. hero->biography = node["texts"]["biography"].String();
  299. hero->specName = node["texts"]["specialty"]["name"].String();
  300. hero->specTooltip = node["texts"]["specialty"]["tooltip"].String();
  301. hero->specDescr = node["texts"]["specialty"]["description"].String();
  302. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  303. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  304. hero->portraitSmall = node["images"]["small"].String();
  305. hero->portraitLarge = node["images"]["large"].String();
  306. hero->battleImage = node["battleImage"].String();
  307. loadHeroArmy(hero, node);
  308. loadHeroSkills(hero, node);
  309. loadHeroSpecialty(hero, node);
  310. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  311. [=](si32 classID)
  312. {
  313. hero->heroClass = classes[HeroClassID(classID)];
  314. });
  315. return hero;
  316. }
  317. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  318. {
  319. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  320. hero->initialArmy.resize(node["army"].Vector().size());
  321. for (size_t i=0; i< hero->initialArmy.size(); i++)
  322. {
  323. const JsonNode & source = node["army"].Vector()[i];
  324. hero->initialArmy[i].minAmount = static_cast<ui32>(source["min"].Float());
  325. hero->initialArmy[i].maxAmount = static_cast<ui32>(source["max"].Float());
  326. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  327. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  328. {
  329. hero->initialArmy[i].creature = CreatureID(creature);
  330. });
  331. }
  332. }
  333. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  334. {
  335. for(const JsonNode &set : node["skills"].Vector())
  336. {
  337. int skillLevel = static_cast<int>(boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels));
  338. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  339. {
  340. size_t currentIndex = hero->secSkillsInit.size();
  341. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  342. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  343. {
  344. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  345. });
  346. }
  347. else
  348. {
  349. logMod->error("Unknown skill level: %s", set["level"].String());
  350. }
  351. }
  352. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  353. hero->haveSpellBook = !node["spellbook"].isNull();
  354. for(const JsonNode & spell : node["spellbook"].Vector())
  355. {
  356. VLC->modh->identifiers.requestIdentifier("spell", spell,
  357. [=](si32 spellID)
  358. {
  359. hero->spells.insert(SpellID(spellID));
  360. });
  361. }
  362. }
  363. // add standard creature specialty to result
  364. void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
  365. {
  366. const CCreature &specBaseCreature = *VLC->creh->objects[creatureID]; //base creature in which we have specialty
  367. bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
  368. bonus->type = Bonus::STACKS_SPEED;
  369. bonus->valType = Bonus::ADDITIVE_VALUE;
  370. bonus->val = 1;
  371. result.push_back(bonus);
  372. // attack and defense may differ for upgraded creatures => separate bonuses
  373. std::vector<int> specTargets;
  374. specTargets.push_back(creatureID);
  375. specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());
  376. for(int cid : specTargets)
  377. {
  378. const CCreature &specCreature = *VLC->creh->objects[cid];
  379. bonus = std::make_shared<Bonus>(*bonus);
  380. bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
  381. bonus->type = Bonus::PRIMARY_SKILL;
  382. bonus->val = 0;
  383. int stepSize = specCreature.level ? specCreature.level : 5;
  384. bonus->subtype = PrimarySkill::ATTACK;
  385. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
  386. result.push_back(bonus);
  387. bonus = std::make_shared<Bonus>(*bonus);
  388. bonus->subtype = PrimarySkill::DEFENSE;
  389. bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefense(false), stepSize));
  390. result.push_back(bonus);
  391. }
  392. }
  393. // convert deprecated format
  394. std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
  395. {
  396. std::vector<std::shared_ptr<Bonus>> result;
  397. std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
  398. bonus->duration = Bonus::PERMANENT;
  399. bonus->source = Bonus::HERO_SPECIAL;
  400. bonus->sid = sid;
  401. bonus->val = spec.val;
  402. switch (spec.type)
  403. {
  404. case 1: //creature specialty
  405. AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
  406. break;
  407. case 2: //secondary skill
  408. bonus->type = Bonus::SECONDARY_SKILL_PREMY;
  409. bonus->valType = Bonus::PERCENT_TO_BASE;
  410. bonus->subtype = spec.subtype;
  411. bonus->updater.reset(new TimesHeroLevelUpdater());
  412. result.push_back(bonus);
  413. break;
  414. case 3: //spell damage bonus, level dependent but calculated elsewhere
  415. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  416. bonus->subtype = spec.subtype;
  417. bonus->updater.reset(new TimesHeroLevelUpdater());
  418. result.push_back(bonus);
  419. break;
  420. case 4: //creature stat boost
  421. switch (spec.subtype)
  422. {
  423. case 1:
  424. bonus->type = Bonus::PRIMARY_SKILL;
  425. bonus->subtype = PrimarySkill::ATTACK;
  426. break;
  427. case 2:
  428. bonus->type = Bonus::PRIMARY_SKILL;
  429. bonus->subtype = PrimarySkill::DEFENSE;
  430. break;
  431. case 3:
  432. bonus->type = Bonus::CREATURE_DAMAGE;
  433. bonus->subtype = 0; //both min and max
  434. break;
  435. case 4:
  436. bonus->type = Bonus::STACK_HEALTH;
  437. break;
  438. case 5:
  439. bonus->type = Bonus::STACKS_SPEED;
  440. break;
  441. default:
  442. logMod->warn("Unknown subtype for specialty 4");
  443. return result;
  444. }
  445. bonus->valType = Bonus::ADDITIVE_VALUE;
  446. bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->objects[spec.additionalinfo], true));
  447. result.push_back(bonus);
  448. break;
  449. case 5: //spell damage bonus in percent
  450. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  451. bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
  452. bonus->subtype = spec.subtype; //spell id
  453. result.push_back(bonus);
  454. break;
  455. case 6: //damage bonus for bless (Adela)
  456. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  457. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  458. bonus->additionalInfo = spec.additionalinfo; //damage factor
  459. bonus->updater.reset(new TimesHeroLevelUpdater());
  460. result.push_back(bonus);
  461. break;
  462. case 7: //maxed mastery for spell
  463. bonus->type = Bonus::MAXED_SPELL;
  464. bonus->subtype = spec.subtype; //spell id
  465. result.push_back(bonus);
  466. break;
  467. case 8: //peculiar spells - enchantments
  468. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  469. bonus->subtype = spec.subtype; //spell id
  470. bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
  471. result.push_back(bonus);
  472. break;
  473. case 9: //upgrade creatures
  474. {
  475. const auto &creatures = VLC->creh->objects;
  476. bonus->type = Bonus::SPECIAL_UPGRADE;
  477. bonus->subtype = spec.subtype; //base id
  478. bonus->additionalInfo = spec.additionalinfo; //target id
  479. result.push_back(bonus);
  480. //propagate for regular upgrades of base creature
  481. for(auto cre_id : creatures[spec.subtype]->upgrades)
  482. {
  483. std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
  484. upgradeUpgradedVersion->subtype = cre_id;
  485. result.push_back(upgradeUpgradedVersion);
  486. }
  487. }
  488. break;
  489. case 10: //resource generation
  490. bonus->type = Bonus::GENERATE_RESOURCE;
  491. bonus->subtype = spec.subtype;
  492. result.push_back(bonus);
  493. break;
  494. case 11: //starting skill with mastery (Adrienne)
  495. logMod->warn("Secondary skill mastery is no longer supported as specialty.");
  496. break;
  497. case 12: //army speed
  498. bonus->type = Bonus::STACKS_SPEED;
  499. result.push_back(bonus);
  500. break;
  501. case 13: //Dragon bonuses (Mutare)
  502. bonus->type = Bonus::PRIMARY_SKILL;
  503. bonus->valType = Bonus::ADDITIVE_VALUE;
  504. switch(spec.subtype)
  505. {
  506. case 1:
  507. bonus->subtype = PrimarySkill::ATTACK;
  508. break;
  509. case 2:
  510. bonus->subtype = PrimarySkill::DEFENSE;
  511. break;
  512. }
  513. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  514. result.push_back(bonus);
  515. break;
  516. default:
  517. logMod->warn("Unknown hero specialty %d", spec.type);
  518. break;
  519. }
  520. return result;
  521. }
  522. // convert deprecated format
  523. std::vector<std::shared_ptr<Bonus>> SpecialtyBonusToBonuses(const SSpecialtyBonus & spec, int sid)
  524. {
  525. std::vector<std::shared_ptr<Bonus>> result;
  526. for(std::shared_ptr<Bonus> oldBonus : spec.bonuses)
  527. {
  528. oldBonus->sid = sid;
  529. if(oldBonus->type == Bonus::SPECIAL_SPELL_LEV || oldBonus->type == Bonus::SPECIAL_BLESS_DAMAGE)
  530. {
  531. // these bonuses used to auto-scale with hero level
  532. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  533. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  534. result.push_back(newBonus);
  535. }
  536. else if(spec.growsWithLevel)
  537. {
  538. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
  539. switch(newBonus->type)
  540. {
  541. case Bonus::SECONDARY_SKILL_PREMY:
  542. break; // ignore - used to be overwritten based on SPECIAL_SECONDARY_SKILL
  543. case Bonus::SPECIAL_SECONDARY_SKILL:
  544. newBonus->type = Bonus::SECONDARY_SKILL_PREMY;
  545. newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
  546. result.push_back(newBonus);
  547. break;
  548. case Bonus::PRIMARY_SKILL:
  549. if((newBonus->subtype == PrimarySkill::ATTACK || newBonus->subtype == PrimarySkill::DEFENSE) && newBonus->limiter)
  550. {
  551. std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(newBonus->limiter);
  552. if(creatureLimiter)
  553. {
  554. const CCreature * cre = creatureLimiter->creature;
  555. int creStat = newBonus->subtype == PrimarySkill::ATTACK ? cre->getAttack(false) : cre->getDefense(false);
  556. int creLevel = cre->level ? cre->level : 5;
  557. newBonus->updater = std::make_shared<GrowsWithLevelUpdater>(creStat, creLevel);
  558. }
  559. result.push_back(newBonus);
  560. }
  561. break;
  562. default:
  563. result.push_back(newBonus);
  564. }
  565. }
  566. else
  567. {
  568. result.push_back(oldBonus);
  569. }
  570. }
  571. return result;
  572. }
  573. void CHeroHandler::beforeValidate(JsonNode & object)
  574. {
  575. //handle "base" specialty info
  576. JsonNode & specialtyNode = object["specialty"];
  577. if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  578. {
  579. const JsonNode & base = specialtyNode["base"];
  580. if(!base.isNull())
  581. {
  582. if(specialtyNode["bonuses"].isNull())
  583. {
  584. logMod->warn("specialty has base without bonuses");
  585. }
  586. else
  587. {
  588. JsonMap & bonuses = specialtyNode["bonuses"].Struct();
  589. for(std::pair<std::string, JsonNode> keyValue : bonuses)
  590. JsonUtils::inherit(bonuses[keyValue.first], base);
  591. }
  592. }
  593. }
  594. }
  595. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  596. {
  597. int sid = hero->ID.getNum();
  598. auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
  599. {
  600. bonus->duration = Bonus::PERMANENT;
  601. bonus->source = Bonus::HERO_SPECIAL;
  602. bonus->sid = sid;
  603. return bonus;
  604. };
  605. //deprecated, used only for original specialties
  606. const JsonNode & specialtiesNode = node["specialties"];
  607. if (!specialtiesNode.isNull())
  608. {
  609. logMod->warn("Hero %s has deprecated specialties format.", hero->identifier);
  610. for(const JsonNode &specialty : specialtiesNode.Vector())
  611. {
  612. SSpecialtyInfo spec;
  613. spec.type = static_cast<si32>(specialty["type"].Integer());
  614. spec.val = static_cast<si32>(specialty["val"].Integer());
  615. spec.subtype = static_cast<si32>(specialty["subtype"].Integer());
  616. spec.additionalinfo = static_cast<si32>(specialty["info"].Integer());
  617. //we convert after loading completes, to have all identifiers for json logging
  618. hero->specDeprecated.push_back(spec);
  619. }
  620. }
  621. //new(er) format, using bonus system
  622. const JsonNode & specialtyNode = node["specialty"];
  623. if(specialtyNode.getType() == JsonNode::JsonType::DATA_VECTOR)
  624. {
  625. //deprecated middle-aged format
  626. for(const JsonNode & specialty : node["specialty"].Vector())
  627. {
  628. SSpecialtyBonus hs;
  629. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  630. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  631. hs.bonuses.push_back(prepSpec(JsonUtils::parseBonus(bonus)));
  632. hero->specialtyDeprecated.push_back(hs);
  633. }
  634. }
  635. else if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
  636. {
  637. //creature specialty - alias for simplicity
  638. if(!specialtyNode["creature"].isNull())
  639. {
  640. VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
  641. // use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
  642. SSpecialtyInfo spec;
  643. spec.type = 1;
  644. spec.additionalinfo = creature;
  645. hero->specDeprecated.push_back(spec);
  646. });
  647. }
  648. if(!specialtyNode["bonuses"].isNull())
  649. {
  650. //proper new format
  651. for(auto keyValue : specialtyNode["bonuses"].Struct())
  652. hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
  653. }
  654. }
  655. }
  656. void CHeroHandler::loadExperience()
  657. {
  658. expPerLevel.push_back(0);
  659. expPerLevel.push_back(1000);
  660. expPerLevel.push_back(2000);
  661. expPerLevel.push_back(3200);
  662. expPerLevel.push_back(4600);
  663. expPerLevel.push_back(6200);
  664. expPerLevel.push_back(8000);
  665. expPerLevel.push_back(10000);
  666. expPerLevel.push_back(12200);
  667. expPerLevel.push_back(14700);
  668. expPerLevel.push_back(17500);
  669. expPerLevel.push_back(20600);
  670. expPerLevel.push_back(24320);
  671. expPerLevel.push_back(28784);
  672. expPerLevel.push_back(34140);
  673. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  674. {
  675. auto i = expPerLevel.size() - 1;
  676. auto diff = expPerLevel[i] - expPerLevel[i-1];
  677. diff += diff / 5;
  678. expPerLevel.push_back (expPerLevel[i] + diff);
  679. }
  680. expPerLevel.pop_back();//last value is broken
  681. }
  682. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  683. static std::string genRefName(std::string input)
  684. {
  685. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  686. input[0] = std::tolower(input[0]); // to camelCase
  687. return input;
  688. }
  689. void CHeroHandler::loadBallistics()
  690. {
  691. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  692. ballParser.endLine(); //header
  693. ballParser.endLine();
  694. do
  695. {
  696. ballParser.readString();
  697. ballParser.readString();
  698. CHeroHandler::SBallisticsLevelInfo bli;
  699. bli.keep = static_cast<ui8>(ballParser.readNumber());
  700. bli.tower = static_cast<ui8>(ballParser.readNumber());
  701. bli.gate = static_cast<ui8>(ballParser.readNumber());
  702. bli.wall = static_cast<ui8>(ballParser.readNumber());
  703. bli.shots = static_cast<ui8>(ballParser.readNumber());
  704. bli.noDmg = static_cast<ui8>(ballParser.readNumber());
  705. bli.oneDmg = static_cast<ui8>(ballParser.readNumber());
  706. bli.twoDmg = static_cast<ui8>(ballParser.readNumber());
  707. bli.sum = static_cast<ui8>(ballParser.readNumber());
  708. ballistics.push_back(bli);
  709. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  710. }
  711. while (ballParser.endLine());
  712. }
  713. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  714. {
  715. objects.resize(dataSize);
  716. std::vector<JsonNode> h3Data;
  717. h3Data.reserve(dataSize);
  718. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  719. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  720. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  721. parser.endLine(); //ignore header
  722. parser.endLine();
  723. specParser.endLine(); //ignore header
  724. specParser.endLine();
  725. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  726. {
  727. JsonNode heroData;
  728. heroData["texts"]["name"].String() = parser.readString();
  729. heroData["texts"]["biography"].String() = bioParser.readString();
  730. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  731. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  732. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  733. for(int x=0;x<3;x++)
  734. {
  735. JsonNode armySlot;
  736. armySlot["min"].Float() = parser.readNumber();
  737. armySlot["max"].Float() = parser.readNumber();
  738. armySlot["creature"].String() = genRefName(parser.readString());
  739. heroData["army"].Vector().push_back(armySlot);
  740. }
  741. parser.endLine();
  742. specParser.endLine();
  743. bioParser.endLine();
  744. h3Data.push_back(heroData);
  745. }
  746. return h3Data;
  747. }
  748. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  749. {
  750. size_t index = objects.size();
  751. auto object = loadFromJson(scope, data, normalizeIdentifier(scope, CModHandler::scopeBuiltin(), name), index);
  752. object->imageIndex = (si32)index + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits
  753. objects.push_back(object);
  754. registerObject(scope, "hero", name, object->getIndex());
  755. }
  756. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  757. {
  758. auto object = loadFromJson(scope, data, normalizeIdentifier(scope, CModHandler::scopeBuiltin(), name), index);
  759. object->imageIndex = static_cast<si32>(index);
  760. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  761. objects[index] = object;
  762. registerObject(scope, "hero", name, object->getIndex());
  763. }
  764. void CHeroHandler::afterLoadFinalization()
  765. {
  766. for(auto & hero : objects)
  767. {
  768. for(auto bonus : hero->specialty)
  769. {
  770. bonus->sid = hero->getIndex();
  771. }
  772. if(hero->specDeprecated.size() > 0 || hero->specialtyDeprecated.size() > 0)
  773. {
  774. logMod->debug("Converting specialty format for hero %s(%s)", hero->identifier, FactionID::encode(hero->heroClass->faction));
  775. std::vector<std::shared_ptr<Bonus>> convertedBonuses;
  776. for(const SSpecialtyInfo & spec : hero->specDeprecated)
  777. {
  778. for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
  779. convertedBonuses.push_back(b);
  780. }
  781. for(const SSpecialtyBonus & spec : hero->specialtyDeprecated)
  782. {
  783. for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(spec, hero->ID.getNum()))
  784. convertedBonuses.push_back(b);
  785. }
  786. hero->specDeprecated.clear();
  787. hero->specialtyDeprecated.clear();
  788. // store and create json for logging
  789. std::vector<JsonNode> specVec;
  790. std::vector<std::string> specNames;
  791. for(std::shared_ptr<Bonus> bonus : convertedBonuses)
  792. {
  793. hero->specialty.push_back(bonus);
  794. specVec.push_back(bonus->toJsonNode());
  795. // find fitting & unique bonus name
  796. std::string bonusName = bonus->nameForBonus();
  797. if(vstd::contains(specNames, bonusName))
  798. {
  799. int suffix = 2;
  800. while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
  801. suffix++;
  802. bonusName += std::to_string(suffix);
  803. }
  804. specNames.push_back(bonusName);
  805. }
  806. // log new format for easy copy-and-paste
  807. JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
  808. if(specVec.size() > 1)
  809. {
  810. JsonNode base = JsonUtils::intersect(specVec);
  811. if(base.containsBaseData())
  812. {
  813. specNode["base"] = base;
  814. for(JsonNode & node : specVec)
  815. node = JsonUtils::difference(node, base);
  816. }
  817. }
  818. // add json for bonuses
  819. specNode["bonuses"].Struct();
  820. for(int i = 0; i < specVec.size(); i++)
  821. specNode["bonuses"][specNames[i]] = specVec[i];
  822. logMod->trace("\"specialty\" : %s", specNode.toJson(true));
  823. }
  824. }
  825. }
  826. ui32 CHeroHandler::level (ui64 experience) const
  827. {
  828. return static_cast<ui32>(boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel));
  829. }
  830. ui64 CHeroHandler::reqExp (ui32 level) const
  831. {
  832. if(!level)
  833. return 0;
  834. if (level <= expPerLevel.size())
  835. {
  836. return expPerLevel[level-1];
  837. }
  838. else
  839. {
  840. logGlobal->warn("A hero has reached unsupported amount of experience");
  841. return expPerLevel[expPerLevel.size()-1];
  842. }
  843. }
  844. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  845. {
  846. // Look Data/HOTRAITS.txt for reference
  847. std::vector<bool> allowedHeroes;
  848. allowedHeroes.reserve(size());
  849. for(const CHero * hero : objects)
  850. {
  851. allowedHeroes.push_back(!hero->special);
  852. }
  853. return allowedHeroes;
  854. }
  855. VCMI_LIB_NAMESPACE_END