CHeroHandler.cpp 30 KB

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