CGHeroInstance.cpp 50 KB

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