CGHeroInstance.cpp 50 KB

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