ModManager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * ModManager.cpp, 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. #include "StdInc.h"
  11. #include "ModManager.h"
  12. #include "ModDescription.h"
  13. #include "ModScope.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../json/JsonNode.h"
  16. #include "../texts/CGeneralTextHandler.h"
  17. VCMI_LIB_NAMESPACE_BEGIN
  18. static std::string getModSettingsDirectory(const TModID & modName)
  19. {
  20. std::string result = modName;
  21. boost::to_upper(result);
  22. boost::algorithm::replace_all(result, ".", "/MODS/");
  23. return "MODS/" + result + "/MODS/";
  24. }
  25. static JsonPath getModDescriptionFile(const TModID & modName)
  26. {
  27. std::string result = modName;
  28. boost::to_upper(result);
  29. boost::algorithm::replace_all(result, ".", "/MODS/");
  30. return JsonPath::builtin("MODS/" + result + "/mod");
  31. }
  32. ModsState::ModsState()
  33. {
  34. modList.push_back(ModScope::scopeBuiltin());
  35. std::vector<TModID> testLocations = scanModsDirectory("MODS/");
  36. while(!testLocations.empty())
  37. {
  38. std::string target = testLocations.back();
  39. testLocations.pop_back();
  40. modList.push_back(boost::algorithm::to_lower_copy(target));
  41. for(const auto & submod : scanModsDirectory(getModSettingsDirectory(target)))
  42. testLocations.push_back(target + '.' + submod);
  43. // TODO: check that this is vcmi mod and not era mod?
  44. // TODO: check that mod name is not reserved (ModScope::isScopeReserved(modFullName)))
  45. }
  46. }
  47. TModList ModsState::getAllMods() const
  48. {
  49. return modList;
  50. }
  51. std::vector<TModID> ModsState::scanModsDirectory(const std::string & modDir) const
  52. {
  53. size_t depth = boost::range::count(modDir, '/');
  54. const auto & modScanFilter = [&](const ResourcePath & id) -> bool
  55. {
  56. if(id.getType() != EResType::DIRECTORY)
  57. return false;
  58. if(!boost::algorithm::starts_with(id.getName(), modDir))
  59. return false;
  60. if(boost::range::count(id.getName(), '/') != depth)
  61. return false;
  62. return true;
  63. };
  64. auto list = CResourceHandler::get("initial")->getFilteredFiles(modScanFilter);
  65. //storage for found mods
  66. std::vector<TModID> foundMods;
  67. for(const auto & entry : list)
  68. {
  69. std::string name = entry.getName();
  70. name.erase(0, modDir.size()); //Remove path prefix
  71. if(name.empty())
  72. continue;
  73. if(name.find('.') != std::string::npos)
  74. continue;
  75. if(!CResourceHandler::get("initial")->existsResource(JsonPath::builtin(entry.getName() + "/MOD")))
  76. continue;
  77. foundMods.push_back(name);
  78. }
  79. return foundMods;
  80. }
  81. ///////////////////////////////////////////////////////////////////////////////
  82. static JsonNode loadModSettings(const JsonPath & path)
  83. {
  84. if(CResourceHandler::get("local")->existsResource(ResourcePath(path)))
  85. {
  86. return JsonNode(path);
  87. }
  88. // Probably new install. Create initial configuration
  89. CResourceHandler::get("local")->createResource(path.getOriginalName() + ".json");
  90. return JsonNode();
  91. }
  92. ModsPresetState::ModsPresetState()
  93. {
  94. modConfig = loadModSettings(JsonPath::builtin("config/modSettings.json"));
  95. if(modConfig["presets"].isNull())
  96. {
  97. modConfig["activePreset"] = JsonNode("default");
  98. if(modConfig["activeMods"].isNull())
  99. createInitialPreset(); // new install
  100. else
  101. importInitialPreset(); // 1.5 format import
  102. saveConfiguration(modConfig);
  103. }
  104. }
  105. void ModsPresetState::saveConfiguration(const JsonNode & modSettings)
  106. {
  107. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  108. file << modSettings.toString();
  109. }
  110. void ModsPresetState::createInitialPreset()
  111. {
  112. // TODO: scan mods directory for all its content? Probably unnecessary since this looks like new install, but who knows?
  113. modConfig["presets"]["default"]["mods"].Vector().push_back(JsonNode("vcmi"));
  114. }
  115. void ModsPresetState::importInitialPreset()
  116. {
  117. JsonNode preset;
  118. for(const auto & mod : modConfig["activeMods"].Struct())
  119. {
  120. if(mod.second["active"].Bool())
  121. preset["mods"].Vector().push_back(JsonNode(mod.first));
  122. for(const auto & submod : mod.second["mods"].Struct())
  123. preset["settings"][mod.first][submod.first] = submod.second["active"];
  124. }
  125. modConfig["presets"]["default"] = preset;
  126. }
  127. const JsonNode & ModsPresetState::getActivePresetConfig() const
  128. {
  129. const std::string & currentPresetName = modConfig["activePreset"].String();
  130. const JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  131. return currentPreset;
  132. }
  133. TModList ModsPresetState::getActiveRootMods() const
  134. {
  135. const JsonNode & modsToActivateJson = getActivePresetConfig()["mods"];
  136. std::vector<TModID> modsToActivate = modsToActivateJson.convertTo<std::vector<TModID>>();
  137. modsToActivate.push_back(ModScope::scopeBuiltin());
  138. return modsToActivate;
  139. }
  140. std::map<TModID, bool> ModsPresetState::getModSettings(const TModID & modID) const
  141. {
  142. const JsonNode & modSettingsJson = getActivePresetConfig()["settings"][modID];
  143. std::map<TModID, bool> modSettings = modSettingsJson.convertTo<std::map<TModID, bool>>();
  144. return modSettings;
  145. }
  146. void ModsPresetState::setSettingActiveInPreset(const TModID & modName, const TModID & settingName, bool isActive)
  147. {
  148. const std::string & currentPresetName = modConfig["activePreset"].String();
  149. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  150. currentPreset["settings"][modName][settingName].Bool() = isActive;
  151. }
  152. void ModsPresetState::eraseModInAllPresets(const TModID & modName)
  153. {
  154. for (auto & preset : modConfig["presets"].Struct())
  155. vstd::erase(preset.second["mods"].Vector(), JsonNode(modName));
  156. }
  157. void ModsPresetState::eraseModSettingInAllPresets(const TModID & modName, const TModID & settingName)
  158. {
  159. for (auto & preset : modConfig["presets"].Struct())
  160. preset.second["settings"][modName].Struct().erase(modName);
  161. }
  162. std::vector<TModID> ModsPresetState::getActiveMods() const
  163. {
  164. TModList activeRootMods = getActiveRootMods();
  165. TModList allActiveMods;
  166. for(const auto & activeMod : activeRootMods)
  167. {
  168. activeRootMods.push_back(activeMod);
  169. for(const auto & submod : getModSettings(activeMod))
  170. if(submod.second)
  171. allActiveMods.push_back(activeMod + '.' + submod.first);
  172. }
  173. return allActiveMods;
  174. }
  175. ModsStorage::ModsStorage(const std::vector<TModID> & modsToLoad)
  176. {
  177. JsonNode coreModConfig(JsonPath::builtin("config/gameConfig.json"));
  178. coreModConfig.setModScope(ModScope::scopeBuiltin());
  179. mods.try_emplace(ModScope::scopeBuiltin(), ModScope::scopeBuiltin(), coreModConfig);
  180. for(auto modID : modsToLoad)
  181. {
  182. if(ModScope::isScopeReserved(modID))
  183. {
  184. logMod->error("Can not load mod %s - this name is reserved for internal use!", modID);
  185. continue;
  186. }
  187. JsonNode modConfig(getModDescriptionFile(modID));
  188. modConfig.setModScope(modID);
  189. if(modConfig["modType"].isNull())
  190. {
  191. logMod->error("Can not load mod %s - invalid mod config file!", modID);
  192. continue;
  193. }
  194. mods.try_emplace(modID, modID, modConfig);
  195. }
  196. }
  197. const ModDescription & ModsStorage::getMod(const TModID & fullID) const
  198. {
  199. return mods.at(fullID);
  200. }
  201. ModManager::ModManager()
  202. : modsState(std::make_unique<ModsState>())
  203. , modsPreset(std::make_unique<ModsPresetState>())
  204. {
  205. eraseMissingModsFromPreset();
  206. addNewModsToPreset();
  207. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  208. modsStorage = std::make_unique<ModsStorage>(desiredModList);
  209. generateLoadOrder(desiredModList);
  210. }
  211. ModManager::~ModManager() = default;
  212. const ModDescription & ModManager::getModDescription(const TModID & modID) const
  213. {
  214. return modsStorage->getMod(modID);
  215. }
  216. bool ModManager::isModActive(const TModID & modID) const
  217. {
  218. return vstd::contains(activeMods, modID);
  219. }
  220. const TModList & ModManager::getActiveMods() const
  221. {
  222. return activeMods;
  223. }
  224. void ModManager::eraseMissingModsFromPreset()
  225. {
  226. const TModList & installedMods = modsState->getAllMods();
  227. const TModList & rootMods = modsPreset->getActiveRootMods();
  228. for(const auto & rootMod : rootMods)
  229. {
  230. if(!vstd::contains(installedMods, rootMod))
  231. {
  232. modsPreset->eraseModInAllPresets(rootMod);
  233. continue;
  234. }
  235. const auto & modSettings = modsPreset->getModSettings(rootMod);
  236. for(const auto & modSetting : modSettings)
  237. {
  238. TModID fullModID = rootMod + '.' + modSetting.first;
  239. if(!vstd::contains(installedMods, fullModID))
  240. {
  241. modsPreset->eraseModSettingInAllPresets(rootMod, modSetting.first);
  242. continue;
  243. }
  244. }
  245. }
  246. }
  247. void ModManager::addNewModsToPreset()
  248. {
  249. const TModList & installedMods = modsState->getAllMods();
  250. for(const auto & modID : installedMods)
  251. {
  252. size_t dotPos = modID.find('.');
  253. if(dotPos == std::string::npos)
  254. continue; // only look up submods aka mod settings
  255. std::string rootMod = modID.substr(0, dotPos);
  256. std::string settingID = modID.substr(dotPos + 1);
  257. const auto & modSettings = modsPreset->getModSettings(rootMod);
  258. if (!modSettings.count(settingID))
  259. modsPreset->setSettingActiveInPreset(rootMod, settingID, modsStorage->getMod(modID).keepDisabled());
  260. }
  261. }
  262. void ModManager::generateLoadOrder(std::vector<TModID> modsToResolve)
  263. {
  264. // Topological sort algorithm.
  265. boost::range::sort(modsToResolve); // Sort mods per name
  266. std::vector<TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  267. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  268. std::set<TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  269. std::set<TModID> notResolvedModIDs(modsToResolve.begin(), modsToResolve.end()); // Use a set for validation for performance reason
  270. // Mod is resolved if it has no dependencies or all its dependencies are already resolved
  271. auto isResolved = [&](const ModDescription & mod) -> bool
  272. {
  273. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage())
  274. return false;
  275. if(mod.getDependencies().size() > resolvedModIDs.size())
  276. return false;
  277. for(const TModID & dependency : mod.getDependencies())
  278. if(!vstd::contains(resolvedModIDs, dependency))
  279. return false;
  280. for(const TModID & softDependency : mod.getSoftDependencies())
  281. if(vstd::contains(notResolvedModIDs, softDependency))
  282. return false;
  283. for(const TModID & conflict : mod.getConflicts())
  284. if(vstd::contains(resolvedModIDs, conflict))
  285. return false;
  286. for(const TModID & reverseConflict : resolvedModIDs)
  287. if(vstd::contains(modsStorage->getMod(reverseConflict).getConflicts(), mod.getID()))
  288. return false;
  289. return true;
  290. };
  291. while(true)
  292. {
  293. std::set<TModID> resolvedOnCurrentTreeLevel;
  294. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  295. {
  296. if(isResolved(modsStorage->getMod(*it)))
  297. {
  298. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node children will be resolved on the next iteration
  299. sortedValidMods.push_back(*it);
  300. it = modsToResolve.erase(it);
  301. continue;
  302. }
  303. it++;
  304. }
  305. if(!resolvedOnCurrentTreeLevel.empty())
  306. {
  307. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  308. for(const auto & it : resolvedOnCurrentTreeLevel)
  309. notResolvedModIDs.erase(it);
  310. continue;
  311. }
  312. // If there are no valid mods on the current mods tree level, no more mod can be resolved, should be ended.
  313. break;
  314. }
  315. activeMods = sortedValidMods;
  316. brokenMods = modsToResolve;
  317. }
  318. // modLoadErrors = std::make_unique<MetaString>();
  319. //
  320. // auto addErrorMessage = [this](const std::string & textID, const std::string & brokenModID, const std::string & missingModID)
  321. // {
  322. // modLoadErrors->appendTextID(textID);
  323. //
  324. // if (allMods.count(brokenModID))
  325. // modLoadErrors->replaceRawString(allMods.at(brokenModID).getVerificationInfo().name);
  326. // else
  327. // modLoadErrors->replaceRawString(brokenModID);
  328. //
  329. // if (allMods.count(missingModID))
  330. // modLoadErrors->replaceRawString(allMods.at(missingModID).getVerificationInfo().name);
  331. // else
  332. // modLoadErrors->replaceRawString(missingModID);
  333. //
  334. // };
  335. //
  336. // // Left mods have unresolved dependencies, output all to log.
  337. // for(const auto & brokenModID : modsToResolve)
  338. // {
  339. // const CModInfo & brokenMod = allMods.at(brokenModID);
  340. // bool showErrorMessage = false;
  341. // for(const TModID & dependency : brokenMod.dependencies)
  342. // {
  343. // if(!vstd::contains(resolvedModIDs, dependency) && brokenMod.config["modType"].String() != "Compatibility")
  344. // {
  345. // addErrorMessage("vcmi.server.errors.modNoDependency", brokenModID, dependency);
  346. // showErrorMessage = true;
  347. // }
  348. // }
  349. // for(const TModID & conflict : brokenMod.conflicts)
  350. // {
  351. // if(vstd::contains(resolvedModIDs, conflict))
  352. // {
  353. // addErrorMessage("vcmi.server.errors.modConflict", brokenModID, conflict);
  354. // showErrorMessage = true;
  355. // }
  356. // }
  357. // for(const TModID & reverseConflict : resolvedModIDs)
  358. // {
  359. // if (vstd::contains(allMods.at(reverseConflict).conflicts, brokenModID))
  360. // {
  361. // addErrorMessage("vcmi.server.errors.modConflict", brokenModID, reverseConflict);
  362. // showErrorMessage = true;
  363. // }
  364. // }
  365. //
  366. // // some mods may in a (soft) dependency loop.
  367. // if(!showErrorMessage && brokenMod.config["modType"].String() != "Compatibility")
  368. // {
  369. // modLoadErrors->appendTextID("vcmi.server.errors.modDependencyLoop");
  370. // if (allMods.count(brokenModID))
  371. // modLoadErrors->replaceRawString(allMods.at(brokenModID).getVerificationInfo().name);
  372. // else
  373. // modLoadErrors->replaceRawString(brokenModID);
  374. // }
  375. //
  376. // }
  377. // return sortedValidMods;
  378. //}
  379. VCMI_LIB_NAMESPACE_END