CGHeroInstance.cpp 54 KB

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