CGHeroInstance.cpp 49 KB

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