CMap.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * CMap.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 "CMapEvent.h"
  12. #include "CMapHeader.h"
  13. #include "TerrainTile.h"
  14. #include "MapTilesStorage.h"
  15. #include "../mapObjects/CGObjectInstance.h"
  16. #include "../callback/GameCallbackHolder.h"
  17. #include "../networkPacks/TradeItem.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. class CArtifactInstance;
  20. class CArtifactSet;
  21. class CGObjectInstance;
  22. class CGHeroInstance;
  23. class CCommanderInstance;
  24. class CGameState;
  25. class CGCreature;
  26. class CQuest;
  27. class CGTownInstance;
  28. class IModableArt;
  29. class IQuestObject;
  30. class CInputStream;
  31. class CMapEditManager;
  32. class JsonSerializeFormat;
  33. class IGameSettings;
  34. class GameSettings;
  35. struct TeleportChannel;
  36. enum class EGameSettings;
  37. /// The rumor struct consists of a rumor name and text.
  38. struct DLL_LINKAGE Rumor
  39. {
  40. std::string name;
  41. MetaString text;
  42. Rumor() = default;
  43. ~Rumor() = default;
  44. template <typename Handler>
  45. void serialize(Handler & h)
  46. {
  47. h & name;
  48. h & text;
  49. }
  50. void serializeJson(JsonSerializeFormat & handler);
  51. };
  52. /// The map contains the map header, the tiles of the terrain, objects, heroes, towns, rumors...
  53. class DLL_LINKAGE CMap : public CMapHeader, public GameCallbackHolder
  54. {
  55. friend class CSerializer;
  56. std::unique_ptr<GameSettings> gameSettings;
  57. /// All artifacts that exists on map, whether on map, in hero inventory, or stored in some object
  58. std::vector<std::shared_ptr<CArtifactInstance>> artInstances;
  59. /// All heroes that are currently free for recruitment in taverns and are not present on map
  60. std::vector<std::shared_ptr<CGHeroInstance> > heroesPool;
  61. /// Precomputed indices of all towns on map
  62. std::vector<ObjectInstanceID> towns;
  63. /// Precomputed indices of all heroes on map. Does not includes heroes in prisons
  64. std::vector<ObjectInstanceID> heroesOnMap;
  65. void deserializeHeroPool(const std::vector<std::shared_ptr<CGHeroInstance> > &);
  66. public:
  67. /// Central lists of items in game. Position of item in the vectors below is their (instance) id.
  68. /// TODO: make private
  69. std::vector<std::shared_ptr<CGObjectInstance>> objects;
  70. explicit CMap(IGameInfoCallback *cb);
  71. ~CMap();
  72. void initTerrain();
  73. CMapEditManager * getEditManager();
  74. inline TerrainTile & getTile(const int3 & tile);
  75. inline const TerrainTile & getTile(const int3 & tile) const;
  76. bool isCoastalTile(const int3 & pos) const;
  77. inline bool isInTheMap(const int3 & pos) const;
  78. bool canMoveBetween(const int3 &src, const int3 &dst) const;
  79. bool checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const;
  80. int3 guardingCreaturePosition (int3 pos) const;
  81. void calculateGuardingGreaturePositions();
  82. void calculateGuardingGreaturePositions(int3 topleft, int3 bottomright);
  83. void saveCompatibilityAddMissingArtifact(std::shared_ptr<CArtifactInstance> artifact);
  84. /// Creates instance of spell scroll artifact with provided spell
  85. CArtifactInstance * createScroll(const SpellID & spellId);
  86. /// Creates instance of requested artifact
  87. /// For combined artifact this method will also create alll required components
  88. /// For scrolls this method will also initialize its spell
  89. CArtifactInstance * createArtifact(const ArtifactID & artId, const SpellID & spellId = SpellID::NONE);
  90. /// Creates single instance of requested artifact
  91. /// Does NOT creates components for combined artifacts
  92. /// Does NOT initializes spell when spell scroll artifact is created
  93. CArtifactInstance * createArtifactComponent(const ArtifactID & artId);
  94. /// Returns pointer to requested Artifact Instance. Throws on invalid ID
  95. CArtifactInstance * getArtifactInstance(const ArtifactInstanceID & artifactID);
  96. /// Returns pointer to requested Artifact Instance. Throws on invalid ID
  97. const CArtifactInstance * getArtifactInstance(const ArtifactInstanceID & artifactID) const;
  98. /// Completely removes artifact instance from the game
  99. void eraseArtifactInstance(const ArtifactInstanceID art);
  100. void moveArtifactInstance(CArtifactSet & srcSet, const ArtifactPosition & srcSlot, CArtifactSet & dstSet, const ArtifactPosition & dstSlot);
  101. void putArtifactInstance(CArtifactSet & set, const ArtifactInstanceID art, const ArtifactPosition & slot);
  102. void removeArtifactInstance(CArtifactSet & set, const ArtifactPosition & slot);
  103. /// Generates unique string identifier for provided object instance
  104. void generateUniqueInstanceName(CGObjectInstance * target);
  105. /// Generates new, unique numeric identifier that can be used for creation of a new object
  106. ObjectInstanceID allocateUniqueInstanceID();
  107. /// Adds provided object to the map
  108. /// Throws on error, for example if object is already on map
  109. void addNewObject(std::shared_ptr<CGObjectInstance> obj);
  110. /// Moves anchor position of requested object to specified coordinates and updates map state
  111. /// Throws in invalid object instance ID
  112. void moveObject(ObjectInstanceID target, const int3 & dst);
  113. /// Hides object from map without actually removing it from object list
  114. void hideObject(CGObjectInstance * obj);
  115. /// Shows previously hiiden object on map
  116. void showObject(CGObjectInstance * obj);
  117. /// Remove objects and shifts object indicies.
  118. /// Only for use in map editor / RMG
  119. std::shared_ptr<CGObjectInstance> removeObject(ObjectInstanceID oldObject);
  120. /// Replaced map object with specified ID with new object
  121. /// Old object must exist and will be removed from map
  122. /// Returns pointer to old object, which can be manipulated or dropped
  123. std::shared_ptr<CGObjectInstance> replaceObject(ObjectInstanceID oldObject, const std::shared_ptr<CGObjectInstance> & newObject);
  124. /// Erases object from map without shifting indices
  125. /// Returns pointer to old object, which can be manipulated or dropped
  126. std::shared_ptr<CGObjectInstance> eraseObject(ObjectInstanceID oldObject);
  127. bool isHeroOnMap(const ObjectInstanceID &heroId) const;
  128. void heroAddedToMap(const CGHeroInstance * hero);
  129. void heroRemovedFromMap(const CGHeroInstance * hero);
  130. void townAddedToMap(const CGTownInstance * town);
  131. void townRemovedFromMap(const CGTownInstance * town);
  132. /// Adds provided hero to map pool. Hero with same identity must not exist
  133. void addToHeroPool(std::shared_ptr<CGHeroInstance> hero);
  134. /// Attempts to take hero of specified identity from pool. Returns nullptr on failure
  135. /// Hero is removed from pool on success
  136. std::shared_ptr<CGHeroInstance> tryTakeFromHeroPool(HeroTypeID hero);
  137. /// Attempts to access hero of specified identity in pool. Returns nullptr on failure
  138. CGHeroInstance * tryGetFromHeroPool(HeroTypeID hero);
  139. /// Returns list of identities of heroes currently present in pool
  140. std::vector<HeroTypeID> getHeroesInPool() const;
  141. CGObjectInstance * getObject(ObjectInstanceID obj);
  142. const CGObjectInstance * getObject(ObjectInstanceID obj) const;
  143. void attachToBonusSystem(CGameState & gs);
  144. /// Returns all valid objects of specified class present on map
  145. template<typename ObjectType = CGObjectInstance>
  146. std::vector<const ObjectType *> getObjects() const
  147. {
  148. std::vector<const ObjectType *> result;
  149. for (const auto & object : objects)
  150. {
  151. auto casted = dynamic_cast<const ObjectType*>(object.get());
  152. if (casted)
  153. result.push_back(casted);
  154. }
  155. return result;
  156. }
  157. /// Returns all valid objects of specified class present on map
  158. template<typename ObjectType = CGObjectInstance>
  159. std::vector<ObjectType *> getObjects()
  160. {
  161. std::vector<ObjectType *> result;
  162. for (const auto & object : objects)
  163. {
  164. auto casted = dynamic_cast<ObjectType*>(object.get());
  165. if (casted)
  166. result.push_back(casted);
  167. }
  168. return result;
  169. }
  170. /// Returns all valid artifacts present on map
  171. std::vector<CArtifactInstance *> getArtifacts()
  172. {
  173. std::vector<CArtifactInstance *> result;
  174. for (const auto & art : artInstances)
  175. if (art)
  176. result.push_back(art.get());
  177. return result;
  178. }
  179. bool isWaterMap() const;
  180. bool calculateWaterContent();
  181. void banWaterArtifacts();
  182. void banHero(const HeroTypeID& id);
  183. void unbanHero(const HeroTypeID & id);
  184. void banWaterSpells();
  185. void banWaterSkills();
  186. void banWaterContent();
  187. /// Gets object of specified type on requested position
  188. const CGObjectInstance * getObjectiveObjectFrom(const int3 & pos, Obj type);
  189. /// Returns pointer to hero of specified type if hero is present on map
  190. CGHeroInstance * getHero(HeroTypeID heroId);
  191. const CGHeroInstance * getHero(HeroTypeID heroId) const;
  192. /// Returns ID's of all heroes that are currently present on map
  193. /// Includes all garrisoned and imprisoned heroes
  194. const std::vector<ObjectInstanceID> & getHeroesOnMap() const;
  195. /// Returns ID's of all towns present on map
  196. const std::vector<ObjectInstanceID> & getAllTowns() const;
  197. /// Sets the victory/loss condition objectives ??
  198. void checkForObjectives();
  199. void resolveQuestIdentifiers();
  200. void reindexObjects();
  201. std::vector<Rumor> rumors;
  202. std::set<SpellID> allowedSpells;
  203. std::set<ArtifactID> allowedArtifact;
  204. std::set<SecondarySkill> allowedAbilities;
  205. std::vector<CMapEvent> events;
  206. int3 grailPos;
  207. int grailRadius;
  208. //Helper lists
  209. std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > teleportChannels;
  210. std::unique_ptr<CMapEditManager> editManager;
  211. MapTilesStorage<int3> guardingCreaturePositions;
  212. std::map<std::string, std::shared_ptr<CGObjectInstance> > instanceNames;
  213. bool waterMap;
  214. ui8 obeliskCount = 0; //how many obelisks are on map
  215. std::map<TeamID, ui8> obelisksVisited; //map: team_id => how many obelisks has been visited
  216. std::vector<ArtifactID> townMerchantArtifacts;
  217. void overrideGameSettings(const JsonNode & input);
  218. void overrideGameSetting(EGameSettings option, const JsonNode & input);
  219. const IGameSettings & getSettings() const;
  220. void saveCompatibilityStoreAllocatedArtifactID();
  221. void parseUidCounter();
  222. static bool compareObjectBlitOrder(const CGObjectInstance * a, const CGObjectInstance * b);
  223. private:
  224. /// a 3-dimensional array of terrain tiles
  225. MapTilesStorage<TerrainTile> terrain;
  226. si32 uidCounter;
  227. public:
  228. template <typename Handler>
  229. void serialize(Handler &h)
  230. {
  231. h & static_cast<CMapHeader&>(*this);
  232. h & triggeredEvents; //from CMapHeader
  233. h & rumors;
  234. h & allowedSpells;
  235. h & allowedAbilities;
  236. h & allowedArtifact;
  237. h & events;
  238. h & grailPos;
  239. h & artInstances;
  240. if (!h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  241. {
  242. saveCompatibilityStoreAllocatedArtifactID();
  243. std::vector< std::shared_ptr<CQuest> > quests;
  244. h & quests;
  245. }
  246. if (h.saving)
  247. h & heroesPool;
  248. else
  249. {
  250. std::vector<std::shared_ptr<CGHeroInstance> > poolFromSave;
  251. h & poolFromSave;
  252. deserializeHeroPool(poolFromSave);
  253. }
  254. //TODO: viccondetails
  255. h & terrain;
  256. h & guardingCreaturePositions;
  257. h & objects;
  258. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  259. h & heroesOnMap;
  260. else
  261. {
  262. std::vector<std::shared_ptr<CGObjectInstance>> objectPtrs;
  263. h & objectPtrs;
  264. for (const auto & ptr : objectPtrs)
  265. heroesOnMap.push_back(ptr->id);
  266. for (auto & ptr : heroesPool)
  267. if (vstd::contains(objects, ptr))
  268. ptr = nullptr;
  269. }
  270. h & teleportChannels;
  271. if (h.hasFeature(Handler::Version::NO_RAW_POINTERS_IN_SERIALIZER))
  272. h & towns;
  273. else
  274. {
  275. std::vector<std::shared_ptr<CGObjectInstance>> objectPtrs;
  276. h & objectPtrs;
  277. for (const auto & ptr : objectPtrs)
  278. towns.push_back(ptr->id);
  279. }
  280. h & artInstances;
  281. // static members
  282. h & obeliskCount;
  283. h & obelisksVisited;
  284. h & townMerchantArtifacts;
  285. if (!h.hasFeature(Handler::Version::UNIVERSITY_CONFIG))
  286. {
  287. std::vector<TradeItemBuy> townUniversitySkills;
  288. h & townUniversitySkills;
  289. }
  290. h & instanceNames;
  291. h & *gameSettings;
  292. if (!h.hasFeature(Handler::Version::STORE_UID_COUNTER_IN_CMAP))
  293. {
  294. if (!h.saving)
  295. parseUidCounter();
  296. }
  297. else
  298. {
  299. h & uidCounter;
  300. }
  301. }
  302. };
  303. inline bool CMap::isInTheMap(const int3 & pos) const
  304. {
  305. // Check whether coord < 0 is done implicitly. Negative signed int overflows to unsigned number larger than all signed ints.
  306. return
  307. static_cast<uint32_t>(pos.x) < static_cast<uint32_t>(width) &&
  308. static_cast<uint32_t>(pos.y) < static_cast<uint32_t>(height) &&
  309. static_cast<uint32_t>(pos.z) <= levels() - 1;
  310. }
  311. inline TerrainTile & CMap::getTile(const int3 & tile)
  312. {
  313. assert(isInTheMap(tile));
  314. return terrain[tile];
  315. }
  316. inline const TerrainTile & CMap::getTile(const int3 & tile) const
  317. {
  318. assert(isInTheMap(tile));
  319. return terrain[tile];
  320. }
  321. VCMI_LIB_NAMESPACE_END