CGHeroInstance.cpp 41 KB

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