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