CGHeroInstance.cpp 45 KB

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