CGHeroInstance.cpp 44 KB

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