CGHeroInstance.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. /*
  2. * CGHeroInstance.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 "CGHeroInstance.h"
  12. #include <vcmi/ServerCallback.h>
  13. #include <vcmi/spells/Spell.h>
  14. #include <vstd/RNG.h>
  15. #include "../callback/IGameInfoCallback.h"
  16. #include "../callback/IGameEventCallback.h"
  17. #include "../texts/CGeneralTextHandler.h"
  18. #include "../TerrainHandler.h"
  19. #include "../RoadHandler.h"
  20. #include "../IGameSettings.h"
  21. #include "../CSoundBase.h"
  22. #include "../spells/CSpellHandler.h"
  23. #include "../CSkillHandler.h"
  24. #include "../gameState/CGameState.h"
  25. #include "../gameState/UpgradeInfo.h"
  26. #include "../CCreatureHandler.h"
  27. #include "../mapping/CMap.h"
  28. #include "../StartInfo.h"
  29. #include "CGTownInstance.h"
  30. #include "../entities/artifact/ArtifactUtils.h"
  31. #include "../entities/artifact/CArtifact.h"
  32. #include "../entities/faction/CTownHandler.h"
  33. #include "../entities/hero/CHeroHandler.h"
  34. #include "../entities/hero/CHeroClass.h"
  35. #include "../battle/CBattleInfoEssentials.h"
  36. #include "../campaign/CampaignState.h"
  37. #include "../json/JsonBonus.h"
  38. #include "../pathfinder/TurnInfo.h"
  39. #include "../serializer/JsonSerializeFormat.h"
  40. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  41. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  42. #include "../mapObjects/MiscObjects.h"
  43. #include "../modding/ModScope.h"
  44. #include "../networkPacks/PacksForClient.h"
  45. #include "../networkPacks/PacksForClientBattle.h"
  46. #include "../constants/StringConstants.h"
  47. #include "../battle/Unit.h"
  48. #include "CConfigHandler.h"
  49. VCMI_LIB_NAMESPACE_BEGIN
  50. const ui32 CGHeroInstance::NO_PATROLLING = std::numeric_limits<ui32>::max();
  51. void CGHeroPlaceholder::serializeJsonOptions(JsonSerializeFormat & handler)
  52. {
  53. serializeJsonOwner(handler);
  54. bool isHeroType = heroType.has_value();
  55. handler.serializeBool("placeholderType", isHeroType, false);
  56. if(!handler.saving)
  57. {
  58. if(isHeroType)
  59. heroType = HeroTypeID::NONE;
  60. else
  61. powerRank = 0;
  62. }
  63. if(isHeroType)
  64. handler.serializeId("heroType", heroType.value(), HeroTypeID::NONE);
  65. else
  66. handler.serializeInt("powerRank", powerRank.value());
  67. }
  68. FactionID CGHeroInstance::getFactionID() const
  69. {
  70. return getHeroClass()->faction;
  71. }
  72. const IBonusBearer* CGHeroInstance::getBonusBearer() const
  73. {
  74. return this;
  75. }
  76. TerrainId CGHeroInstance::getNativeTerrain() const
  77. {
  78. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  79. // This is clearly bug in H3 however intended behaviour is not clear.
  80. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  81. // will always have best penalty without any influence from player-defined stacks order
  82. // and army that consist solely from neutral will always be considered to be on native terrain
  83. TerrainId nativeTerrain = ETerrainId::ANY_TERRAIN;
  84. for(const auto & stack : stacks)
  85. {
  86. TerrainId stackNativeTerrain = stack.second->getNativeTerrain(); //consider terrain bonuses e.g. Lodestar.
  87. if(stackNativeTerrain == ETerrainId::NONE)
  88. continue;
  89. if(nativeTerrain == ETerrainId::ANY_TERRAIN)
  90. nativeTerrain = stackNativeTerrain;
  91. else if(nativeTerrain != stackNativeTerrain)
  92. return ETerrainId::NONE;
  93. }
  94. return nativeTerrain;
  95. }
  96. bool CGHeroInstance::isCoastVisitable() const
  97. {
  98. return true;
  99. }
  100. bool CGHeroInstance::isBlockedVisitable() const
  101. {
  102. return true;
  103. }
  104. BattleField CGHeroInstance::getBattlefield() const
  105. {
  106. return BattleField::NONE;
  107. }
  108. ui8 CGHeroInstance::getSecSkillLevel(const SecondarySkill & skill) const
  109. {
  110. for(const auto & elem : secSkills)
  111. if(elem.first == skill)
  112. return elem.second;
  113. return 0;
  114. }
  115. void CGHeroInstance::setSecSkillLevel(const SecondarySkill & which, int val, ChangeValueMode mode)
  116. {
  117. int currentLevel = getSecSkillLevel(which);
  118. int newLevel = mode == ChangeValueMode::ABSOLUTE ? val : currentLevel + val;
  119. int newLevelClamped = std::clamp<int>(newLevel, MasteryLevel::NONE, MasteryLevel::EXPERT);
  120. if (currentLevel == newLevelClamped)
  121. return; // no change
  122. if (newLevelClamped == 0) // skill removal
  123. {
  124. vstd::erase_if(secSkills, [which](const std::pair<SecondarySkill, ui8>& pair) { return pair.first == which; });
  125. }
  126. else if(currentLevel == 0) // gained new skill
  127. {
  128. secSkills.emplace_back(which, newLevelClamped);
  129. }
  130. else
  131. {
  132. for (auto & elem : secSkills)
  133. {
  134. if(elem.first == which)
  135. elem.second = newLevelClamped;
  136. }
  137. }
  138. updateSkillBonus(which, newLevelClamped);
  139. }
  140. int3 CGHeroInstance::convertToVisitablePos(const int3 & position) const
  141. {
  142. return position - getVisitableOffset();
  143. }
  144. int3 CGHeroInstance::convertFromVisitablePos(const int3 & position) const
  145. {
  146. return position + getVisitableOffset();
  147. }
  148. bool CGHeroInstance::canLearnSkill() const
  149. {
  150. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  151. }
  152. bool CGHeroInstance::canLearnSkill(const SecondarySkill & which) const
  153. {
  154. if ( !canLearnSkill())
  155. return false;
  156. if (!cb->isAllowed(which))
  157. return false;
  158. if (getSecSkillLevel(which) > 0)
  159. return false;
  160. if (getHeroClass()->secSkillProbability.count(which) == 0)
  161. return false;
  162. if (getHeroClass()->secSkillProbability.at(which) == 0)
  163. return false;
  164. return true;
  165. }
  166. int CGHeroInstance::movementPointsRemaining() const
  167. {
  168. return movement;
  169. }
  170. void CGHeroInstance::setMovementPoints(int points)
  171. {
  172. if(getBonusBearer()->hasBonusOfType(BonusType::UNLIMITED_MOVEMENT))
  173. movement = 1000000;
  174. else
  175. movement = std::max(0, points);
  176. }
  177. int CGHeroInstance::movementPointsLimit(bool onLand) const
  178. {
  179. auto ti = getTurnInfo(0);
  180. return onLand ? ti->getMovePointsLimitLand() : ti->getMovePointsLimitWater();
  181. }
  182. int CGHeroInstance::getLowestCreatureSpeed() const
  183. {
  184. if(stacksCount() != 0)
  185. {
  186. int minimalSpeed = std::numeric_limits<int>::max();
  187. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  188. for(const auto & slot : Slots())
  189. minimalSpeed = std::min(minimalSpeed, slot.second->getInitiative());
  190. return minimalSpeed;
  191. }
  192. else
  193. {
  194. if(commander && commander->alive)
  195. return commander->getInitiative();
  196. }
  197. return 10;
  198. }
  199. std::unique_ptr<TurnInfo> CGHeroInstance::getTurnInfo(int days) const
  200. {
  201. return std::make_unique<TurnInfo>(turnInfoCache.get(), this, days);
  202. }
  203. int CGHeroInstance::movementPointsLimitCached(bool onLand, const TurnInfo * ti) const
  204. {
  205. if (onLand)
  206. return ti->getMovePointsLimitLand();
  207. else
  208. return ti->getMovePointsLimitWater();
  209. }
  210. CGHeroInstance::CGHeroInstance(IGameInfoCallback * cb)
  211. : CArmedInstance(cb),
  212. CArtifactSet(cb),
  213. tacticFormationEnabled(false),
  214. inTownGarrison(false),
  215. moveDir(4),
  216. mana(UNINITIALIZED_MANA),
  217. movement(UNINITIALIZED_MOVEMENT),
  218. level(1),
  219. exp(UNINITIALIZED_EXPERIENCE),
  220. gender(EHeroGender::DEFAULT),
  221. primarySkills(this),
  222. magicSchoolMastery(this),
  223. turnInfoCache(std::make_unique<TurnInfoCache>(this)),
  224. manaPerKnowledgeCached(this, Selector::type()(BonusType::MANA_PER_KNOWLEDGE_PERCENTAGE))
  225. {
  226. setNodeType(HERO);
  227. ID = Obj::HERO;
  228. secSkills.emplace_back(SecondarySkill::NONE, -1);
  229. }
  230. PlayerColor CGHeroInstance::getOwner() const
  231. {
  232. return tempOwner;
  233. }
  234. const CHeroClass * CGHeroInstance::getHeroClass() const
  235. {
  236. return getHeroType()->heroClass;
  237. }
  238. HeroClassID CGHeroInstance::getHeroClassID() const
  239. {
  240. auto heroType = getHeroTypeID();
  241. if (heroType.hasValue())
  242. return getHeroType()->heroClass->getId();
  243. else
  244. return HeroClassID();
  245. }
  246. const CHero * CGHeroInstance::getHeroType() const
  247. {
  248. return getHeroTypeID().toHeroType();
  249. }
  250. HeroTypeID CGHeroInstance::getHeroTypeID() const
  251. {
  252. if (ID == Obj::RANDOM_HERO)
  253. return HeroTypeID::NONE;
  254. return HeroTypeID(getObjTypeIndex().getNum());
  255. }
  256. void CGHeroInstance::setHeroType(HeroTypeID heroType)
  257. {
  258. subID = heroType;
  259. }
  260. bool CGHeroInstance::isGarrisoned() const
  261. {
  262. return inTownGarrison;
  263. }
  264. const CGTownInstance * CGHeroInstance::getVisitedTown() const
  265. {
  266. if (!visitedTown.hasValue())
  267. return nullptr;
  268. return cb->getTown(visitedTown);
  269. }
  270. CGTownInstance * CGHeroInstance::getVisitedTown()
  271. {
  272. if (!visitedTown.hasValue())
  273. return nullptr;
  274. return dynamic_cast<CGTownInstance*>(cb->gameState().getObjInstance(visitedTown));
  275. }
  276. void CGHeroInstance::setVisitedTown(const CGTownInstance * town, bool garrisoned)
  277. {
  278. if (town)
  279. visitedTown = town->id;
  280. else
  281. visitedTown = {};
  282. inTownGarrison = garrisoned;
  283. }
  284. const CCommanderInstance * CGHeroInstance::getCommander() const
  285. {
  286. return commander.get();
  287. }
  288. CCommanderInstance * CGHeroInstance::getCommander()
  289. {
  290. return commander.get();
  291. }
  292. void CGHeroInstance::initObj(vstd::RNG & rand)
  293. {
  294. if (ID == Obj::HERO)
  295. updateAppearance();
  296. }
  297. void CGHeroInstance::initHero(vstd::RNG & rand, const HeroTypeID & SUBID)
  298. {
  299. subID = SUBID.getNum();
  300. initHero(rand);
  301. }
  302. TObjectTypeHandler CGHeroInstance::getObjectHandler() const
  303. {
  304. if (ID == Obj::HERO)
  305. return LIBRARY->objtypeh->getHandlerFor(ID, getHeroClass()->getIndex());
  306. else // prison or random hero
  307. return LIBRARY->objtypeh->getHandlerFor(ID, 0);
  308. }
  309. void CGHeroInstance::updateAppearance()
  310. {
  311. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  312. auto terrain = cb->getTile(visitablePos())->getTerrainID();
  313. auto app = handler->getOverride(terrain, this);
  314. if (app)
  315. appearance = app;
  316. }
  317. void CGHeroInstance::initHero(vstd::RNG & rand)
  318. {
  319. assert(validTypes(true));
  320. if (gender == EHeroGender::DEFAULT)
  321. gender = getHeroType()->gender;
  322. if (ID == Obj::HERO)
  323. {
  324. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClass()->getIndex());
  325. appearance = handler->getTemplates().front();
  326. }
  327. if(!vstd::contains(spells, SpellID::PRESET))
  328. {
  329. // hero starts with default spells
  330. for(const auto & spellID : getHeroType()->spells)
  331. spells.insert(spellID);
  332. }
  333. else //remove placeholder
  334. spells -= SpellID::PRESET;
  335. if(!vstd::contains(spells, SpellID::SPELLBOOK_PRESET))
  336. {
  337. // hero starts with default spellbook presence status
  338. if(!getArt(ArtifactPosition::SPELLBOOK) && getHeroType()->haveSpellBook)
  339. {
  340. auto artifact = cb->gameState().createArtifact(ArtifactID::SPELLBOOK);
  341. putArtifact(ArtifactPosition::SPELLBOOK, artifact);
  342. }
  343. }
  344. else
  345. spells -= SpellID::SPELLBOOK_PRESET;
  346. if(!getArt(ArtifactPosition::MACH4))
  347. {
  348. auto artifact = cb->gameState().createArtifact(ArtifactID::CATAPULT);
  349. putArtifact(ArtifactPosition::MACH4, artifact); //everyone has a catapult
  350. }
  351. if(!hasBonusFrom(BonusSource::HERO_BASE_SKILL))
  352. {
  353. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  354. {
  355. pushPrimSkill(static_cast<PrimarySkill>(g), getHeroClass()->primarySkillInitial[g]);
  356. }
  357. }
  358. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::NONE, -1)) //set secondary skills to default
  359. secSkills = getHeroType()->secSkillsInit;
  360. setFormation(EArmyFormation::LOOSE);
  361. if (!stacksCount()) //standard army//initial army
  362. {
  363. initArmy(rand);
  364. }
  365. assert(validTypes());
  366. if (patrol.patrolling)
  367. patrol.initialPos = visitablePos();
  368. if(exp == UNINITIALIZED_EXPERIENCE)
  369. {
  370. initExp(rand);
  371. }
  372. else
  373. {
  374. levelUpAutomatically(rand);
  375. }
  376. // load base hero bonuses, TODO: per-map loading of base hero bonuses
  377. // must be done separately from global bonuses since recruitable heroes in taverns
  378. // are not attached to global bonus node but need access to some global bonuses
  379. // e.g. MANA_PER_KNOWLEDGE_PERCENTAGE for correct preview and initial state after recruit for(const auto & ob : LIBRARY->modh->heroBaseBonuses)
  380. // or MOVEMENT to compute initial movement before recruiting is finished
  381. const JsonNode & baseBonuses = cb->getSettings().getValue(EGameSettings::BONUSES_PER_HERO);
  382. for(const auto & b : baseBonuses.Struct())
  383. {
  384. auto bonus = JsonUtils::parseBonus(b.second);
  385. bonus->source = BonusSource::HERO_BASE_SKILL;
  386. bonus->sid = BonusSourceID(id);
  387. bonus->duration = BonusDuration::PERMANENT;
  388. addNewBonus(bonus);
  389. }
  390. if (cb->getSettings().getBoolean(EGameSettings::MODULE_COMMANDERS) && !commander && getHeroClass()->commander.hasValue())
  391. {
  392. commander = std::make_unique<CCommanderInstance>(cb, getHeroClass()->commander);
  393. commander->setArmy(getArmy()); //TODO: separate function for setting commanders
  394. commander->giveTotalStackExperience(exp); //after our exp is set
  395. }
  396. skillsInfo = SecondarySkillsInfo();
  397. //copy active (probably growing) bonuses from hero prototype to hero object
  398. for(const std::shared_ptr<Bonus> & b : getHeroType()->specialty)
  399. addNewBonus(b);
  400. //initialize bonuses
  401. recreateSecondarySkillsBonuses();
  402. movement = movementPointsLimit(true);
  403. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  404. }
  405. void CGHeroInstance::initArmy(vstd::RNG & rand, IArmyDescriptor * dst)
  406. {
  407. if(!dst)
  408. dst = this;
  409. int warMachinesGiven = 0;
  410. auto stacksCountChances = cb->getSettings().getVector(EGameSettings::HEROES_STARTING_STACKS_CHANCES);
  411. int stacksCountInitRandomNumber = rand.nextInt(1, 100);
  412. size_t maxStacksCount = std::min(stacksCountChances.size(), getHeroType()->initialArmy.size());
  413. for(int stackNo=0; stackNo < maxStacksCount; stackNo++)
  414. {
  415. if (stacksCountInitRandomNumber > stacksCountChances[stackNo])
  416. continue;
  417. auto & stack = getHeroType()->initialArmy[stackNo];
  418. int count = rand.nextInt(stack.minAmount, stack.maxAmount);
  419. if(stack.creature == CreatureID::NONE)
  420. {
  421. logGlobal->error("Hero %s has invalid creature in initial army", getNameTranslated());
  422. continue;
  423. }
  424. const CCreature * creature = stack.creature.toCreature();
  425. if(creature->warMachine != ArtifactID::NONE) //war machine
  426. {
  427. warMachinesGiven++;
  428. if(dst != this)
  429. continue;
  430. ArtifactID aid = creature->warMachine;
  431. const CArtifact * art = aid.toArtifact();
  432. if(art != nullptr && !art->getPossibleSlots().at(ArtBearer::HERO).empty())
  433. {
  434. //TODO: should we try another possible slots?
  435. ArtifactPosition slot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  436. if(!getArt(slot))
  437. {
  438. auto artifact = cb->gameState().createArtifact(aid);
  439. putArtifact(slot, artifact);
  440. }
  441. else
  442. logGlobal->warn("Hero %s already has artifact at %d, omitting giving artifact %d", getNameTranslated(), slot.toEnum(), aid.toEnum());
  443. }
  444. else
  445. {
  446. logGlobal->error("Hero %s has invalid war machine in initial army", getNameTranslated());
  447. }
  448. }
  449. else
  450. {
  451. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  452. }
  453. }
  454. }
  455. CGHeroInstance::~CGHeroInstance() = default;
  456. bool CGHeroInstance::needsLastStack() const
  457. {
  458. return true;
  459. }
  460. void CGHeroInstance::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  461. {
  462. if(h == this) return; //exclude potential self-visiting
  463. if (ID == Obj::HERO)
  464. {
  465. if( cb->getPlayerRelations(tempOwner, h->tempOwner) != PlayerRelations::ENEMIES)
  466. {
  467. //exchange
  468. gameEvents.heroExchange(h->id, id);
  469. }
  470. else //battle
  471. {
  472. if(getVisitedTown()) //we're in town
  473. getVisitedTown()->onHeroVisit(gameEvents, h); //town will handle attacking
  474. else
  475. gameEvents.startBattle(h, this);
  476. }
  477. }
  478. else if(ID == Obj::PRISON)
  479. {
  480. if (cb->getHeroCount(h->tempOwner, false) < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))//free hero slot
  481. {
  482. //update hero parameters
  483. SetMovePoints smp;
  484. smp.hid = id;
  485. gameEvents.setManaPoints(id, manaLimit());
  486. ObjectInstanceID boatId;
  487. const auto boatPos = visitablePos();
  488. if (cb->getTile(boatPos)->isWater())
  489. {
  490. smp.val = movementPointsLimit(false);
  491. if (!inBoat())
  492. {
  493. //Create a new boat for hero
  494. gameEvents.createBoat(boatPos, getBoatType(), h->getOwner());
  495. boatId = cb->getTopObj(boatPos)->id;
  496. }
  497. }
  498. else
  499. {
  500. smp.val = movementPointsLimit(true);
  501. }
  502. gameEvents.giveHero(id, h->tempOwner, boatId); //recreates def and adds hero to player
  503. gameEvents.setObjPropertyID(id, ObjProperty::ID, Obj(Obj::HERO)); //set ID to 34 AFTER hero gets correct flag color
  504. gameEvents.setMovePoints (&smp);
  505. h->showInfoDialog(gameEvents, 102);
  506. }
  507. else //already 8 wandering heroes
  508. {
  509. h->showInfoDialog(gameEvents, 103);
  510. }
  511. }
  512. }
  513. std::string CGHeroInstance::getObjectName() const
  514. {
  515. if(ID != Obj::PRISON)
  516. {
  517. std::string hoverName = LIBRARY->generaltexth->allTexts[15];
  518. boost::algorithm::replace_first(hoverName,"%s",getNameTranslated());
  519. boost::algorithm::replace_first(hoverName,"%s", getClassNameTranslated());
  520. return hoverName;
  521. }
  522. else
  523. return LIBRARY->objtypeh->getObjectName(ID, 0);
  524. }
  525. std::string CGHeroInstance::getHoverText(PlayerColor player) const
  526. {
  527. std::string hoverText = CArmedInstance::getHoverText(player) + getMovementPointsTextIfOwner(player);
  528. return hoverText;
  529. }
  530. std::string CGHeroInstance::getMovementPointsTextIfOwner(PlayerColor player) const
  531. {
  532. std::string output = "";
  533. if(player == getOwner())
  534. {
  535. output += " " + LIBRARY->generaltexth->translate("vcmi.adventureMap.movementPointsHeroInfo");
  536. boost::replace_first(output, "%POINTS", std::to_string(movementPointsLimit(!inBoat())));
  537. boost::replace_first(output, "%REMAINING", std::to_string(movementPointsRemaining()));
  538. }
  539. return output;
  540. }
  541. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  542. {
  543. return getHeroClass()->isMagicHero() ? 3 : 4;
  544. }
  545. ui8 CGHeroInstance::maxlevelsToWisdom() const
  546. {
  547. return getHeroClass()->isMagicHero() ? 3 : 6;
  548. }
  549. CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo():
  550. magicSchoolCounter(1),
  551. wisdomCounter(1)
  552. {}
  553. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  554. {
  555. magicSchoolCounter = 0;
  556. }
  557. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  558. {
  559. wisdomCounter = 0;
  560. }
  561. void CGHeroInstance::pickRandomObject(vstd::RNG & randomGenerator)
  562. {
  563. assert(ID == Obj::HERO || ID == Obj::PRISON || ID == Obj::RANDOM_HERO);
  564. if (ID == Obj::RANDOM_HERO)
  565. {
  566. auto selectedHero = cb->gameState().pickNextHeroType(randomGenerator, getOwner());
  567. ID = Obj::HERO;
  568. subID = selectedHero;
  569. randomizeArmy(getHeroClass()->faction);
  570. }
  571. auto oldSubID = subID;
  572. // to find object handler we must use heroClass->id
  573. // after setType subID used to store unique hero identify id. Check issue 2277 for details
  574. // exclude prisons which should use appearance as set in map, via map editor or RMG
  575. if (ID != Obj::PRISON)
  576. setType(ID, getHeroClass()->getIndex());
  577. this->subID = oldSubID;
  578. }
  579. void CGHeroInstance::recreateSecondarySkillsBonuses()
  580. {
  581. auto secondarySkillsBonuses = getBonusesFrom(BonusSource::SECONDARY_SKILL);
  582. for(const auto & bonus : *secondarySkillsBonuses)
  583. removeBonus(bonus);
  584. for(const auto & skill_info : secSkills)
  585. if(skill_info.second > 0)
  586. updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
  587. }
  588. void CGHeroInstance::updateSkillBonus(const SecondarySkill & which, int val)
  589. {
  590. removeBonuses(Selector::source(BonusSource::SECONDARY_SKILL, BonusSourceID(which)));
  591. if(val > 0)
  592. {
  593. auto skillBonus = (*LIBRARY->skillh)[which]->at(val).effects;
  594. for(const auto& b : skillBonus)
  595. addNewBonus(std::make_shared<Bonus>(*b));
  596. }
  597. }
  598. void CGHeroInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  599. {
  600. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  601. setStackCount(SlotID(0), identifier.getNum());
  602. }
  603. int CGHeroInstance::getPrimSkillLevel(PrimarySkill id) const
  604. {
  605. return primarySkills.getSkill(id);
  606. }
  607. double CGHeroInstance::getFightingStrength() const
  608. {
  609. const auto & skillValues = primarySkills.getSkills();
  610. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::ATTACK.getNum()]) * (1.0 + 0.05*skillValues[PrimarySkill::DEFENSE.getNum()]));
  611. }
  612. double CGHeroInstance::getMagicStrength() const
  613. {
  614. const auto & skillValues = primarySkills.getSkills();
  615. if (!hasSpellbook())
  616. return 1;
  617. bool atLeastOneCombatSpell = false;
  618. for (auto spell : spells)
  619. {
  620. if (spell.toSpell()->isCombat())
  621. {
  622. atLeastOneCombatSpell = true;
  623. break;
  624. }
  625. }
  626. if (!atLeastOneCombatSpell)
  627. return 1;
  628. return sqrt((1.0 + 0.05*skillValues[PrimarySkill::KNOWLEDGE.getNum()] * mana / manaLimit()) * (1.0 + 0.05*skillValues[PrimarySkill::SPELL_POWER.getNum()] * mana / manaLimit()));
  629. }
  630. double CGHeroInstance::getHeroStrength() const
  631. {
  632. return getFightingStrength() * getMagicStrength();
  633. }
  634. uint64_t CGHeroInstance::getValueForDiplomacy() const
  635. {
  636. // H3 formula for hero strength when considering diplomacy skill
  637. uint64_t armyStrength = getArmyStrength();
  638. double heroStrength = sqrt(
  639. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::ATTACK)) *
  640. (1.0 + 0.05 * getPrimSkillLevel(PrimarySkill::DEFENSE))
  641. );
  642. return heroStrength * armyStrength;
  643. }
  644. uint32_t CGHeroInstance::getValueForCampaign() const
  645. {
  646. /// Determined by testing H3: hero is preferred for transfer in campaigns if total sum of his primary skills and his secondary skill levels is greatest
  647. uint32_t score = 0;
  648. score += getPrimSkillLevel(PrimarySkill::ATTACK);
  649. score += getPrimSkillLevel(PrimarySkill::DEFENSE);
  650. score += getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  651. score += getPrimSkillLevel(PrimarySkill::DEFENSE);
  652. for (const auto& secondary : secSkills)
  653. score += secondary.second;
  654. return score;
  655. }
  656. ui64 CGHeroInstance::getTotalStrength() const
  657. {
  658. double ret = getHeroStrength() * getArmyStrength();
  659. return static_cast<ui64>(ret);
  660. }
  661. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  662. {
  663. return static_cast<TExpType>(exp * (valOfBonuses(BonusType::HERO_EXPERIENCE_GAIN_PERCENT)) / 100.0);
  664. }
  665. int32_t CGHeroInstance::getCasterUnitId() const
  666. {
  667. return id.getNum();
  668. }
  669. int32_t CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool) const
  670. {
  671. int32_t skill = -1; //skill level
  672. spell->forEachSchool([&, this](const SpellSchool & cnf, bool & stop)
  673. {
  674. int32_t thisSchool = magicSchoolMastery.getMastery(cnf); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
  675. if(thisSchool > skill)
  676. {
  677. skill = thisSchool;
  678. if(outSelectedSchool)
  679. *outSelectedSchool = cnf;
  680. }
  681. });
  682. vstd::amax(skill, magicSchoolMastery.getMastery(SpellSchool::ANY)); //any school bonus
  683. vstd::amax(skill, valOfBonuses(BonusType::SPELL, BonusSubtypeID(spell->getId()))); //given by artifact or other effect
  684. vstd::amax(skill, 0); //in case we don't know any school
  685. vstd::amin(skill, 3);
  686. return skill;
  687. }
  688. int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
  689. {
  690. //applying sorcery secondary skill
  691. if(spell->isMagical())
  692. base = static_cast<int64_t>(base * (valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(SpellSchool::ANY))) / 100.0);
  693. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  694. int maxSchoolBonus = 0;
  695. spell->forEachSchool([&maxSchoolBonus, this](const SpellSchool & cnf, bool & stop)
  696. {
  697. vstd::amax(maxSchoolBonus, valOfBonuses(BonusType::SPELL_DAMAGE, BonusSubtypeID(cnf)));
  698. });
  699. base = static_cast<int64_t>(base * (100 + maxSchoolBonus) / 100.0);
  700. if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
  701. base = static_cast<int64_t>(base * static_cast<double>(100 + valOfBonuses(BonusType::SPECIAL_SPELL_LEV, BonusSubtypeID(spell->getId())) / affectedStack->creatureLevel()) / 100.0);
  702. return base;
  703. }
  704. int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  705. {
  706. base = static_cast<int64_t>(base * (100 + valOfBonuses(BonusType::SPECIFIC_SPELL_DAMAGE, BonusSubtypeID(spell->getId()))) / 100.0);
  707. return base;
  708. }
  709. int32_t CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
  710. {
  711. return getSpellSchoolLevel(spell);
  712. }
  713. int32_t CGHeroInstance::getEffectPower(const spells::Spell * spell) const
  714. {
  715. return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  716. }
  717. int32_t CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
  718. {
  719. int32_t spellpower = getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  720. int32_t durationCommon = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID());
  721. int32_t durationSpecific = valOfBonuses(BonusType::SPELL_DURATION, BonusSubtypeID(spell->getId()));
  722. return spellpower + durationCommon + durationSpecific;
  723. }
  724. int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
  725. {
  726. return 0;
  727. }
  728. PlayerColor CGHeroInstance::getCasterOwner() const
  729. {
  730. return tempOwner;
  731. }
  732. void CGHeroInstance::getCasterName(MetaString & text) const
  733. {
  734. //FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
  735. text.replaceRawString(getNameTranslated());
  736. }
  737. void CGHeroInstance::getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const
  738. {
  739. const bool singleTarget = attacked.size() == 1;
  740. const int textIndex = singleTarget ? 195 : 196;
  741. text.appendLocalString(EMetaText::GENERAL_TXT, textIndex);
  742. getCasterName(text);
  743. text.replaceName(spell->getId());
  744. if(singleTarget)
  745. attacked.at(0)->addNameReplacement(text, true);
  746. }
  747. const CGHeroInstance * CGHeroInstance::getHeroCaster() const
  748. {
  749. return this;
  750. }
  751. void CGHeroInstance::spendMana(ServerCallback * server, const int spellCost) const
  752. {
  753. if(spellCost != 0)
  754. {
  755. SetMana sm;
  756. sm.mode = ChangeValueMode::RELATIVE;
  757. sm.hid = id;
  758. sm.val = -spellCost;
  759. server->apply(sm);
  760. }
  761. }
  762. bool CGHeroInstance::canCastThisSpell(const spells::Spell * spell) const
  763. {
  764. const bool isAllowed = cb->isAllowed(spell->getId());
  765. const bool inSpellBook = vstd::contains(spells, spell->getId()) && hasSpellbook();
  766. const bool specificBonus = hasBonusOfType(BonusType::SPELL, BonusSubtypeID(spell->getId()));
  767. bool schoolBonus = false;
  768. spell->forEachSchool([this, &schoolBonus](const SpellSchool & cnf, bool & stop)
  769. {
  770. if(hasBonusOfType(BonusType::SPELLS_OF_SCHOOL, BonusSubtypeID(cnf)))
  771. {
  772. schoolBonus = stop = true;
  773. }
  774. });
  775. const bool levelBonus = hasBonusOfType(BonusType::SPELLS_OF_LEVEL, BonusCustomSubtype::spellLevel(spell->getLevel()));
  776. if(spell->isSpecial())
  777. {
  778. if(inSpellBook)
  779. {//hero has this spell in spellbook
  780. logGlobal->error("Special spell %s in spellbook.", spell->getNameTranslated());
  781. }
  782. return specificBonus;
  783. }
  784. else if(!isAllowed)
  785. {
  786. if(inSpellBook)
  787. {
  788. //hero has this spell in spellbook
  789. //it is normal if set in map editor, but trace it to possible debug of magic guild
  790. logGlobal->trace("Banned spell %s in spellbook.", spell->getNameTranslated());
  791. }
  792. return inSpellBook || specificBonus || schoolBonus || levelBonus;
  793. }
  794. else
  795. {
  796. return inSpellBook || schoolBonus || specificBonus || levelBonus;
  797. }
  798. }
  799. bool CGHeroInstance::canLearnSpell(const spells::Spell * spell, bool allowBanned) const
  800. {
  801. if(!hasSpellbook())
  802. return false;
  803. if(spell->getLevel() > maxSpellLevel()) //not enough wisdom
  804. return false;
  805. if(vstd::contains(spells, spell->getId()))//already known
  806. return false;
  807. if(spell->isSpecial())
  808. {
  809. logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->getNameTranslated());
  810. return false;//special spells can not be learned
  811. }
  812. if(spell->isCreatureAbility())
  813. {
  814. logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->getNameTranslated());
  815. return false;//creature abilities can not be learned
  816. }
  817. if(!allowBanned && !cb->isAllowed(spell->getId()))
  818. {
  819. logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->getNameTranslated());
  820. return false;//banned spells should not be learned
  821. }
  822. return true;
  823. }
  824. /**
  825. * Calculates what creatures and how many to be raised from a battle.
  826. * @param battleResult The results of the battle.
  827. * @return Returns a pair with the first value indicating the ID of the creature
  828. * type and second value the amount. Both values are returned as -1 if necromancy
  829. * could not be applied.
  830. */
  831. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  832. {
  833. bool hasImprovedNecromancy = hasBonusOfType(BonusType::IMPROVED_NECROMANCY);
  834. // need skill or cloak of undead king - lesser artifacts don't work without skill
  835. if (hasImprovedNecromancy)
  836. {
  837. double necromancySkill = valOfBonuses(BonusType::UNDEAD_RAISE_PERCENTAGE) / 100.0;
  838. const ui8 necromancyLevel = valOfBonuses(BonusType::IMPROVED_NECROMANCY);
  839. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  840. const std::map<CreatureID,si32> &casualties = battleResult.casualties[CBattleInfoEssentials::otherSide(battleResult.winner)];
  841. if(casualties.empty())
  842. return CStackBasicDescriptor();
  843. // figure out what to raise - pick strongest creature meeting requirements
  844. CreatureID creatureTypeRaised = CreatureID::NONE; //now we always have IMPROVED_NECROMANCY, no need for hardcode
  845. int requiredCasualtyLevel = 1;
  846. TConstBonusListPtr improvedNecromancy = getBonusesOfType(BonusType::IMPROVED_NECROMANCY);
  847. if(!improvedNecromancy->empty())
  848. {
  849. int maxCasualtyLevel = 1;
  850. for(const auto & casualty : casualties)
  851. vstd::amax(maxCasualtyLevel, LIBRARY->creatures()->getById(casualty.first)->getLevel());
  852. // pick best bonus available
  853. std::shared_ptr<Bonus> topPick;
  854. for(const std::shared_ptr<Bonus> & newPick : *improvedNecromancy)
  855. {
  856. // addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
  857. if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
  858. continue;
  859. if(!topPick)
  860. {
  861. topPick = newPick;
  862. }
  863. else
  864. {
  865. auto quality = [](const std::shared_ptr<Bonus> & pick) -> std::tuple<int, int, int>
  866. {
  867. const auto * c = pick->subtype.as<CreatureID>().toCreature();
  868. return std::tuple<int, int, int> {c->getLevel(), static_cast<int>(c->getFullRecruitCost().marketValue()), -pick->additionalInfo[1]};
  869. };
  870. if(quality(topPick) < quality(newPick))
  871. topPick = newPick;
  872. }
  873. }
  874. if(topPick)
  875. {
  876. creatureTypeRaised = topPick->subtype.as<CreatureID>();
  877. requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
  878. }
  879. }
  880. assert(creatureTypeRaised != CreatureID::NONE);
  881. // raise upgraded creature (at 2/3 rate) if no space available otherwise
  882. if(getSlotFor(creatureTypeRaised) == SlotID())
  883. {
  884. for(const CreatureID & upgraded : creatureTypeRaised.toCreature()->upgrades)
  885. {
  886. if(getSlotFor(upgraded) != SlotID())
  887. {
  888. creatureTypeRaised = upgraded;
  889. necromancySkill *= 2/3.0;
  890. break;
  891. }
  892. }
  893. }
  894. // calculate number of creatures raised - low level units contribute at 50% rate
  895. const double raisedUnitHealth = creatureTypeRaised.toCreature()->getMaxHealth();
  896. double raisedUnits = 0;
  897. for(const auto & casualty : casualties)
  898. {
  899. const CCreature * c = casualty.first.toCreature();
  900. double raisedFromCasualty = std::min(c->getMaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
  901. if(c->getLevel() < requiredCasualtyLevel)
  902. raisedFromCasualty *= 0.5;
  903. raisedUnits += raisedFromCasualty;
  904. }
  905. return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
  906. }
  907. return CStackBasicDescriptor();
  908. }
  909. /*
  910. int3 CGHeroInstance::getSightCenter() const
  911. {
  912. return getPosition(false);
  913. }*/
  914. int CGHeroInstance::getSightRadius() const
  915. {
  916. return valOfBonuses(BonusType::SIGHT_RADIUS); // scouting gives SIGHT_RADIUS bonus
  917. }
  918. si32 CGHeroInstance::manaRegain() const
  919. {
  920. if (hasBonusOfType(BonusType::FULL_MANA_REGENERATION))
  921. return manaLimit();
  922. return valOfBonuses(BonusType::MANA_REGENERATION);
  923. }
  924. si32 CGHeroInstance::getManaNewTurn() const
  925. {
  926. if(getVisitedTown() && getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  927. {
  928. //if hero starts turn in town with mage guild - restore all mana
  929. return std::max(mana, manaLimit());
  930. }
  931. si32 res = mana + manaRegain();
  932. res = std::min(res, manaLimit());
  933. res = std::max(res, mana);
  934. res = std::max(res, 0);
  935. return res;
  936. }
  937. // /**
  938. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  939. // * or discards it if it cannot be equipped.
  940. // */
  941. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  942. // {
  943. // CArtifact * const artifact = LIBRARY->arth->objects[aid]; //pointer to constant object
  944. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  945. // ai->putAt(this, ai->firstAvailableSlot(this));
  946. // }
  947. BoatId CGHeroInstance::getBoatType() const
  948. {
  949. return BoatId(LIBRARY->townh->getById(getHeroClass()->faction)->getBoatType());
  950. }
  951. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  952. {
  953. offsets = {
  954. {0, -1, 0},
  955. {+1, -1, 0},
  956. {+1, 0, 0},
  957. {+1, +1, 0},
  958. {0, +1, 0},
  959. {-1, +1, 0},
  960. {-1, 0, 0},
  961. {-1, -1, 0},
  962. };
  963. }
  964. const IObjectInterface * CGHeroInstance::getObject() const
  965. {
  966. return this;
  967. }
  968. int32_t CGHeroInstance::getSpellCost(const spells::Spell * sp) const
  969. {
  970. return sp->getCost(getSpellSchoolLevel(sp));
  971. }
  972. void CGHeroInstance::pushPrimSkill( PrimarySkill which, int val )
  973. {
  974. auto sel = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which))
  975. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  976. removeBonuses(sel);
  977. addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::HERO_BASE_SKILL, val, BonusSourceID(id), BonusSubtypeID(which)));
  978. }
  979. EAlignment CGHeroInstance::getAlignment() const
  980. {
  981. return getHeroClass()->getAlignment();
  982. }
  983. void CGHeroInstance::initExp(vstd::RNG & rand)
  984. {
  985. exp = rand.nextInt(40, 89);
  986. }
  987. std::string CGHeroInstance::nodeName() const
  988. {
  989. return "Hero " + getNameTextID();
  990. }
  991. si32 CGHeroInstance::manaLimit() const
  992. {
  993. return getPrimSkillLevel(PrimarySkill::KNOWLEDGE) * manaPerKnowledgeCached.getValue() / 100;
  994. }
  995. HeroTypeID CGHeroInstance::getPortraitSource() const
  996. {
  997. if (customPortraitSource.isValid())
  998. return customPortraitSource;
  999. else
  1000. return getHeroTypeID();
  1001. }
  1002. int32_t CGHeroInstance::getIconIndex() const
  1003. {
  1004. return getPortraitSource().toEntity(LIBRARY)->getIconIndex();
  1005. }
  1006. std::string CGHeroInstance::getNameTranslated() const
  1007. {
  1008. return LIBRARY->generaltexth->translate(getNameTextID());
  1009. }
  1010. std::string CGHeroInstance::getClassNameTranslated() const
  1011. {
  1012. return LIBRARY->generaltexth->translate(getClassNameTextID());
  1013. }
  1014. std::string CGHeroInstance::getClassNameTextID() const
  1015. {
  1016. if (isCampaignGem())
  1017. return "core.genrltxt.735";
  1018. return getHeroClass()->getNameTextID();
  1019. }
  1020. std::string CGHeroInstance::getNameTextID() const
  1021. {
  1022. if (!nameCustomTextId.empty())
  1023. return nameCustomTextId;
  1024. if (getHeroTypeID().hasValue())
  1025. return getHeroType()->getNameTextID();
  1026. // FIXME: called by logging from some specialties (mods?) before type is set on deserialization
  1027. // assert(0);
  1028. return "";
  1029. }
  1030. std::string CGHeroInstance::getBiographyTranslated() const
  1031. {
  1032. return LIBRARY->generaltexth->translate(getBiographyTextID());
  1033. }
  1034. std::string CGHeroInstance::getBiographyTextID() const
  1035. {
  1036. if (!biographyCustomTextId.empty())
  1037. return biographyCustomTextId;
  1038. if (getHeroTypeID().hasValue())
  1039. return getHeroType()->getBiographyTextID();
  1040. return ""; //for random hero
  1041. }
  1042. CGHeroInstance::ArtPlacementMap CGHeroInstance::putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art)
  1043. {
  1044. assert(art->canBePutAt(this, pos));
  1045. if(ArtifactUtils::isSlotEquipment(pos))
  1046. attachToSource(*art);
  1047. return CArtifactSet::putArtifact(pos, art);
  1048. }
  1049. void CGHeroInstance::removeArtifact(const ArtifactPosition & pos)
  1050. {
  1051. auto art = getArt(pos);
  1052. assert(art);
  1053. CArtifactSet::removeArtifact(pos);
  1054. if(ArtifactUtils::isSlotEquipment(pos))
  1055. detachFromSource(*art);
  1056. }
  1057. bool CGHeroInstance::hasSpellbook() const
  1058. {
  1059. return getArt(ArtifactPosition::SPELLBOOK);
  1060. }
  1061. void CGHeroInstance::addSpellToSpellbook(const SpellID & spell)
  1062. {
  1063. spells.insert(spell);
  1064. }
  1065. void CGHeroInstance::removeSpellFromSpellbook(const SpellID & spell)
  1066. {
  1067. spells.erase(spell);
  1068. }
  1069. bool CGHeroInstance::spellbookContainsSpell(const SpellID & spell) const
  1070. {
  1071. return vstd::contains(spells, spell);
  1072. }
  1073. void CGHeroInstance::removeSpellbook()
  1074. {
  1075. spells.clear();
  1076. if(hasSpellbook())
  1077. {
  1078. cb->gameState().getMap().removeArtifactInstance(*this, ArtifactPosition::SPELLBOOK);
  1079. }
  1080. }
  1081. const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
  1082. {
  1083. return spells;
  1084. }
  1085. int CGHeroInstance::maxSpellLevel() const
  1086. {
  1087. return std::min(GameConstants::SPELL_LEVELS, valOfBonuses(BonusType::MAX_LEARNABLE_SPELL_LEVEL));
  1088. }
  1089. bool CGHeroInstance::inBoat() const
  1090. {
  1091. return boardedBoat.hasValue();
  1092. }
  1093. const CGBoat * CGHeroInstance::getBoat() const
  1094. {
  1095. if (boardedBoat.hasValue())
  1096. return dynamic_cast<const CGBoat*>(cb->getObjInstance(boardedBoat));
  1097. return nullptr;
  1098. }
  1099. CGBoat * CGHeroInstance::getBoat()
  1100. {
  1101. if (boardedBoat.hasValue())
  1102. return dynamic_cast<CGBoat*>(cb->gameState().getObjInstance(boardedBoat));
  1103. return nullptr;
  1104. }
  1105. void CGHeroInstance::setBoat(CGBoat* newBoat)
  1106. {
  1107. if (newBoat)
  1108. {
  1109. boardedBoat = newBoat->id;
  1110. attachTo(*newBoat);
  1111. newBoat->setBoardedHero(this);
  1112. }
  1113. else if (boardedBoat.hasValue())
  1114. {
  1115. auto oldBoat = getBoat();
  1116. boardedBoat = {};
  1117. detachFrom(*oldBoat);
  1118. oldBoat->setBoardedHero(nullptr);
  1119. }
  1120. }
  1121. void CGHeroInstance::restoreBonusSystem(CGameState & gs)
  1122. {
  1123. CArmedInstance::restoreBonusSystem(gs);
  1124. artDeserializationFix(gs, this);
  1125. if (commander)
  1126. commander->artDeserializationFix(gs, this->commander.get());
  1127. if (boardedBoat.hasValue())
  1128. {
  1129. auto boat = gs.getObjInstance(boardedBoat);
  1130. if (boat)
  1131. attachTo(dynamic_cast<CGBoat&>(*boat));
  1132. }
  1133. }
  1134. void CGHeroInstance::attachToBonusSystem(CGameState & gs)
  1135. {
  1136. CArmedInstance::attachToBonusSystem(gs);
  1137. if (boardedBoat.hasValue())
  1138. {
  1139. auto boat = gs.getObjInstance(boardedBoat);
  1140. if (boat)
  1141. attachTo(dynamic_cast<CGBoat&>(*boat));
  1142. }
  1143. }
  1144. void CGHeroInstance::detachFromBonusSystem(CGameState & gs)
  1145. {
  1146. CArmedInstance::detachFromBonusSystem(gs);
  1147. if (boardedBoat.hasValue())
  1148. {
  1149. auto boat = gs.getObjInstance(boardedBoat);
  1150. if (boat)
  1151. detachFrom(dynamic_cast<CGBoat&>(*boat));
  1152. }
  1153. }
  1154. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const
  1155. {
  1156. if(!getVisitedTown())
  1157. return nullptr;
  1158. if (isBattleOutsideTown)
  1159. return const_cast<CTownAndVisitingHero *>(&getVisitedTown()->townAndVis);
  1160. return const_cast<CGTownInstance*>(getVisitedTown());
  1161. }
  1162. CBonusSystemNode * CGHeroInstance::whereShouldBeAttachedOnSiege(CGameState & gs)
  1163. {
  1164. if(getVisitedTown())
  1165. return whereShouldBeAttachedOnSiege(getVisitedTown()->isBattleOutsideTown(this));
  1166. return &CArmedInstance::whereShouldBeAttached(gs);
  1167. }
  1168. CBonusSystemNode & CGHeroInstance::whereShouldBeAttached(CGameState & gs)
  1169. {
  1170. if(visitedTown.hasValue())
  1171. {
  1172. auto town = gs.getTown(visitedTown);
  1173. if(isGarrisoned())
  1174. return *town;
  1175. else
  1176. return town->townAndVis;
  1177. }
  1178. else
  1179. return CArmedInstance::whereShouldBeAttached(gs);
  1180. }
  1181. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
  1182. {
  1183. if(!ti->hasFreeShipBoarding())
  1184. return 0; // take all MPs by default
  1185. auto boatLayer = inBoat() ? getBoat()->layer : EPathfindingLayer::SAIL;
  1186. int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : boatLayer);
  1187. int mp2 = ti->getMaxMovePoints(disembark ? boatLayer : EPathfindingLayer::LAND);
  1188. int ret = static_cast<int>((MPsBefore - basicCost) * static_cast<double>(mp1) / mp2);
  1189. return ret;
  1190. }
  1191. EDiggingStatus CGHeroInstance::diggingStatus() const
  1192. {
  1193. if(static_cast<int>(movement) < movementPointsLimit(true))
  1194. return EDiggingStatus::LACK_OF_MOVEMENT;
  1195. if(!ArtifactID(ArtifactID::GRAIL).toArtifact()->canBePutAt(this))
  1196. return EDiggingStatus::BACKPACK_IS_FULL;
  1197. return cb->getTileDigStatus(visitablePos());
  1198. }
  1199. ArtBearer CGHeroInstance::bearerType() const
  1200. {
  1201. return ArtBearer::HERO;
  1202. }
  1203. std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills(vstd::RNG & rand) const
  1204. {
  1205. auto getObligatorySkills = [](CSkill::Obligatory obl){
  1206. std::set<SecondarySkill> obligatory;
  1207. for(auto i = 0; i < LIBRARY->skillh->size(); i++)
  1208. if((*LIBRARY->skillh)[SecondarySkill(i)]->obligatory(obl))
  1209. obligatory.insert(i); //Always return all obligatory skills
  1210. return obligatory;
  1211. };
  1212. auto intersect = [](const std::set<SecondarySkill> & left, const std::set<SecondarySkill> & right)
  1213. {
  1214. std::set<SecondarySkill> intersect;
  1215. std::set_intersection(left.begin(), left.end(), right.begin(), right.end(),
  1216. std::inserter(intersect, intersect.begin()));
  1217. return intersect;
  1218. };
  1219. std::set<SecondarySkill> wisdomList = getObligatorySkills(CSkill::Obligatory::MAJOR);
  1220. std::set<SecondarySkill> schoolList = getObligatorySkills(CSkill::Obligatory::MINOR);
  1221. std::set<SecondarySkill> basicAndAdv;
  1222. std::set<SecondarySkill> none;
  1223. for(int i = 0; i < LIBRARY->skillh->size(); i++)
  1224. if (canLearnSkill(SecondarySkill(i)))
  1225. none.insert(SecondarySkill(i));
  1226. for(const auto & elem : secSkills)
  1227. {
  1228. if(elem.second < MasteryLevel::EXPERT)
  1229. basicAndAdv.insert(elem.first);
  1230. none.erase(elem.first);
  1231. }
  1232. bool wantsWisdom = skillsInfo.wisdomCounter + 1 >= maxlevelsToWisdom();
  1233. bool wantsSchool = skillsInfo.magicSchoolCounter + 1 >= maxlevelsToMagicSchool();
  1234. std::vector<SecondarySkill> skills;
  1235. auto chooseSkill = [&](std::set<SecondarySkill> & options)
  1236. {
  1237. bool selectWisdom = wantsWisdom && !intersect(options, wisdomList).empty();
  1238. bool selectSchool = wantsSchool && !intersect(options, schoolList).empty();
  1239. SecondarySkill selection;
  1240. if (selectWisdom)
  1241. selection = getHeroClass()->chooseSecSkill(intersect(options, wisdomList), rand);
  1242. else if (selectSchool)
  1243. selection = getHeroClass()->chooseSecSkill(intersect(options, schoolList), rand);
  1244. else
  1245. selection = getHeroClass()->chooseSecSkill(options, rand);
  1246. skills.push_back(selection);
  1247. options.erase(selection);
  1248. if (wisdomList.count(selection))
  1249. wisdomList.clear();
  1250. if (schoolList.count(selection))
  1251. schoolList.clear();
  1252. };
  1253. if (!basicAndAdv.empty())
  1254. chooseSkill(basicAndAdv);
  1255. if (canLearnSkill() && !none.empty())
  1256. chooseSkill(none);
  1257. if (!basicAndAdv.empty() && skills.size() < 2)
  1258. chooseSkill(basicAndAdv);
  1259. if (canLearnSkill() && !none.empty() && skills.size() < 2)
  1260. chooseSkill(none);
  1261. return skills;
  1262. }
  1263. PrimarySkill CGHeroInstance::nextPrimarySkill(vstd::RNG & rand) const
  1264. {
  1265. assert(gainsLevel());
  1266. const auto isLowLevelHero = level < GameConstants::HERO_HIGH_LEVEL;
  1267. const auto & skillChances = isLowLevelHero ? getHeroClass()->primarySkillLowLevel : getHeroClass()->primarySkillHighLevel;
  1268. if (isCampaignYog())
  1269. {
  1270. // Yog can only receive Attack or Defence on level-up
  1271. std::vector<int> yogChances = { skillChances[0], skillChances[1]};
  1272. return static_cast<PrimarySkill>(RandomGeneratorUtil::nextItemWeighted(yogChances, rand));
  1273. }
  1274. return static_cast<PrimarySkill>(RandomGeneratorUtil::nextItemWeighted(skillChances, rand));
  1275. }
  1276. std::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(vstd::RNG & rand) const
  1277. {
  1278. assert(gainsLevel());
  1279. std::optional<SecondarySkill> chosenSecondarySkill;
  1280. const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(rand);
  1281. if(!proposedSecondarySkills.empty())
  1282. {
  1283. std::vector<SecondarySkill> learnedSecondarySkills;
  1284. for(const auto & secondarySkill : proposedSecondarySkills)
  1285. {
  1286. if(getSecSkillLevel(secondarySkill) > 0)
  1287. {
  1288. learnedSecondarySkills.push_back(secondarySkill);
  1289. }
  1290. }
  1291. if(learnedSecondarySkills.empty())
  1292. {
  1293. // there are only new skills to learn, so choose anyone of them
  1294. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
  1295. }
  1296. else
  1297. {
  1298. // preferably upgrade a already learned secondary skill
  1299. chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
  1300. }
  1301. }
  1302. return chosenSecondarySkill;
  1303. }
  1304. void CGHeroInstance::setPrimarySkill(PrimarySkill primarySkill, si64 value, ChangeValueMode mode)
  1305. {
  1306. if(primarySkill < PrimarySkill::EXPERIENCE)
  1307. {
  1308. auto skill = getLocalBonus(Selector::type()(BonusType::PRIMARY_SKILL)
  1309. .And(Selector::subtype()(BonusSubtypeID(primarySkill)))
  1310. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1311. assert(skill);
  1312. if(mode == ChangeValueMode::ABSOLUTE)
  1313. {
  1314. skill->val = static_cast<si32>(value);
  1315. }
  1316. else
  1317. {
  1318. skill->val += static_cast<si32>(value);
  1319. }
  1320. nodeHasChanged();
  1321. }
  1322. else if(primarySkill == PrimarySkill::EXPERIENCE)
  1323. {
  1324. if(mode == ChangeValueMode::ABSOLUTE)
  1325. {
  1326. exp = value;
  1327. }
  1328. else
  1329. {
  1330. exp += value;
  1331. }
  1332. }
  1333. }
  1334. bool CGHeroInstance::gainsLevel() const
  1335. {
  1336. return level < LIBRARY->heroh->maxSupportedLevel() && exp >= static_cast<TExpType>(LIBRARY->heroh->reqExp(level+1));
  1337. }
  1338. void CGHeroInstance::levelUp(const std::vector<SecondarySkill> & skills)
  1339. {
  1340. ++level;
  1341. //deterministic secondary skills
  1342. ++skillsInfo.magicSchoolCounter;
  1343. ++skillsInfo.wisdomCounter;
  1344. for(const auto & skill : skills)
  1345. {
  1346. if((*LIBRARY->skillh)[skill]->obligatory(CSkill::Obligatory::MAJOR))
  1347. skillsInfo.resetWisdomCounter();
  1348. if((*LIBRARY->skillh)[skill]->obligatory(CSkill::Obligatory::MINOR))
  1349. skillsInfo.resetMagicSchoolCounter();
  1350. }
  1351. //update specialty and other bonuses that scale with level
  1352. nodeHasChanged();
  1353. }
  1354. void CGHeroInstance::attachCommanderToArmy()
  1355. {
  1356. if (commander)
  1357. commander->setArmy(this);
  1358. }
  1359. void CGHeroInstance::levelUpAutomatically(vstd::RNG & rand)
  1360. {
  1361. while(gainsLevel())
  1362. {
  1363. const auto primarySkill = nextPrimarySkill(rand);
  1364. setPrimarySkill(primarySkill, 1, ChangeValueMode::RELATIVE);
  1365. auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(rand);
  1366. const auto secondarySkill = nextSecondarySkill(rand);
  1367. if(secondarySkill)
  1368. {
  1369. setSecSkillLevel(*secondarySkill, 1, ChangeValueMode::RELATIVE);
  1370. }
  1371. //TODO why has the secondary skills to be passed to the method?
  1372. levelUp(proposedSecondarySkills);
  1373. }
  1374. }
  1375. bool CGHeroInstance::hasVisions(const CGObjectInstance * target, BonusSubtypeID subtype) const
  1376. {
  1377. //VISIONS spell support
  1378. const int visionsMultiplier = valOfBonuses(BonusType::VISIONS, subtype);
  1379. int visionsRange = visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  1380. if (visionsMultiplier > 0)
  1381. vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present
  1382. const int distance = static_cast<int>(target->anchorPos().dist2d(visitablePos()));
  1383. //logGlobal->debug(boost::str(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));
  1384. return (distance < visionsRange) && (target->anchorPos().z == anchorPos().z);
  1385. }
  1386. std::string CGHeroInstance::getHeroTypeName() const
  1387. {
  1388. if(ID == Obj::HERO || ID == Obj::PRISON)
  1389. return getHeroType()->getJsonKey();
  1390. return "";
  1391. }
  1392. void CGHeroInstance::afterAddToMap(CMap * map)
  1393. {
  1394. map->heroAddedToMap(this);
  1395. }
  1396. void CGHeroInstance::afterRemoveFromMap(CMap* map)
  1397. {
  1398. map->heroRemovedFromMap(this);
  1399. }
  1400. void CGHeroInstance::setHeroTypeName(const std::string & identifier)
  1401. {
  1402. if(ID == Obj::HERO || ID == Obj::PRISON)
  1403. {
  1404. auto rawId = LIBRARY->identifiers()->getIdentifier(ModScope::scopeMap(), "hero", identifier);
  1405. if(rawId)
  1406. subID = rawId.value();
  1407. else
  1408. {
  1409. throw std::runtime_error("Couldn't resolve hero identifier " + identifier);
  1410. }
  1411. }
  1412. }
  1413. void CGHeroInstance::updateFrom(const JsonNode & data)
  1414. {
  1415. CGObjectInstance::updateFrom(data);
  1416. }
  1417. void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
  1418. {
  1419. handler.serializeString("biography", biographyCustomTextId);
  1420. handler.serializeInt("experience", exp, 0);
  1421. if(!handler.saving && exp != UNINITIALIZED_EXPERIENCE) //do not gain levels if experience is not initialized
  1422. {
  1423. while (gainsLevel())
  1424. {
  1425. ++level;
  1426. }
  1427. }
  1428. handler.serializeString("name", nameCustomTextId);
  1429. handler.serializeInt("gender", gender, 0);
  1430. handler.serializeId("portrait", customPortraitSource, HeroTypeID::NONE);
  1431. //primary skills
  1432. if(handler.saving)
  1433. {
  1434. const bool haveSkills = hasBonus(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1435. if(haveSkills)
  1436. {
  1437. auto primarySkills = handler.enterStruct("primarySkills");
  1438. for(auto skill : PrimarySkill::ALL_SKILLS())
  1439. {
  1440. int value = valOfBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(skill)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)));
  1441. handler.serializeInt(NPrimarySkill::names[skill.getNum()], value, 0);
  1442. }
  1443. }
  1444. }
  1445. else
  1446. {
  1447. auto primarySkills = handler.enterStruct("primarySkills");
  1448. if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
  1449. {
  1450. for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  1451. {
  1452. int value = 0;
  1453. handler.serializeInt(NPrimarySkill::names[i], value, 0);
  1454. pushPrimSkill(static_cast<PrimarySkill>(i), value);
  1455. }
  1456. }
  1457. }
  1458. //secondary skills
  1459. if(handler.saving)
  1460. {
  1461. //does hero have default skills?
  1462. bool defaultSkills = false;
  1463. bool normalSkills = false;
  1464. for(const auto & p : secSkills)
  1465. {
  1466. if(p.first == SecondarySkill(SecondarySkill::NONE))
  1467. defaultSkills = true;
  1468. else
  1469. normalSkills = true;
  1470. }
  1471. if(defaultSkills && normalSkills)
  1472. logGlobal->error("Mixed default and normal secondary skills");
  1473. //in json default skills means no field/null
  1474. if(!defaultSkills)
  1475. {
  1476. //enter array here as handler initialize it
  1477. auto secondarySkills = handler.enterArray("secondarySkills");
  1478. secondarySkills.syncSize(secSkills, JsonNode::JsonType::DATA_VECTOR);
  1479. for(size_t skillIndex = 0; skillIndex < secondarySkills.size(); ++skillIndex)
  1480. {
  1481. JsonArraySerializer inner = secondarySkills.enterArray(skillIndex);
  1482. SecondarySkill skillId = secSkills.at(skillIndex).first;
  1483. handler.serializeId("skill", skillId);
  1484. std::string skillLevel = NSecondarySkill::levels.at(secSkills.at(skillIndex).second);
  1485. handler.serializeString("level", skillLevel);
  1486. }
  1487. }
  1488. }
  1489. else
  1490. {
  1491. auto secondarySkills = handler.getCurrent()["secondarySkills"];
  1492. secSkills.clear();
  1493. if(secondarySkills.getType() == JsonNode::JsonType::DATA_NULL)
  1494. {
  1495. secSkills.emplace_back(SecondarySkill::NONE, -1);
  1496. }
  1497. else
  1498. {
  1499. auto addSkill = [this](const std::string & skillId, const std::string & levelId)
  1500. {
  1501. const int rawId = SecondarySkill::decode(skillId);
  1502. if(rawId < 0)
  1503. {
  1504. logGlobal->error("Invalid secondary skill %s", skillId);
  1505. return;
  1506. }
  1507. const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
  1508. if(level < 0)
  1509. {
  1510. logGlobal->error("Invalid secondary skill level%s", levelId);
  1511. return;
  1512. }
  1513. secSkills.emplace_back(SecondarySkill(rawId), level);
  1514. };
  1515. if(secondarySkills.getType() == JsonNode::JsonType::DATA_VECTOR)
  1516. {
  1517. for(const auto & p : secondarySkills.Vector())
  1518. {
  1519. auto skillMap = p.Struct();
  1520. addSkill(skillMap["skill"].String(), skillMap["level"].String());
  1521. }
  1522. }
  1523. else if(secondarySkills.getType() == JsonNode::JsonType::DATA_STRUCT)
  1524. {
  1525. for(const auto & p : secondarySkills.Struct())
  1526. {
  1527. addSkill(p.first, p.second.String());
  1528. };
  1529. }
  1530. }
  1531. }
  1532. handler.serializeIdArray("spellBook", spells);
  1533. if(handler.saving)
  1534. CArtifactSet::serializeJsonArtifacts(handler, "artifacts", &cb->gameState().getMap());
  1535. }
  1536. void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  1537. {
  1538. serializeCommonOptions(handler);
  1539. serializeJsonOwner(handler);
  1540. if(ID == Obj::HERO || ID == Obj::PRISON)
  1541. {
  1542. std::string typeName;
  1543. if(handler.saving)
  1544. typeName = getHeroTypeName();
  1545. handler.serializeString("type", typeName);
  1546. if(!handler.saving)
  1547. setHeroTypeName(typeName);
  1548. }
  1549. if(!handler.saving)
  1550. {
  1551. if(!appearance)
  1552. {
  1553. // crossoverDeserialize
  1554. appearance = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, getHeroClassID())->getTemplates().front();
  1555. }
  1556. }
  1557. CArmedInstance::serializeJsonOptions(handler);
  1558. {
  1559. ui32 rawPatrolRadius = NO_PATROLLING;
  1560. if(handler.saving)
  1561. {
  1562. rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLLING;
  1563. }
  1564. handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLLING);
  1565. if(!handler.saving)
  1566. {
  1567. patrol.patrolling = (rawPatrolRadius != NO_PATROLLING);
  1568. patrol.initialPos = visitablePos();
  1569. patrol.patrolRadius = patrol.patrolling ? rawPatrolRadius : 0;
  1570. }
  1571. }
  1572. }
  1573. void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
  1574. {
  1575. serializeCommonOptions(handler);
  1576. }
  1577. bool CGHeroInstance::isMissionCritical() const
  1578. {
  1579. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  1580. {
  1581. if (event.effect.type != EventEffect::DEFEAT)
  1582. continue;
  1583. auto const & testFunctor = [&](const EventCondition & condition)
  1584. {
  1585. if ((condition.condition == EventCondition::CONTROL) && condition.objectID != ObjectInstanceID::NONE)
  1586. return (id != condition.objectID);
  1587. if (condition.condition == EventCondition::HAVE_ARTIFACT)
  1588. {
  1589. if(hasArt(condition.objectType.as<ArtifactID>()))
  1590. return true;
  1591. }
  1592. if(condition.condition == EventCondition::IS_HUMAN)
  1593. return true;
  1594. return false;
  1595. };
  1596. if(event.trigger.test(testFunctor))
  1597. return true;
  1598. }
  1599. return false;
  1600. }
  1601. void CGHeroInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance & stack) const
  1602. {
  1603. TConstBonusListPtr lista = getBonusesOfType(BonusType::SPECIAL_UPGRADE, BonusSubtypeID(stack.getId()));
  1604. for(const auto & it : *lista)
  1605. {
  1606. auto nid = CreatureID(it->additionalInfo[0]);
  1607. if (nid != stack.getId()) //in very specific case the upgrade is available by default (?)
  1608. {
  1609. info.addUpgrade(nid, stack.getType());
  1610. }
  1611. }
  1612. }
  1613. bool CGHeroInstance::isCampaignYog() const
  1614. {
  1615. const StartInfo *si = cb->getStartInfo();
  1616. // it would be nice to find a way to move this hack to config/mapOverrides.json
  1617. if(!si || !si->campState)
  1618. return false;
  1619. std::string campaign = si->campState->getFilename();
  1620. if (!boost::starts_with(campaign, "DATA/YOG")) // "Birth of a Barbarian"
  1621. return false;
  1622. if (getHeroTypeID() != HeroTypeID::SOLMYR) // Yog (based on Solmyr)
  1623. return false;
  1624. return true;
  1625. }
  1626. bool CGHeroInstance::isCampaignGem() const
  1627. {
  1628. const StartInfo *si = cb->getStartInfo();
  1629. // it would be nice to find a way to move this hack to config/mapOverrides.json
  1630. if(!si || !si->campState)
  1631. return false;
  1632. std::string campaign = si->campState->getFilename();
  1633. if (!boost::starts_with(campaign, "DATA/GEM") && !boost::starts_with(campaign, "DATA/FINAL")) // "New Beginning" and "Unholy Alliance"
  1634. return false;
  1635. if (getHeroTypeID() != HeroTypeID::GEM) // Yog (based on Solmyr)
  1636. return false;
  1637. return true;
  1638. }
  1639. ResourceSet CGHeroInstance::dailyIncome() const
  1640. {
  1641. ResourceSet income;
  1642. for (GameResID k : GameResID::ALL_RESOURCES())
  1643. income[k] += valOfBonuses(BonusType::GENERATE_RESOURCE, BonusSubtypeID(k));
  1644. const auto & playerSettings = cb->getPlayerSettings(getOwner());
  1645. income.applyHandicap(playerSettings->handicap.percentIncome);
  1646. return income;
  1647. }
  1648. std::vector<CreatureID> CGHeroInstance::providedCreatures() const
  1649. {
  1650. return {};
  1651. }
  1652. const IOwnableObject * CGHeroInstance::asOwnable() const
  1653. {
  1654. return this;
  1655. }
  1656. int CGHeroInstance::getBasePrimarySkillValue(PrimarySkill which) const
  1657. {
  1658. std::string cachingStr = "CGHeroInstance::getBasePrimarySkillValue" + std::to_string(which.getNum());
  1659. auto selector = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(which)).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1660. auto minSkillValue = LIBRARY->engineSettings()->getVectorValue(EGameSettings::HEROES_MINIMAL_PRIMARY_SKILLS, which.getNum());
  1661. return std::max(valOfBonuses(selector, cachingStr), minSkillValue);
  1662. }
  1663. VCMI_LIB_NAMESPACE_END