CGHeroInstance.cpp 45 KB

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