CGHeroInstance.cpp 45 KB

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