CGHeroInstance.cpp 49 KB

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