CGHeroInstance.cpp 47 KB

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