CGHeroInstance.cpp 44 KB

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