CCreatureSet.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. * CCreatureSet.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 "CCreatureHandler.h"
  12. #include "GameConstants.h"
  13. #include "bonuses/Bonus.h"
  14. #include "bonuses/BonusCache.h"
  15. #include "bonuses/CBonusSystemNode.h"
  16. #include "callback/GameCallbackHolder.h"
  17. #include "serializer/Serializeable.h"
  18. #include "mapObjects/CGObjectInstance.h"
  19. #include "entities/artifact/CArtifactSet.h"
  20. #include <vcmi/Entity.h>
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. class JsonNode;
  23. class CCreature;
  24. class CGHeroInstance;
  25. class CArmedInstance;
  26. class CCreatureArtifactSet;
  27. class JsonSerializeFormat;
  28. class DLL_LINKAGE CStackBasicDescriptor
  29. {
  30. CreatureID typeID;
  31. TQuantity count = -1; //exact quantity or quantity ID from CCreature::getQuantityID when getting info about enemy army
  32. public:
  33. CStackBasicDescriptor();
  34. CStackBasicDescriptor(const CreatureID & id, TQuantity Count);
  35. CStackBasicDescriptor(const CCreature *c, TQuantity Count);
  36. virtual ~CStackBasicDescriptor() = default;
  37. const Creature * getType() const;
  38. const CCreature * getCreature() const;
  39. CreatureID getId() const;
  40. TQuantity getCount() const;
  41. virtual void setType(const CCreature * c);
  42. virtual void setCount(TQuantity amount);
  43. friend bool operator== (const CStackBasicDescriptor & l, const CStackBasicDescriptor & r);
  44. template <typename Handler> void serialize(Handler &h)
  45. {
  46. if(h.saving)
  47. {
  48. h & typeID;
  49. }
  50. else
  51. {
  52. CreatureID creatureID;
  53. h & creatureID;
  54. if(creatureID != CreatureID::NONE)
  55. setType(creatureID.toCreature());
  56. }
  57. h & count;
  58. }
  59. void serializeJson(JsonSerializeFormat & handler);
  60. };
  61. class DLL_LINKAGE CStackInstance : public CBonusSystemNode, public CStackBasicDescriptor, public CArtifactSet, public ACreature, public GameCallbackHolder
  62. {
  63. BonusValueCache nativeTerrain;
  64. BonusValueCache initiative;
  65. CArmedInstance * armyInstance = nullptr; //stack must be part of some army, army must be part of some object
  66. IGameInfoCallback * getCallback() const final { return cb; }
  67. TExpType totalExperience;//commander needs same amount of exp as hero
  68. public:
  69. struct RandomStackInfo
  70. {
  71. uint8_t level;
  72. uint8_t upgrade;
  73. };
  74. // helper variable used during loading map, when object (hero or town) have creatures that must have same alignment.
  75. std::optional<RandomStackInfo> randomStack;
  76. CArmedInstance * getArmy();
  77. const CArmedInstance * getArmy() const; //stack must be part of some army, army must be part of some object
  78. void setArmy(CArmedInstance *ArmyObj);
  79. TExpType getTotalExperience() const;
  80. TExpType getAverageExperience() const;
  81. virtual bool canGainExperience() const;
  82. template <typename Handler> void serialize(Handler &h)
  83. {
  84. h & static_cast<CBonusSystemNode&>(*this);
  85. h & static_cast<CStackBasicDescriptor&>(*this);
  86. h & static_cast<CArtifactSet&>(*this);
  87. if (h.hasFeature(Handler::Version::STACK_INSTANCE_ARMY_FIX))
  88. {
  89. // no-op
  90. }
  91. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  92. {
  93. ObjectInstanceID dummyID;
  94. h & dummyID;
  95. }
  96. else
  97. {
  98. std::shared_ptr<CGObjectInstance> army;
  99. h & army;
  100. }
  101. h & totalExperience;
  102. if (!h.hasFeature(Handler::Version::STACK_INSTANCE_EXPERIENCE_FIX))
  103. {
  104. totalExperience *= getCount();
  105. }
  106. }
  107. void serializeJson(JsonSerializeFormat & handler);
  108. //overrides CBonusSystemNode
  109. std::string bonusToString(const std::shared_ptr<Bonus>& bonus) const override; // how would bonus description look for this particular type of node
  110. ImagePath bonusToGraphics(const std::shared_ptr<Bonus> & bonus) const; //file name of graphics from StackSkills , in future possibly others
  111. //IConstBonusProvider
  112. const IBonusBearer* getBonusBearer() const override;
  113. //INativeTerrainProvider
  114. FactionID getFactionID() const override;
  115. virtual ui64 getPower() const;
  116. /// Returns total market value of resources needed to recruit this unit
  117. virtual ui64 getMarketValue() const;
  118. CCreature::CreatureQuantityId getQuantityID() const;
  119. std::string getQuantityTXT(bool capitalized = true) const;
  120. virtual int getExpRank() const;
  121. virtual int getLevel() const; //different for regular stack and commander
  122. CreatureID getCreatureID() const; //-1 if not available
  123. std::string getName() const; //plural or singular
  124. CStackInstance(IGameInfoCallback *cb);
  125. CStackInstance(IGameInfoCallback *cb, BonusNodeType nodeType, bool isHypothetic = false);
  126. CStackInstance(IGameInfoCallback *cb, const CreatureID & id, TQuantity count, bool isHypothetic = false);
  127. virtual ~CStackInstance() = default;
  128. void setType(const CreatureID & creID);
  129. void setType(const CCreature * c) final;
  130. void setCount(TQuantity amount) final;
  131. /// Gives specified amount of stack experience that will not be scaled by unit size
  132. void giveAverageStackExperience(TExpType exp);
  133. void giveTotalStackExperience(TExpType exp);
  134. bool valid(bool allowUnrandomized) const;
  135. ArtPlacementMap putArtifact(const ArtifactPosition & pos, const CArtifactInstance * art) override;//from CArtifactSet
  136. void removeArtifact(const ArtifactPosition & pos) override;
  137. ArtBearer bearerType() const override; //from CArtifactSet
  138. std::string nodeName() const override; //from CBonusSystemnode
  139. PlayerColor getOwner() const override;
  140. int32_t getInitiative(int turn = 0) const final;
  141. TerrainId getNativeTerrain() const final;
  142. TerrainId getCurrentTerrain() const;
  143. };
  144. class DLL_LINKAGE CCommanderInstance : public CStackInstance
  145. {
  146. public:
  147. //TODO: what if Commander is not a part of creature set?
  148. //commander class is determined by its base creature
  149. ui8 alive; //maybe change to bool when breaking save compatibility?
  150. ui8 level; //required only to count callbacks
  151. std::string name; // each Commander has different name
  152. std::vector <ui8> secondarySkills; //ID -> level
  153. std::set <ui8> specialSkills;
  154. //std::vector <CArtifactInstance *> arts;
  155. CCommanderInstance(IGameInfoCallback *cb);
  156. CCommanderInstance(IGameInfoCallback *cb, const CreatureID & id);
  157. void setAlive (bool alive);
  158. void levelUp ();
  159. bool canGainExperience() const override;
  160. bool gainsLevel() const; //true if commander has lower level than should upon his experience
  161. ui64 getPower() const override {return 0;};
  162. int getExpRank() const override;
  163. int getLevel() const override;
  164. ArtBearer bearerType() const override; //from CArtifactSet
  165. template <typename Handler> void serialize(Handler &h)
  166. {
  167. h & static_cast<CStackInstance&>(*this);
  168. h & alive;
  169. h & level;
  170. h & name;
  171. h & secondarySkills;
  172. h & specialSkills;
  173. }
  174. };
  175. using TSlots = std::map<SlotID, std::unique_ptr<CStackInstance>>;
  176. using TSimpleSlots = std::map<SlotID, std::pair<CreatureID, TQuantity>>;
  177. using TPairCreatureSlot = std::pair<const CCreature *, SlotID>;
  178. using TMapCreatureSlot = std::map<const CCreature *, SlotID>;
  179. struct DLL_LINKAGE CreatureSlotComparer
  180. {
  181. bool operator()(const TPairCreatureSlot & lhs, const TPairCreatureSlot & rhs);
  182. };
  183. using TCreatureQueue = std::priority_queue<TPairCreatureSlot, std::vector<TPairCreatureSlot>, CreatureSlotComparer>;
  184. class IArmyDescriptor
  185. {
  186. public:
  187. virtual void clearSlots() = 0;
  188. virtual bool setCreature(SlotID slot, CreatureID cre, TQuantity count) = 0;
  189. };
  190. //simplified version of CCreatureSet
  191. class DLL_LINKAGE CSimpleArmy : public IArmyDescriptor
  192. {
  193. public:
  194. TSimpleSlots army;
  195. void clearSlots() override;
  196. bool setCreature(SlotID slot, CreatureID cre, TQuantity count) override;
  197. operator bool() const;
  198. template <typename Handler> void serialize(Handler &h)
  199. {
  200. h & army;
  201. }
  202. };
  203. namespace NArmyFormation
  204. {
  205. static const std::vector<std::string> names{ "wide", "tight" };
  206. }
  207. class DLL_LINKAGE CCreatureSet : public IArmyDescriptor, public virtual Serializeable //seven combined creatures
  208. {
  209. CCreatureSet(const CCreatureSet &) = delete;
  210. CCreatureSet &operator=(const CCreatureSet&);
  211. public:
  212. TSlots stacks; //slots[slot_id]->> pair(creature_id,creature_quantity)
  213. EArmyFormation formation = EArmyFormation::LOOSE; //0 - wide, 1 - tight
  214. CCreatureSet() = default; //Should be here to avoid compile errors
  215. virtual ~CCreatureSet();
  216. virtual void armyChanged();
  217. const CStackInstance & operator[](const SlotID & slot) const;
  218. const TSlots &Slots() const {return stacks;}
  219. void addToSlot(const SlotID & slot, const CreatureID & cre, TQuantity count, bool allowMerging = true); //Adds stack to slot. Slot must be empty or with same type creature
  220. void addToSlot(const SlotID & slot, std::unique_ptr<CStackInstance> stack, bool allowMerging = true); //Adds stack to slot. Slot must be empty or with same type creature
  221. void clearSlots() override;
  222. void setFormation(EArmyFormation tight);
  223. virtual CArmedInstance * getArmy() { return nullptr; }
  224. virtual const CArmedInstance * getArmy() const { return nullptr; }
  225. //basic operations
  226. void putStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack); //adds new stack to the army, slot must be empty
  227. void setStackCount(const SlotID & slot, TQuantity count); //stack must exist!
  228. std::unique_ptr<CStackInstance> detachStack(const SlotID & slot); //removes stack from army but doesn't destroy it (so it can be moved somewhere else or safely deleted)
  229. void setStackType(const SlotID & slot, const CreatureID & type);
  230. /// Give specified amount of experience to all units in army
  231. /// Amount of granted experience is scaled by unit stack size
  232. void giveAverageStackExperience(TExpType exp);
  233. /// Give specified amount of experience to unit in specified slot
  234. /// Amount of granted experience is not scaled by unit stack size
  235. void giveTotalStackExperience(const SlotID & slot, TExpType exp);
  236. /// Erased stack from specified slot. Slot must be non-empty
  237. void eraseStack(const SlotID & slot);
  238. /// Joins stack into stack that occupies targeted slot.
  239. /// Slot must be non-empty and contain same creature type
  240. void joinStack(const SlotID & slot, std::unique_ptr<CStackInstance> stack); //adds new stack to the existing stack of the same type
  241. /// Splits off some units of specified stack and returns newly created stack
  242. /// Slot must be non-empty and contain more units that split quantity
  243. std::unique_ptr<CStackInstance> splitStack(const SlotID & slot, TQuantity toSplit);
  244. void changeStackCount(const SlotID & slot, TQuantity toAdd); //stack must exist!
  245. bool setCreature (SlotID slot, CreatureID type, TQuantity quantity) override; //replaces creature in stack; slots 0 to 6, if quantity=0 erases stack
  246. void setToArmy(CSimpleArmy &src); //erases all our army and moves stacks from src to us; src MUST NOT be an armed object! WARNING: use it wisely. Or better do not use at all.
  247. const CStackInstance & getStack(const SlotID & slot) const; //stack must exist
  248. CStackInstance * getStackPtr(const SlotID & slot) const; //if stack doesn't exist, returns nullptr
  249. const CCreature * getCreature(const SlotID & slot) const; //workaround of map issue;
  250. int getStackCount(const SlotID & slot) const;
  251. TExpType getStackTotalExperience(const SlotID & slot) const;
  252. TExpType getStackAverageExperience(const SlotID & slot) const;
  253. SlotID findStack(const CStackInstance *stack) const; //-1 if none
  254. SlotID getSlotFor(const CreatureID & creature, ui32 slotsAmount = GameConstants::ARMY_SIZE) const; //returns -1 if no slot available
  255. SlotID getSlotFor(const CCreature *c, ui32 slotsAmount = GameConstants::ARMY_SIZE) const; //returns -1 if no slot available
  256. bool hasCreatureSlots(const CCreature * c, const SlotID & exclude) const;
  257. std::vector<SlotID> getCreatureSlots(const CCreature * c, const SlotID & exclude, TQuantity ignoreAmount = -1) const;
  258. bool isCreatureBalanced(const CCreature* c, TQuantity ignoreAmount = 1) const; // Check if the creature is evenly distributed across slots
  259. SlotID getFreeSlot(ui32 slotsAmount = GameConstants::ARMY_SIZE) const; //returns first free slot
  260. std::vector<SlotID> getFreeSlots(ui32 slotsAmount = GameConstants::ARMY_SIZE) const;
  261. std::queue<SlotID> getFreeSlotsQueue(ui32 slotsAmount = GameConstants::ARMY_SIZE) const;
  262. TMapCreatureSlot getCreatureMap() const;
  263. TCreatureQueue getCreatureQueue(const SlotID & exclude) const;
  264. bool mergeableStacks(std::pair<SlotID, SlotID> & out, const SlotID & preferable = SlotID()) const; //looks for two same stacks, returns slot positions;
  265. bool validTypes(bool allowUnrandomized = false) const; //checks if all types of creatures are set properly
  266. bool slotEmpty(const SlotID & slot) const;
  267. int stacksCount() const;
  268. virtual bool needsLastStack() const; //true if last stack cannot be taken
  269. ui64 getArmyStrength(int fortLevel = 0) const; //sum of AI values of creatures
  270. ui64 getArmyCost() const; //sum of cost of creatures
  271. ui64 getPower(const SlotID & slot) const; //value of specific stack
  272. std::string getRoughAmount(const SlotID & slot, int mode = 0) const; //rough size of specific stack
  273. std::string getArmyDescription() const;
  274. bool hasStackAtSlot(const SlotID & slot) const;
  275. bool contains(const CStackInstance *stack) const;
  276. bool canBeMergedWith(const CCreatureSet &cs, bool allowMergingStacks = true) const;
  277. /// Returns true if this creature set contains all listed units
  278. /// If requireLastStack is true, then this function will also
  279. /// require presence of any unit other than requested (or more units than requested)
  280. bool hasUnits(const std::vector<CStackBasicDescriptor> & units, bool requireLastStack = true) const;
  281. template <typename Handler> void serialize(Handler &h)
  282. {
  283. h & stacks;
  284. h & formation;
  285. }
  286. void serializeJson(JsonSerializeFormat & handler, const std::string & armyFieldName, const std::optional<int> fixedSize = std::nullopt);
  287. operator bool() const
  288. {
  289. return !stacks.empty();
  290. }
  291. };
  292. VCMI_LIB_NAMESPACE_END