CModHandler.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * CModHandler.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 "filesystem/Filesystem.h"
  12. #include "VCMI_Lib.h"
  13. #include "JsonNode.h"
  14. class CModHandler;
  15. class CModIndentifier;
  16. class CModInfo;
  17. class JsonNode;
  18. class IHandlerBase;
  19. /// class that stores all object identifiers strings and maps them to numeric ID's
  20. /// if possible, objects ID's should be in format <type>.<name>, camelCase e.g. "creature.grandElf"
  21. class CIdentifierStorage
  22. {
  23. enum ELoadingState
  24. {
  25. LOADING,
  26. FINALIZING,
  27. FINISHED
  28. };
  29. struct ObjectCallback // entry created on ID request
  30. {
  31. std::string localScope; /// scope from which this ID was requested
  32. std::string remoteScope; /// scope in which this object must be found
  33. std::string type; /// type, e.g. creature, faction, hero, etc
  34. std::string name; /// string ID
  35. std::function<void(si32)> callback;
  36. bool optional;
  37. ObjectCallback(std::string localScope, std::string remoteScope,
  38. std::string type, std::string name,
  39. const std::function<void(si32)> & callback,
  40. bool optional);
  41. };
  42. struct ObjectData // entry created on ID registration
  43. {
  44. si32 id;
  45. std::string scope; /// scope in which this ID located
  46. bool operator==(const ObjectData & other) const
  47. {
  48. return id == other.id && scope == other.scope;
  49. }
  50. template <typename Handler> void serialize(Handler &h, const int version)
  51. {
  52. h & id;
  53. h & scope;
  54. }
  55. };
  56. std::multimap<std::string, ObjectData> registeredObjects;
  57. std::vector<ObjectCallback> scheduledRequests;
  58. ELoadingState state;
  59. /// Check if identifier can be valid (camelCase, point as separator)
  60. void checkIdentifier(std::string & ID);
  61. void requestIdentifier(ObjectCallback callback);
  62. bool resolveIdentifier(const ObjectCallback & callback);
  63. std::vector<ObjectData> getPossibleIdentifiers(const ObjectCallback & callback);
  64. public:
  65. CIdentifierStorage();
  66. virtual ~CIdentifierStorage();
  67. /// request identifier for specific object name.
  68. /// Function callback will be called during ID resolution phase of loading
  69. void requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  70. ///fullName = [remoteScope:]type.name
  71. void requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)> & callback);
  72. void requestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback);
  73. void requestIdentifier(const JsonNode & name, const std::function<void(si32)> & callback);
  74. /// try to request ID. If ID with such name won't be loaded, callback function will not be called
  75. void tryRequestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  76. void tryRequestIdentifier(std::string type, const JsonNode & name, const std::function<void(si32)> & callback);
  77. /// get identifier immediately. If identifier is not know and not silent call will result in error message
  78. boost::optional<si32> getIdentifier(std::string scope, std::string type, std::string name, bool silent = false);
  79. boost::optional<si32> getIdentifier(std::string type, const JsonNode & name, bool silent = false);
  80. boost::optional<si32> getIdentifier(const JsonNode & name, bool silent = false);
  81. boost::optional<si32> getIdentifier(std::string scope, std::string fullName, bool silent = false);
  82. /// registers new object
  83. void registerObject(std::string scope, std::string type, std::string name, si32 identifier);
  84. /// called at the very end of loading to check for any missing ID's
  85. void finalize();
  86. template <typename Handler> void serialize(Handler &h, const int version)
  87. {
  88. h & registeredObjects;
  89. h & state;
  90. }
  91. };
  92. /// internal type to handle loading of one data type (e.g. artifacts, creatures)
  93. class DLL_LINKAGE ContentTypeHandler
  94. {
  95. public:
  96. struct ModInfo
  97. {
  98. /// mod data from this mod and for this mod
  99. JsonNode modData;
  100. /// mod data for this mod from other mods (patches)
  101. JsonNode patches;
  102. };
  103. /// handler to which all data will be loaded
  104. IHandlerBase * handler;
  105. std::string objectName;
  106. /// contains all loaded H3 data
  107. std::vector<JsonNode> originalData;
  108. std::map<std::string, ModInfo> modData;
  109. ContentTypeHandler(IHandlerBase * handler, std::string objectName);
  110. /// local version of methods in ContentHandler
  111. /// returns true if loading was successful
  112. bool preloadModData(std::string modName, std::vector<std::string> fileList, bool validate);
  113. bool loadMod(std::string modName, bool validate);
  114. void loadCustom();
  115. void afterLoadFinalization();
  116. };
  117. /// class used to load all game data into handlers. Used only during loading
  118. class DLL_LINKAGE CContentHandler
  119. {
  120. /// preloads all data from fileList as data from modName.
  121. bool preloadModData(std::string modName, JsonNode modConfig, bool validate);
  122. /// actually loads data in mod
  123. bool loadMod(std::string modName, bool validate);
  124. std::map<std::string, ContentTypeHandler> handlers;
  125. public:
  126. CContentHandler();
  127. void init();
  128. /// preloads all data from fileList as data from modName.
  129. void preloadData(CModInfo & mod);
  130. /// actually loads data in mod
  131. void load(CModInfo & mod);
  132. void loadCustom();
  133. /// all data was loaded, time for final validation / integration
  134. void afterLoadFinalization();
  135. const ContentTypeHandler & operator[] (const std::string & name) const;
  136. };
  137. typedef std::string TModID;
  138. class DLL_LINKAGE CModInfo
  139. {
  140. public:
  141. enum EValidationStatus
  142. {
  143. PENDING,
  144. FAILED,
  145. PASSED
  146. };
  147. struct Version
  148. {
  149. int major = 0;
  150. int minor = 0;
  151. int patch = 0;
  152. Version() = default;
  153. Version(int mj, int mi, int p): major(mj), minor(mi), patch(p) {}
  154. static Version GameVersion();
  155. static Version fromString(std::string from);
  156. std::string toString() const;
  157. bool compatible(const Version & other, bool checkMinor = false, bool checkPatch = false) const;
  158. bool isNull() const;
  159. template <typename Handler> void serialize(Handler &h, const int version)
  160. {
  161. h & major;
  162. h & minor;
  163. h & patch;
  164. }
  165. };
  166. /// identifier, identical to name of folder with mod
  167. std::string identifier;
  168. /// human-readable strings
  169. std::string name;
  170. std::string description;
  171. /// version of the mod
  172. Version version;
  173. ///The vcmi versions compatible with the mod
  174. Version vcmiCompatibleMin, vcmiCompatibleMax;
  175. /// list of mods that should be loaded before this one
  176. std::set <TModID> dependencies;
  177. /// list of mods that can't be used in the same time as this one
  178. std::set <TModID> conflicts;
  179. /// CRC-32 checksum of the mod
  180. ui32 checksum;
  181. /// true if mod is enabled
  182. bool enabled;
  183. EValidationStatus validation;
  184. JsonNode config;
  185. CModInfo();
  186. CModInfo(std::string identifier, const JsonNode & local, const JsonNode & config);
  187. JsonNode saveLocalData() const;
  188. void updateChecksum(ui32 newChecksum);
  189. static std::string getModDir(std::string name);
  190. static std::string getModFile(std::string name);
  191. private:
  192. void loadLocalData(const JsonNode & data);
  193. };
  194. class DLL_LINKAGE CModHandler
  195. {
  196. std::map <TModID, CModInfo> allMods;
  197. std::vector <TModID> activeMods;//active mods, in order in which they were loaded
  198. CModInfo coreMod;
  199. void loadConfigFromFile(std::string name);
  200. bool hasCircularDependency(TModID mod, std::set <TModID> currentList = std::set <TModID>()) const;
  201. //returns false if mod list is incorrect and prints error to console. Possible errors are:
  202. // - missing dependency mod
  203. // - conflicting mod in load order
  204. // - circular dependencies
  205. bool checkDependencies(const std::vector <TModID> & input) const;
  206. /**
  207. * 1. Set apart mods with resolved dependencies from mods which have unresolved dependencies
  208. * 2. Sort resolved mods using topological algorithm
  209. * 3. Log all problem mods and their unresolved dependencies
  210. *
  211. * @param modsToResolve list of valid mod IDs (checkDependencies returned true - TODO: Clarify it.)
  212. * @return a vector of the topologically sorted resolved mods: child nodes (dependent mods) have greater index than parents
  213. */
  214. std::vector <TModID> validateAndSortDependencies(std::vector <TModID> modsToResolve) const;
  215. std::vector<std::string> getModList(std::string path);
  216. void loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods);
  217. void loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods);
  218. public:
  219. class Incompatibility: public std::logic_error
  220. {
  221. public:
  222. Incompatibility(const std::string & w): std::logic_error(w)
  223. {}
  224. };
  225. CIdentifierStorage identifiers;
  226. std::shared_ptr<CContentHandler> content; //(!)Do not serialize
  227. /// receives list of available mods and trying to load mod.json from all of them
  228. void initializeConfig();
  229. void loadMods(bool onlyEssential = false);
  230. void loadModFilesystems();
  231. std::set<TModID> getModDependencies(TModID modId, bool & isModFound);
  232. /// returns list of all (active) mods
  233. std::vector<std::string> getAllMods();
  234. std::vector<std::string> getActiveMods();
  235. /// load content from all available mods
  236. void load();
  237. void afterLoad(bool onlyEssential);
  238. struct DLL_LINKAGE hardcodedFeatures
  239. {
  240. JsonNode data;
  241. int CREEP_SIZE; // neutral stacks won't grow beyond this number
  242. int WEEKLY_GROWTH; //percent
  243. int NEUTRAL_STACK_EXP;
  244. int MAX_BUILDING_PER_TURN;
  245. bool DWELLINGS_ACCUMULATE_CREATURES;
  246. bool ALL_CREATURES_GET_DOUBLE_MONTHS;
  247. int MAX_HEROES_AVAILABLE_PER_PLAYER;
  248. int MAX_HEROES_ON_MAP_PER_PLAYER;
  249. bool WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  250. bool BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  251. bool NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  252. template <typename Handler> void serialize(Handler &h, const int version)
  253. {
  254. h & data;
  255. h & CREEP_SIZE;
  256. h & WEEKLY_GROWTH;
  257. h & NEUTRAL_STACK_EXP;
  258. h & MAX_BUILDING_PER_TURN;
  259. h & DWELLINGS_ACCUMULATE_CREATURES;
  260. h & ALL_CREATURES_GET_DOUBLE_MONTHS;
  261. h & MAX_HEROES_AVAILABLE_PER_PLAYER;
  262. h & MAX_HEROES_ON_MAP_PER_PLAYER;
  263. h & WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  264. h & BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  265. h & NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  266. }
  267. } settings;
  268. struct DLL_LINKAGE gameModules
  269. {
  270. bool STACK_EXP;
  271. bool STACK_ARTIFACT;
  272. bool COMMANDERS;
  273. bool MITHRIL;
  274. template <typename Handler> void serialize(Handler &h, const int version)
  275. {
  276. h & STACK_EXP;
  277. h & STACK_ARTIFACT;
  278. h & COMMANDERS;
  279. h & MITHRIL;
  280. }
  281. } modules;
  282. CModHandler();
  283. virtual ~CModHandler();
  284. static std::string normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier);
  285. static void parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier);
  286. static std::string makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier);
  287. template <typename Handler> void serialize(Handler &h, const int version)
  288. {
  289. if(h.saving)
  290. {
  291. h & activeMods;
  292. for(auto & m : activeMods)
  293. h & allMods[m].version;
  294. }
  295. else
  296. {
  297. std::vector<TModID> newActiveMods;
  298. h & newActiveMods;
  299. for(auto & m : newActiveMods)
  300. {
  301. if(!allMods.count(m))
  302. throw Incompatibility(m + " unkown mod");
  303. CModInfo::Version mver;
  304. h & mver;
  305. if(!allMods[m].version.isNull() && !mver.isNull() && !allMods[m].version.compatible(mver))
  306. {
  307. std::string err = allMods[m].name +
  308. ": version needed " + mver.toString() +
  309. "but you have installed " + allMods[m].version.toString();
  310. throw Incompatibility(err);
  311. }
  312. allMods[m].enabled = true;
  313. }
  314. std::swap(activeMods, newActiveMods);
  315. }
  316. h & settings;
  317. h & modules;
  318. h & identifiers;
  319. }
  320. };