CGHeroInstance.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 "CObjectHandler.h"
  13. #include "CArmedInstance.h"
  14. #include "../CArtHandler.h" // For CArtifactSet
  15. #include "../CRandomGenerator.h"
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. class CHero;
  18. class CGBoat;
  19. class CGTownInstance;
  20. class CMap;
  21. struct TerrainTile;
  22. struct TurnInfo;
  23. class CGHeroPlaceholder : public CGObjectInstance
  24. {
  25. public:
  26. //subID stores id of hero type. If it's 0xff then following field is used
  27. ui8 power;
  28. template <typename Handler> void serialize(Handler &h, const int version)
  29. {
  30. h & static_cast<CGObjectInstance&>(*this);
  31. h & power;
  32. }
  33. };
  34. class DLL_LINKAGE CGHeroInstance : public CArmedInstance, public IBoatGenerator, public CArtifactSet, public spells::Caster
  35. {
  36. // We serialize heroes into JSON for crossover
  37. friend class CCampaignState;
  38. friend class CMapLoaderH3M;
  39. friend class CMapFormatJson;
  40. private:
  41. std::set<SpellID> spells; //known spells (spell IDs)
  42. mutable int lowestCreatureSpeed;
  43. public:
  44. //////////////////////////////////////////////////////////////////////////
  45. //format: 123
  46. // 8 4
  47. // 765
  48. ui8 moveDir;
  49. mutable ui8 tacticFormationEnabled;
  50. //////////////////////////////////////////////////////////////////////////
  51. ConstTransitivePtr<CHero> type;
  52. TExpType exp; //experience points
  53. ui32 level; //current level of hero
  54. si32 portrait; //may be custom
  55. si32 mana; // remaining spell points
  56. 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
  57. ui32 movement; //remaining movement points
  58. ui8 sex;
  59. std::string nameCustom;
  60. std::string biographyCustom;
  61. bool inTownGarrison; // if hero is in town garrison
  62. ConstTransitivePtr<CGTownInstance> visitedTown; //set if hero is visiting town or in the town garrison
  63. ConstTransitivePtr<CCommanderInstance> commander;
  64. const CGBoat * boat = nullptr; //set to CGBoat when sailing
  65. static constexpr si32 UNINITIALIZED_PORTRAIT = -1;
  66. static constexpr si32 UNINITIALIZED_MANA = -1;
  67. static constexpr ui32 UNINITIALIZED_MOVEMENT = -1;
  68. static constexpr TExpType UNINITIALIZED_EXPERIENCE = std::numeric_limits<TExpType>::max();
  69. //std::vector<const CArtifact*> artifacts; //hero's artifacts from bag
  70. //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
  71. std::set<ObjectInstanceID> visitedObjects;
  72. struct DLL_LINKAGE Patrol
  73. {
  74. Patrol(){patrolling=false;initialPos=int3();patrolRadius=-1;};
  75. bool patrolling;
  76. int3 initialPos;
  77. ui32 patrolRadius;
  78. template <typename Handler> void serialize(Handler &h, const int version)
  79. {
  80. h & patrolling;
  81. h & initialPos;
  82. h & patrolRadius;
  83. }
  84. } patrol;
  85. // deprecated - used only for loading of old saves
  86. struct HeroSpecial : CBonusSystemNode
  87. {
  88. bool growsWithLevel;
  89. HeroSpecial(){growsWithLevel = false;};
  90. template <typename Handler> void serialize(Handler &h, const int version)
  91. {
  92. h & static_cast<CBonusSystemNode&>(*this);
  93. h & growsWithLevel;
  94. }
  95. };
  96. struct DLL_LINKAGE SecondarySkillsInfo
  97. {
  98. //skills are determined, initialized at map start
  99. //FIXME remove mutable
  100. mutable CRandomGenerator rand;
  101. ui8 magicSchoolCounter;
  102. ui8 wisdomCounter;
  103. SecondarySkillsInfo();
  104. void resetMagicSchoolCounter();
  105. void resetWisdomCounter();
  106. template <typename Handler> void serialize(Handler &h, const int version)
  107. {
  108. h & magicSchoolCounter;
  109. h & wisdomCounter;
  110. h & rand;
  111. }
  112. } skillsInfo;
  113. inline bool isInitialized() const
  114. { // has this hero been on the map at least once?
  115. return movement != UNINITIALIZED_MOVEMENT && mana != UNINITIALIZED_MANA;
  116. }
  117. //int3 getSightCenter() const; //"center" tile from which the sight distance is calculated
  118. int getSightRadius() const override; //sight distance (should be used if player-owned structure)
  119. //////////////////////////////////////////////////////////////////////////
  120. int getBoatType() const override; //0 - evil (if a ship can be evil...?), 1 - good, 2 - neutral
  121. void getOutOffsets(std::vector<int3> &offsets) const override; //offsets to obj pos when we boat can be placed
  122. //////////////////////////////////////////////////////////////////////////
  123. std::string getBiographyTranslated() const;
  124. std::string getNameTranslated() const;
  125. private:
  126. std::string getNameTextID() const;
  127. std::string getBiographyTextID() const;
  128. public:
  129. bool hasSpellbook() const;
  130. int maxSpellLevel() const;
  131. void addSpellToSpellbook(const SpellID & spell);
  132. void removeSpellFromSpellbook(const SpellID & spell);
  133. bool spellbookContainsSpell(const SpellID & spell) const;
  134. void removeSpellbook();
  135. const std::set<SpellID> & getSpellsInSpellbook() const;
  136. EAlignment::EAlignment getAlignment() const;
  137. bool needsLastStack()const override;
  138. ui32 getTileCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const; //move cost - applying pathfinding skill, road and terrain modifiers. NOT includes diagonal move penalty, last move levelling
  139. TerrainId getNativeTerrain() const;
  140. int getLowestCreatureSpeed() const;
  141. si32 manaRegain() const; //how many points of mana can hero regain "naturally" in one day
  142. si32 getManaNewTurn() const; //calculate how much mana this hero is going to have the next day
  143. int getCurrentLuck(int stack=-1, bool town=false) const;
  144. int32_t getSpellCost(const spells::Spell * sp) const; //do not use during battles -> bonuses from army would be ignored
  145. bool canLearnSpell(const spells::Spell * spell) const;
  146. 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
  147. /// convert given position between map position (CGObjectInstance::pos) and visitable position used for hero interactions
  148. int3 convertToVisitablePos(const int3 & position) const;
  149. int3 convertFromVisitablePos(const int3 & position) const;
  150. // ----- primary and secondary skill, experience, level handling -----
  151. /// Returns true if hero has lower level than should upon his experience.
  152. bool gainsLevel() const;
  153. /// Returns the next primary skill on level up. Can only be called if hero can gain a level up.
  154. PrimarySkill::PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const;
  155. /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up.
  156. boost::optional<SecondarySkill> nextSecondarySkill(CRandomGenerator & rand) const;
  157. /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up.
  158. std::vector<SecondarySkill> getLevelUpProposedSecondarySkills() const;
  159. ui8 getSecSkillLevel(const SecondarySkill & skill) const; //0 - no skill
  160. /// Returns true if hero has free secondary skill slot.
  161. bool canLearnSkill() const;
  162. bool canLearnSkill(const SecondarySkill & which) const;
  163. void setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs);
  164. void setSecSkillLevel(const SecondarySkill & which, int val, bool abs); // abs == 0 - changes by value; 1 - sets to value
  165. void levelUp(const std::vector<SecondarySkill> & skills);
  166. int maxMovePoints(bool onLand) const;
  167. //cached version is much faster, TurnInfo construction is costly
  168. int maxMovePointsCached(bool onLand, const TurnInfo * ti) const;
  169. //update army movement bonus
  170. void updateArmyMovementBonus(bool onLand, const TurnInfo * ti) const;
  171. int movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark = false, const TurnInfo * ti = nullptr) const;
  172. double getFightingStrength() const; // takes attack / defense skill into account
  173. double getMagicStrength() const; // takes knowledge / spell power skill into account
  174. double getHeroStrength() const; // includes fighting and magic strength
  175. ui64 getTotalStrength() const; // includes fighting strength and army strength
  176. TExpType calculateXp(TExpType exp) const; //apply learning skill
  177. CStackBasicDescriptor calculateNecromancy (const BattleResult &battleResult) const;
  178. void showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const;
  179. EDiggingStatus diggingStatus() const;
  180. //////////////////////////////////////////////////////////////////////////
  181. void setType(si32 ID, si32 subID) override;
  182. void initHero(CRandomGenerator & rand);
  183. void initHero(CRandomGenerator & rand, const HeroTypeID & SUBID);
  184. void putArtifact(ArtifactPosition pos, CArtifactInstance * art) override;
  185. void putInBackpack(CArtifactInstance *art);
  186. void initExp(CRandomGenerator & rand);
  187. void initArmy(CRandomGenerator & rand, IArmyDescriptor *dst = nullptr);
  188. //void giveArtifact (ui32 aid);
  189. void pushPrimSkill(PrimarySkill::PrimarySkill which, int val);
  190. ui8 maxlevelsToMagicSchool() const;
  191. ui8 maxlevelsToWisdom() const;
  192. void recreateSecondarySkillsBonuses();
  193. void updateSkillBonus(const SecondarySkill & which, int val);
  194. bool hasVisions(const CGObjectInstance * target, const int subtype) const;
  195. /// If this hero perishes, the scenario is failed
  196. bool isMissionCritical() const;
  197. CGHeroInstance();
  198. virtual ~CGHeroInstance();
  199. PlayerColor getOwner() const override;
  200. ///ArtBearer
  201. ArtBearer::ArtBearer bearerType() const override;
  202. ///IBonusBearer
  203. CBonusSystemNode & whereShouldBeAttached(CGameState * gs) override;
  204. std::string nodeName() const override;
  205. si32 manaLimit() const override;
  206. CBonusSystemNode * whereShouldBeAttachedOnSiege(const bool isBattleOutsideTown) const;
  207. CBonusSystemNode * whereShouldBeAttachedOnSiege(CGameState * gs);
  208. ///spells::Caster
  209. int32_t getCasterUnitId() const override;
  210. int32_t getSpellSchoolLevel(const spells::Spell * spell, int32_t * outSelectedSchool = nullptr) const override;
  211. int64_t getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const override;
  212. int64_t getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const override;
  213. int32_t getEffectLevel(const spells::Spell * spell) const override;
  214. int32_t getEffectPower(const spells::Spell * spell) const override;
  215. int32_t getEnchantPower(const spells::Spell * spell) const override;
  216. int64_t getEffectValue(const spells::Spell * spell) const override;
  217. PlayerColor getCasterOwner() const override;
  218. void getCasterName(MetaString & text) const override;
  219. void getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const override;
  220. void spendMana(ServerCallback * server, const int spellCost) const override;
  221. void deserializationFix();
  222. void initObj(CRandomGenerator & rand) override;
  223. void onHeroVisit(const CGHeroInstance * h) const override;
  224. std::string getObjectName() const override;
  225. void afterAddToMap(CMap * map) override;
  226. void afterRemoveFromMap(CMap * map) override;
  227. void updateFrom(const JsonNode & data) override;
  228. BattleField getBattlefield() const override;
  229. protected:
  230. void setPropertyDer(ui8 what, ui32 val) override;//synchr
  231. ///common part of hero instance and hero definition
  232. void serializeCommonOptions(JsonSerializeFormat & handler);
  233. void serializeJsonOptions(JsonSerializeFormat & handler) override;
  234. private:
  235. void levelUpAutomatically(CRandomGenerator & rand);
  236. public:
  237. std::string getHeroTypeName() const;
  238. void setHeroTypeName(const std::string & identifier);
  239. void serializeJsonDefinition(JsonSerializeFormat & handler);
  240. template <typename Handler> void serialize(Handler &h, const int version)
  241. {
  242. h & static_cast<CArmedInstance&>(*this);
  243. h & static_cast<CArtifactSet&>(*this);
  244. h & exp;
  245. h & level;
  246. h & nameCustom;
  247. h & biographyCustom;
  248. h & portrait;
  249. h & mana;
  250. h & secSkills;
  251. h & movement;
  252. h & sex;
  253. h & inTownGarrison;
  254. h & spells;
  255. h & patrol;
  256. h & moveDir;
  257. h & skillsInfo;
  258. h & visitedTown;
  259. h & boat;
  260. h & type;
  261. h & commander;
  262. h & visitedObjects;
  263. BONUS_TREE_DESERIALIZATION_FIX
  264. }
  265. };
  266. VCMI_LIB_NAMESPACE_END