CHeroHandler.cpp 33 KB

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