CGHeroInstance.cpp 44 KB

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