CHeroHandler.cpp 30 KB

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