CHeroHandler.cpp 30 KB

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