2
0

ModManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. allActiveMods.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, const std::vector<JsonNode> & repositoryList)
  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. :ModManager(std::vector<JsonNode>())
  203. {
  204. }
  205. ModManager::ModManager(const std::vector<JsonNode> & repositoryList)
  206. : modsState(std::make_unique<ModsState>())
  207. , modsPreset(std::make_unique<ModsPresetState>())
  208. {
  209. eraseMissingModsFromPreset();
  210. //TODO: load only active mods & all their submods in game mode
  211. modsStorage = std::make_unique<ModsStorage>(modsState->getAllMods(), repositoryList);
  212. addNewModsToPreset();
  213. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  214. generateLoadOrder(desiredModList);
  215. }
  216. ModManager::~ModManager() = default;
  217. const ModDescription & ModManager::getModDescription(const TModID & modID) const
  218. {
  219. return modsStorage->getMod(modID);
  220. }
  221. bool ModManager::isModActive(const TModID & modID) const
  222. {
  223. return vstd::contains(activeMods, modID);
  224. }
  225. const TModList & ModManager::getActiveMods() const
  226. {
  227. return activeMods;
  228. }
  229. const TModList & ModManager::getAllMods() const
  230. {
  231. return activeMods; //TODO
  232. }
  233. void ModManager::eraseMissingModsFromPreset()
  234. {
  235. const TModList & installedMods = modsState->getAllMods();
  236. const TModList & rootMods = modsPreset->getActiveRootMods();
  237. for(const auto & rootMod : rootMods)
  238. {
  239. if(!vstd::contains(installedMods, rootMod))
  240. {
  241. modsPreset->eraseModInAllPresets(rootMod);
  242. continue;
  243. }
  244. const auto & modSettings = modsPreset->getModSettings(rootMod);
  245. for(const auto & modSetting : modSettings)
  246. {
  247. TModID fullModID = rootMod + '.' + modSetting.first;
  248. if(!vstd::contains(installedMods, fullModID))
  249. {
  250. modsPreset->eraseModSettingInAllPresets(rootMod, modSetting.first);
  251. continue;
  252. }
  253. }
  254. }
  255. }
  256. void ModManager::addNewModsToPreset()
  257. {
  258. const TModList & installedMods = modsState->getAllMods();
  259. for(const auto & modID : installedMods)
  260. {
  261. size_t dotPos = modID.find('.');
  262. if(dotPos == std::string::npos)
  263. continue; // only look up submods aka mod settings
  264. std::string rootMod = modID.substr(0, dotPos);
  265. std::string settingID = modID.substr(dotPos + 1);
  266. const auto & modSettings = modsPreset->getModSettings(rootMod);
  267. if (!modSettings.count(settingID))
  268. modsPreset->setSettingActiveInPreset(rootMod, settingID, modsStorage->getMod(modID).keepDisabled());
  269. }
  270. }
  271. void ModManager::generateLoadOrder(std::vector<TModID> modsToResolve)
  272. {
  273. // Topological sort algorithm.
  274. boost::range::sort(modsToResolve); // Sort mods per name
  275. std::vector<TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  276. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  277. std::set<TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  278. std::set<TModID> notResolvedModIDs(modsToResolve.begin(), modsToResolve.end()); // Use a set for validation for performance reason
  279. // Mod is resolved if it has no dependencies or all its dependencies are already resolved
  280. auto isResolved = [&](const ModDescription & mod) -> bool
  281. {
  282. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage())
  283. return false;
  284. if(mod.getDependencies().size() > resolvedModIDs.size())
  285. return false;
  286. for(const TModID & dependency : mod.getDependencies())
  287. if(!vstd::contains(resolvedModIDs, dependency))
  288. return false;
  289. for(const TModID & softDependency : mod.getSoftDependencies())
  290. if(vstd::contains(notResolvedModIDs, softDependency))
  291. return false;
  292. for(const TModID & conflict : mod.getConflicts())
  293. if(vstd::contains(resolvedModIDs, conflict))
  294. return false;
  295. for(const TModID & reverseConflict : resolvedModIDs)
  296. if(vstd::contains(modsStorage->getMod(reverseConflict).getConflicts(), mod.getID()))
  297. return false;
  298. return true;
  299. };
  300. while(true)
  301. {
  302. std::set<TModID> resolvedOnCurrentTreeLevel;
  303. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  304. {
  305. if(isResolved(modsStorage->getMod(*it)))
  306. {
  307. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node children will be resolved on the next iteration
  308. sortedValidMods.push_back(*it);
  309. it = modsToResolve.erase(it);
  310. continue;
  311. }
  312. it++;
  313. }
  314. if(!resolvedOnCurrentTreeLevel.empty())
  315. {
  316. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  317. for(const auto & it : resolvedOnCurrentTreeLevel)
  318. notResolvedModIDs.erase(it);
  319. continue;
  320. }
  321. // If there are no valid mods on the current mods tree level, no more mod can be resolved, should be ended.
  322. break;
  323. }
  324. assert(!sortedValidMods.empty());
  325. activeMods = sortedValidMods;
  326. brokenMods = modsToResolve;
  327. }
  328. // modLoadErrors = std::make_unique<MetaString>();
  329. //
  330. // auto addErrorMessage = [this](const std::string & textID, const std::string & brokenModID, const std::string & missingModID)
  331. // {
  332. // modLoadErrors->appendTextID(textID);
  333. //
  334. // if (allMods.count(brokenModID))
  335. // modLoadErrors->replaceRawString(allMods.at(brokenModID).getVerificationInfo().name);
  336. // else
  337. // modLoadErrors->replaceRawString(brokenModID);
  338. //
  339. // if (allMods.count(missingModID))
  340. // modLoadErrors->replaceRawString(allMods.at(missingModID).getVerificationInfo().name);
  341. // else
  342. // modLoadErrors->replaceRawString(missingModID);
  343. //
  344. // };
  345. //
  346. // // Left mods have unresolved dependencies, output all to log.
  347. // for(const auto & brokenModID : modsToResolve)
  348. // {
  349. // const CModInfo & brokenMod = allMods.at(brokenModID);
  350. // bool showErrorMessage = false;
  351. // for(const TModID & dependency : brokenMod.dependencies)
  352. // {
  353. // if(!vstd::contains(resolvedModIDs, dependency) && brokenMod.config["modType"].String() != "Compatibility")
  354. // {
  355. // addErrorMessage("vcmi.server.errors.modNoDependency", brokenModID, dependency);
  356. // showErrorMessage = true;
  357. // }
  358. // }
  359. // for(const TModID & conflict : brokenMod.conflicts)
  360. // {
  361. // if(vstd::contains(resolvedModIDs, conflict))
  362. // {
  363. // addErrorMessage("vcmi.server.errors.modConflict", brokenModID, conflict);
  364. // showErrorMessage = true;
  365. // }
  366. // }
  367. // for(const TModID & reverseConflict : resolvedModIDs)
  368. // {
  369. // if (vstd::contains(allMods.at(reverseConflict).conflicts, brokenModID))
  370. // {
  371. // addErrorMessage("vcmi.server.errors.modConflict", brokenModID, reverseConflict);
  372. // showErrorMessage = true;
  373. // }
  374. // }
  375. //
  376. // // some mods may in a (soft) dependency loop.
  377. // if(!showErrorMessage && brokenMod.config["modType"].String() != "Compatibility")
  378. // {
  379. // modLoadErrors->appendTextID("vcmi.server.errors.modDependencyLoop");
  380. // if (allMods.count(brokenModID))
  381. // modLoadErrors->replaceRawString(allMods.at(brokenModID).getVerificationInfo().name);
  382. // else
  383. // modLoadErrors->replaceRawString(brokenModID);
  384. // }
  385. //
  386. // }
  387. // return sortedValidMods;
  388. //}
  389. VCMI_LIB_NAMESPACE_END