CGHeroInstance.cpp 41 KB

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