ModManager.cpp 14 KB

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