CHeroHandler.cpp 32 KB

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