CGHeroInstance.cpp 51 KB

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