CGHeroInstance.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * CGHeroInstance.h, 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. #pragma once
  11. #include <vcmi/spells/Caster.h>
  12. #include "CArmedInstance.h"
  13. #include "IOwnableObject.h"
  14. #include "../bonuses/BonusCache.h"
  15. #include "../entities/hero/EHeroGender.h"
  16. #include "../CArtHandler.h" // For CArtifactSet
  17. VCMI_LIB_NAMESPACE_BEGIN
  18. class CHero;
  19. class CGBoat;
  20. class CGTownInstance;
  21. class CMap;
  22. class UpgradeInfo;
  23. class TurnInfo;
  24. struct TerrainTile;
  25. struct TurnInfoCache;
  26. class DLL_LINKAGE CGHeroPlaceholder : public CGObjectInstance
  27. {
  28. public:
  29. using CGObjectInstance::CGObjectInstance;
  30. /// if this is placeholder by power, then power rank of desired hero
  31. std::optional<ui8> powerRank;
  32. /// if this is placeholder by type, then hero type of desired hero
  33. std::optional<HeroTypeID> heroType;
  34. template <typename Handler> void serialize(Handler &h)
  35. {
  36. h & static_cast<CGObjectInstance&>(*this);
  37. h & powerRank;
  38. h & heroType;
  39. }
  40. protected:
  41. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  42. };
  43. class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster, public AFactionMember, public ICreatureUpgrader, public IOwnableObject
  44. {
  45. // We serialize heroes into JSON for crossover
  46. friend class CampaignState;
  47. friend class CMapLoaderH3M;
  48. friend class CMapFormatJson;
  49. private:
  50. PrimarySkillsCache primarySkills;
  51. MagicSchoolMasteryCache magicSchoolMastery;
  52. BonusValueCache manaPerKnowledgeCached;
  53. std::unique_ptr<TurnInfoCache> turnInfoCache;
  54. std::set<SpellID> spells; //known spells (spell IDs)
  55. ui32 movement; //remaining movement points
  56. public:
  57. //////////////////////////////////////////////////////////////////////////
  58. //format: 123
  59. // 8 4
  60. // 765
  61. ui8 moveDir;
  62. mutable ui8 tacticFormationEnabled;
  63. //////////////////////////////////////////////////////////////////////////
  64. TExpType exp; //experience points
  65. ui32 level; //current level of hero
  66. /// If not NONE - then hero should use portrait from referenced hero type
  67. HeroTypeID customPortraitSource;
  68. si32 mana; // remaining spell points
  69. std::vector<std::pair<SecondarySkill,ui8> > secSkills; //first - ID of skill, second - level of skill (1 - basic, 2 - adv., 3 - expert); if hero has ability (-1, -1) it meansthat it should have default secondary abilities
  70. EHeroGender gender;
  71. std::string nameCustomTextId;
  72. std::string biographyCustomTextId;
  73. bool inTownGarrison; // if hero is in town garrison
  74. ConstTransitivePtr<CGTownInstance> visitedTown; //set if hero is visiting town or in the town garrison
  75. ConstTransitivePtr<CCommanderInstance> commander;
  76. const CGBoat * boat = nullptr; //set to CGBoat when sailing
  77. static constexpr si32 UNINITIALIZED_MANA = -1;
  78. static constexpr ui32 UNINITIALIZED_MOVEMENT = -1;
  79. static constexpr auto UNINITIALIZED_EXPERIENCE = std::numeric_limits<TExpType>::max();
  80. static const ui32 NO_PATROLLING;
  81. //std::vector<const CArtifact*> artifacts; //hero's artifacts from bag
  82. //std::map<ui16, const CArtifact*> artifWorn; //map<position,artifact_id>; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
  83. std::set<ObjectInstanceID> visitedObjects;
  84. struct DLL_LINKAGE Patrol
  85. {
  86. bool patrolling{false};
  87. int3 initialPos;
  88. ui32 patrolRadius{NO_PATROLLING};
  89. template <typename Handler> void serialize(Handler &h)
  90. {
  91. h & patrolling;
  92. h & initialPos;
  93. h & patrolRadius;
  94. }
  95. } patrol;
  96. struct DLL_LINKAGE SecondarySkillsInfo
  97. {
  98. ui8 magicSchoolCounter;
  99. ui8 wisdomCounter;
  100. SecondarySkillsInfo();
  101. void resetMagicSchoolCounter();
  102. void resetWisdomCounter();
  103. template <typename Handler> void serialize(Handler &h)
  104. {
  105. h & magicSchoolCounter;
  106. h & wisdomCounter;
  107. }
  108. } skillsInfo;
  109. inline bool isInitialized() const
  110. { // has this hero been on the map at least once?
  111. return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
  112. }
  113. //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
  114. int getSightRadius() const override; //sight distance (should be used if player-owned structure)
  115. //////////////////////////////////////////////////////////////////////////
  116. BoatId getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
  117. void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
  118. const IObjectInterface * getObject() const override;
  119. //////////////////////////////////////////////////////////////////////////
  120. std::string getBiographyTranslated() const;
  121. std::string getBiographyTextID() const;
  122. std::string getNameTextID() const;
  123. std::string getNameTranslated() const;
  124. HeroTypeID getPortraitSource() const;
  125. int32_t getIconIndex() const;
  126. std::string getClassNameTranslated() const;
  127. std::string getClassNameTextID() const;
  128. bool hasSpellbook() const;
  129. int maxSpellLevel() const;
  130. void addSpellToSpellbook(const SpellID & spell);
  131. void removeSpellFromSpellbook(const SpellID & spell);
  132. bool spellbookContainsSpell(const SpellID & spell) const;
  133. void removeSpellbook();
  134. const std::set<SpellID> & getSpellsInSpellbook() const;
  135. EAlignment getAlignment() const;
  136. bool needsLastStack()const override;
  137. ResourceSet dailyIncome() const override;
  138. std::vector<CreatureID> providedCreatures() const override;
  139. const IOwnableObject * asOwnable() const final;
  140. //INativeTerrainProvider
  141. FactionID getFactionID() const override;
  142. TerrainId getNativeTerrain() const override;
  143. int getLowestCreatureSpeed() const;
  144. si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
  145. si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
  146. int getCurrentLuck(int stack=-1, bool town=false) const;
  147. int32_t getSpellCost(const spells::Spell * sp) const; //do not use during battles -> bonuses from army would be ignored
  148. bool canLearnSpell(const spells::Spell * spell, bool allowBanned = false) const;
  149. bool canCastThisSpell(const spells::Spell * spell) const; //determines if this hero can cast given spell; takes into account existing spell in spellbook, existing spellbook and artifact bonuses
  150. /// convert given position between map position (CGObjectInstance::pos) and visitable position used for hero interactions
  151. int3 convertToVisitablePos(const int3 & position) const;
  152. int3 convertFromVisitablePos(const int3 & position) const;
  153. // ----- primary and secondary skill, experience, level handling -----
  154. /// Returns true if hero has lower level than should upon his experience.
  155. bool gainsLevel() const;
  156. /// Returns the next primary skill on level up. Can only be called if hero can gain a level up.
  157. PrimarySkill nextPrimarySkill(vstd::RNG & rand) const;
  158. /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
  159. std::optional<SecondarySkill> nextSecondarySkill(vstd::RNG & rand) const;
  160. /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
  161. std::vector<SecondarySkill> getLevelUpProposedSecondarySkills(vstd::RNG & rand) const;
  162. ui8 getSecSkillLevel(const SecondarySkill & skill) const; //0 - no skill
  163. int getPrimSkillLevel(PrimarySkill id) const;
  164. /// Returns true if hero has free secondary skill slot.
  165. bool canLearnSkill() const;
  166. bool canLearnSkill(const SecondarySkill & which) const;
  167. void setPrimarySkill(PrimarySkill primarySkill, si64 value, ui8 abs);
  168. void setSecSkillLevel(const SecondarySkill & which, int val, bool abs); // abs == 0 - changes by value; 1 - sets to value
  169. void levelUp(const std::vector<SecondarySkill> & skills);
  170. /// returns base movement cost for movement between specific tiles. Does not accounts for diagonal movement or last tile exception
  171. ui32 getTileMovementCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const;
  172. void setMovementPoints(int points);
  173. int movementPointsRemaining() const;
  174. int movementPointsLimit(bool onLand) const;
  175. //cached version is much faster, TurnInfo construction is costly
  176. int movementPointsLimitCached(bool onLand, const TurnInfo * ti) const;
  177. int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const;
  178. std::unique_ptr<TurnInfo> getTurnInfo(int days) const;
  179. double getFightingStrength() const; // takes attack / defense skill into account
  180. double getMagicStrength() const; // takes knowledge / spell power skill but also current mana, whether the hero owns a spell-book and whether that books contains anything into account
  181. double getHeroStrength() const; // includes fighting and magic strength
  182. uint32_t getValueForCampaign() const;
  183. uint64_t getValueForDiplomacy() const;
  184. ui64 getTotalStrength() const; // includes fighting strength and army strength
  185. TExpType calculateXp(TExpType exp) const; //apply learning skill
  186. int getBasePrimarySkillValue(PrimarySkill which) const; //the value of a base-skill without items or temporary bonuses
  187. CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
  188. void showNecromancyDialog(const CStackBasicDescriptor &raisedStack, vstd::RNG & rand) const;
  189. EDiggingStatus diggingStatus() const;
  190. //////////////////////////////////////////////////////////////////////////
  191. const CHeroClass * getHeroClass() const;
  192. HeroClassID getHeroClassID() const;
  193. const CHero * getHeroType() const;
  194. HeroTypeID getHeroTypeID() const;
  195. void setHeroType(HeroTypeID type);
  196. void initObj(vstd::RNG & rand) override;
  197. void initHero(vstd::RNG & rand);
  198. void initHero(vstd::RNG & rand, const HeroTypeID & SUBID);
  199. ArtPlacementMap putArtifact(const ArtifactPosition & pos, CArtifactInstance * art) override;
  200. void removeArtifact(const ArtifactPosition & pos) override;
  201. void initExp(vstd::RNG & rand);
  202. void initArmy(vstd::RNG & rand, IArmyDescriptor *dst = nullptr);
  203. void pushPrimSkill(PrimarySkill which, int val);
  204. ui8 maxlevelsToMagicSchool() const;
  205. ui8 maxlevelsToWisdom() const;
  206. void recreateSecondarySkillsBonuses();
  207. void updateSkillBonus(const SecondarySkill & which, int val);
  208. void fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const override;
  209. bool hasVisions(const CGObjectInstance * target, BonusSubtypeID masteryLevel) const;
  210. /// If this hero perishes, the scenario is failed
  211. bool isMissionCritical() const;
  212. CGHeroInstance(IGameCallback *cb);
  213. virtual ~CGHeroInstance();
  214. PlayerColor getOwner() const override;
  215. ///ArtBearer
  216. ArtBearer::ArtBearer bearerType() const override;
  217. ///IBonusBearer
  218. CBonusSystemNode & whereShouldBeAttached(CGameState * gs) override;
  219. std::string nodeName() const override;
  220. si32 manaLimit() const override;
  221. ///IConstBonusProvider
  222. const IBonusBearer* getBonusBearer() const override;
  223. CBonusSystemNode * whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const;
  224. CBonusSystemNode * whereShouldBeAttachedOnSiege(CGameState * gs);
  225. ///spells::Caster
  226. int32_t getCasterUnitId() const override;
  227. int32_t getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool = nullptr) const override;
  228. int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
  229. int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;
  230. int32_t getEffectLevel(const spells::Spell * spell) const override;
  231. int32_t getEffectPower(const spells::Spell * spell) const override;
  232. int32_t getEnchantPower(const spells::Spell * spell) const override;
  233. int64_t getEffectValue(const spells::Spell * spell) const override;
  234. PlayerColor getCasterOwner() const override;
  235. const CGHeroInstance * getHeroCaster() const override;
  236. void getCasterName(MetaString & text) const override;
  237. void getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const override;
  238. void spendMana(ServerCallback * server, const int spellCost) const override;
  239. void attachToBoat(CGBoat* newBoat);
  240. void boatDeserializationFix();
  241. void deserializationFix();
  242. void updateAppearance();
  243. void pickRandomObject(vstd::RNG & rand) override;
  244. void onHeroVisit(const CGHeroInstance * h) const override;
  245. std::string getObjectName() const override;
  246. std::string getHoverText(PlayerColor player) const override;
  247. std::string getMovementPointsTextIfOwner(PlayerColor player) const;
  248. TObjectTypeHandler getObjectHandler() const override;
  249. void afterAddToMap(CMap * map) override;
  250. void afterRemoveFromMap(CMap * map) override;
  251. void updateFrom(const JsonNode & data) override;
  252. bool isCoastVisitable() const override;
  253. bool isBlockedVisitable() const override;
  254. BattleField getBattlefield() const override;
  255. bool isCampaignYog() const;
  256. bool isCampaignGem() const;
  257. protected:
  258. void setPropertyDer(ObjProperty what, ObjPropertyID identifier) override;//synchr
  259. ///common part of hero instance and hero definition
  260. void serializeCommonOptions(JsonSerializeFormat & handler);
  261. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  262. private:
  263. void levelUpAutomatically(vstd::RNG & rand);
  264. public:
  265. std::string getHeroTypeName() const;
  266. void setHeroTypeName(const std::string & identifier);
  267. void serializeJsonDefinition(JsonSerializeFormat & handler);
  268. template <typename Handler> void serialize(Handler &h)
  269. {
  270. h & static_cast<CArmedInstance&>(*this);
  271. h & static_cast<CArtifactSet&>(*this);
  272. h & exp;
  273. h & level;
  274. h & nameCustomTextId;
  275. h & biographyCustomTextId;
  276. h & customPortraitSource;
  277. h & mana;
  278. h & secSkills;
  279. h & movement;
  280. h & gender;
  281. h & inTownGarrison;
  282. h & spells;
  283. h & patrol;
  284. h & moveDir;
  285. h & skillsInfo;
  286. h & visitedTown;
  287. h & boat;
  288. if (h.version < Handler::Version::REMOVE_TOWN_PTR)
  289. {
  290. HeroTypeID type;
  291. bool isNull = false;
  292. h & isNull;
  293. if(!isNull)
  294. h & type;
  295. }
  296. h & commander;
  297. h & visitedObjects;
  298. BONUS_TREE_DESERIALIZATION_FIX
  299. }
  300. };
  301. VCMI_LIB_NAMESPACE_END