CModHandler.h 12 KB

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