CGHeroInstance.cpp 45 KB

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