CHeroHandler.cpp 32 KB

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