CGHeroInstance.cpp 45 KB

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