CGHeroInstance.cpp 46 KB

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