CModHandler.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. #ifdef __UCLIBC__
  15. #undef major
  16. #undef minor
  17. #undef patch
  18. #endif
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. class CModHandler;
  21. class CModIndentifier;
  22. class CModInfo;
  23. class JsonNode;
  24. class IHandlerBase;
  25. /// class that stores all object identifiers strings and maps them to numeric ID's
  26. /// if possible, objects ID's should be in format <type>.<name>, camelCase e.g. "creature.grandElf"
  27. class DLL_LINKAGE CIdentifierStorage
  28. {
  29. enum ELoadingState
  30. {
  31. LOADING,
  32. FINALIZING,
  33. FINISHED
  34. };
  35. struct ObjectCallback // entry created on ID request
  36. {
  37. std::string localScope; /// scope from which this ID was requested
  38. std::string remoteScope; /// scope in which this object must be found
  39. std::string type; /// type, e.g. creature, faction, hero, etc
  40. std::string name; /// string ID
  41. std::function<void(si32)> callback;
  42. bool optional;
  43. ObjectCallback(std::string localScope, std::string remoteScope,
  44. std::string type, std::string name,
  45. const std::function<void(si32)> & callback,
  46. bool optional);
  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. 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();
  73. /// request identifier for specific object name.
  74. /// Function callback will be called during ID resolution phase of loading
  75. void requestIdentifier(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  76. ///fullName = [remoteScope:]type.name
  77. void requestIdentifier(std::string scope, std::string fullName, const std::function<void(si32)> & callback);
  78. void requestIdentifier(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(std::string scope, std::string type, std::string name, const std::function<void(si32)> & callback);
  82. void tryRequestIdentifier(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. boost::optional<si32> getIdentifier(std::string scope, std::string type, std::string name, bool silent = false);
  85. boost::optional<si32> getIdentifier(std::string type, const JsonNode & name, bool silent = false);
  86. boost::optional<si32> getIdentifier(const JsonNode & name, bool silent = false);
  87. boost::optional<si32> getIdentifier(std::string scope, std::string fullName, bool silent = false);
  88. /// registers new object
  89. void registerObject(std::string scope, std::string type, 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, std::string objectName);
  116. /// local version of methods in ContentHandler
  117. /// returns true if loading was successful
  118. bool preloadModData(std::string modName, std::vector<std::string> fileList, bool validate);
  119. bool loadMod(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(std::string modName, JsonNode modConfig, bool validate);
  128. /// actually loads data in mod
  129. bool loadMod(std::string modName, bool validate);
  130. std::map<std::string, ContentTypeHandler> handlers;
  131. public:
  132. CContentHandler();
  133. void init();
  134. /// preloads all data from fileList as data from modName.
  135. void preloadData(CModInfo & mod);
  136. /// actually loads data in mod
  137. void load(CModInfo & mod);
  138. void loadCustom();
  139. /// all data was loaded, time for final validation / integration
  140. void afterLoadFinalization();
  141. const ContentTypeHandler & operator[] (const std::string & name) const;
  142. };
  143. typedef std::string TModID;
  144. class DLL_LINKAGE CModInfo
  145. {
  146. public:
  147. enum EValidationStatus
  148. {
  149. PENDING,
  150. FAILED,
  151. PASSED
  152. };
  153. struct Version
  154. {
  155. int major = 0;
  156. int minor = 0;
  157. int patch = 0;
  158. Version() = default;
  159. Version(int mj, int mi, int p): major(mj), minor(mi), patch(p) {}
  160. static Version GameVersion();
  161. static Version fromString(std::string from);
  162. std::string toString() const;
  163. bool compatible(const Version & other, bool checkMinor = false, bool checkPatch = false) const;
  164. bool isNull() const;
  165. template <typename Handler> void serialize(Handler &h, const int version)
  166. {
  167. h & major;
  168. h & minor;
  169. h & patch;
  170. }
  171. };
  172. /// identifier, identical to name of folder with mod
  173. std::string identifier;
  174. /// human-readable strings
  175. std::string name;
  176. std::string description;
  177. /// version of the mod
  178. Version version;
  179. /// vcmi versions compatible with the mod
  180. Version vcmiCompatibleMin, vcmiCompatibleMax;
  181. /// list of mods that should be loaded before this one
  182. std::set <TModID> dependencies;
  183. /// list of mods that can't be used in the same time as this one
  184. std::set <TModID> conflicts;
  185. /// CRC-32 checksum of the mod
  186. ui32 checksum;
  187. /// true if mod is enabled
  188. bool enabled;
  189. EValidationStatus validation;
  190. JsonNode config;
  191. CModInfo();
  192. CModInfo(std::string identifier, const JsonNode & local, const JsonNode & config);
  193. JsonNode saveLocalData() const;
  194. void updateChecksum(ui32 newChecksum);
  195. static std::string getModDir(std::string name);
  196. static std::string getModFile(std::string name);
  197. private:
  198. void loadLocalData(const JsonNode & data);
  199. };
  200. class DLL_LINKAGE CModHandler
  201. {
  202. std::map <TModID, CModInfo> allMods;
  203. std::vector <TModID> activeMods;//active mods, in order in which they were loaded
  204. CModInfo coreMod;
  205. void loadConfigFromFile(std::string name);
  206. bool hasCircularDependency(TModID mod, std::set <TModID> currentList = std::set <TModID>()) const;
  207. //returns false if mod list is incorrect and prints error to console. Possible errors are:
  208. // - missing dependency mod
  209. // - conflicting mod in load order
  210. // - circular dependencies
  211. bool checkDependencies(const std::vector <TModID> & input) const;
  212. /**
  213. * 1. Set apart mods with resolved dependencies from mods which have unresolved dependencies
  214. * 2. Sort resolved mods using topological algorithm
  215. * 3. Log all problem mods and their unresolved dependencies
  216. *
  217. * @param modsToResolve list of valid mod IDs (checkDependencies returned true - TODO: Clarify it.)
  218. * @return a vector of the topologically sorted resolved mods: child nodes (dependent mods) have greater index than parents
  219. */
  220. std::vector <TModID> validateAndSortDependencies(std::vector <TModID> modsToResolve) const;
  221. std::vector<std::string> getModList(std::string path);
  222. void loadMods(std::string path, std::string parent, const JsonNode & modSettings, bool enableMods);
  223. void loadOneMod(std::string modName, std::string parent, const JsonNode & modSettings, bool enableMods);
  224. void loadTranslation(TModID modName);
  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. std::set<TModID> getModDependencies(TModID modId, bool & isModFound);
  265. /// returns list of all (active) mods
  266. std::vector<std::string> getAllMods();
  267. std::vector<std::string> getActiveMods();
  268. /// load content from all available mods
  269. void load();
  270. void afterLoad(bool onlyEssential);
  271. struct DLL_LINKAGE hardcodedFeatures
  272. {
  273. JsonNode data;
  274. int CREEP_SIZE; // neutral stacks won't grow beyond this number
  275. int WEEKLY_GROWTH; //percent
  276. int NEUTRAL_STACK_EXP;
  277. int MAX_BUILDING_PER_TURN;
  278. bool DWELLINGS_ACCUMULATE_CREATURES;
  279. bool ALL_CREATURES_GET_DOUBLE_MONTHS;
  280. int MAX_HEROES_AVAILABLE_PER_PLAYER;
  281. int MAX_HEROES_ON_MAP_PER_PLAYER;
  282. bool WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  283. bool BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  284. bool NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  285. double ATTACK_POINT_DMG_MULTIPLIER;
  286. double ATTACK_POINTS_DMG_MULTIPLIER_CAP;
  287. double DEFENSE_POINT_DMG_MULTIPLIER;
  288. double DEFENSE_POINTS_DMG_MULTIPLIER_CAP;
  289. std::vector<int32_t> HERO_STARTING_ARMY_STACKS_COUNT_CHANCES;
  290. std::vector<int32_t> DEFAULT_BUILDING_SET_DWELLING_CHANCES;
  291. template <typename Handler> void serialize(Handler &h, const int version)
  292. {
  293. h & data;
  294. h & CREEP_SIZE;
  295. h & WEEKLY_GROWTH;
  296. h & NEUTRAL_STACK_EXP;
  297. h & MAX_BUILDING_PER_TURN;
  298. h & DWELLINGS_ACCUMULATE_CREATURES;
  299. h & ALL_CREATURES_GET_DOUBLE_MONTHS;
  300. h & MAX_HEROES_AVAILABLE_PER_PLAYER;
  301. h & MAX_HEROES_ON_MAP_PER_PLAYER;
  302. h & WINNING_HERO_WITH_NO_TROOPS_RETREATS;
  303. h & BLACK_MARKET_MONTHLY_ARTIFACTS_CHANGE;
  304. h & NO_RANDOM_SPECIAL_WEEKS_AND_MONTHS;
  305. h & ATTACK_POINT_DMG_MULTIPLIER;
  306. h & ATTACK_POINTS_DMG_MULTIPLIER_CAP;
  307. h & DEFENSE_POINT_DMG_MULTIPLIER;
  308. h & DEFENSE_POINTS_DMG_MULTIPLIER_CAP;
  309. if(version >= 815)
  310. {
  311. h & HERO_STARTING_ARMY_STACKS_COUNT_CHANCES;
  312. h & DEFAULT_BUILDING_SET_DWELLING_CHANCES;
  313. }
  314. }
  315. } settings;
  316. struct DLL_LINKAGE gameModules
  317. {
  318. bool STACK_EXP;
  319. bool STACK_ARTIFACT;
  320. bool COMMANDERS;
  321. bool MITHRIL;
  322. template <typename Handler> void serialize(Handler &h, const int version)
  323. {
  324. h & STACK_EXP;
  325. h & STACK_ARTIFACT;
  326. h & COMMANDERS;
  327. h & MITHRIL;
  328. }
  329. } modules;
  330. CModHandler();
  331. virtual ~CModHandler();
  332. static std::string normalizeIdentifier(const std::string & scope, const std::string & remoteScope, const std::string & identifier);
  333. static void parseIdentifier(const std::string & fullIdentifier, std::string & scope, std::string & type, std::string & identifier);
  334. static std::string makeFullIdentifier(const std::string & scope, const std::string & type, const std::string & identifier);
  335. template <typename Handler> void serialize(Handler &h, const int version)
  336. {
  337. if(h.saving)
  338. {
  339. h & activeMods;
  340. for(const auto & m : activeMods)
  341. h & allMods[m].version;
  342. }
  343. else
  344. {
  345. loadMods();
  346. std::vector<TModID> newActiveMods;
  347. h & newActiveMods;
  348. Incompatibility::ModList missingMods;
  349. for(const auto & m : newActiveMods)
  350. {
  351. CModInfo::Version mver;
  352. h & mver;
  353. if(allMods.count(m) && (allMods[m].version.isNull() || mver.isNull() || allMods[m].version.compatible(mver)))
  354. allMods[m].enabled = true;
  355. else
  356. missingMods.emplace_back(m, mver.toString());
  357. }
  358. if(!missingMods.empty())
  359. throw Incompatibility(std::move(missingMods));
  360. std::swap(activeMods, newActiveMods);
  361. }
  362. h & settings;
  363. h & modules;
  364. h & identifiers;
  365. }
  366. };
  367. VCMI_LIB_NAMESPACE_END