CGHeroInstance.cpp 42 KB

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