ModManager.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 "../constants/StringConstants.h"
  15. #include "../filesystem/Filesystem.h"
  16. #include "../json/JsonNode.h"
  17. #include "../texts/CGeneralTextHandler.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. static std::string getModDirectory(const TModID & modName)
  20. {
  21. std::string result = modName;
  22. boost::to_upper(result);
  23. boost::algorithm::replace_all(result, ".", "/MODS/");
  24. return "MODS/" + result;
  25. }
  26. static std::string getModSettingsDirectory(const TModID & modName)
  27. {
  28. return getModDirectory(modName) + "/MODS/";
  29. }
  30. static JsonPath getModDescriptionFile(const TModID & modName)
  31. {
  32. return JsonPath::builtin(getModDirectory(modName) + "/mod");
  33. }
  34. ModsState::ModsState()
  35. {
  36. modList.push_back(ModScope::scopeBuiltin());
  37. std::vector<TModID> testLocations = scanModsDirectory("MODS/");
  38. while(!testLocations.empty())
  39. {
  40. std::string target = testLocations.back();
  41. testLocations.pop_back();
  42. modList.push_back(boost::algorithm::to_lower_copy(target));
  43. for(const auto & submod : scanModsDirectory(getModSettingsDirectory(target)))
  44. testLocations.push_back(target + '.' + submod);
  45. }
  46. }
  47. TModList ModsState::getInstalledMods() const
  48. {
  49. return modList;
  50. }
  51. uint32_t ModsState::computeChecksum(const TModID & modName) const
  52. {
  53. boost::crc_32_type modChecksum;
  54. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  55. modChecksum.process_bytes(static_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  56. // second - add mod.json into checksum because filesystem does not contains this file
  57. if (modName != ModScope::scopeBuiltin())
  58. {
  59. auto modConfFile = getModDescriptionFile(modName);
  60. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  61. modChecksum.process_bytes(static_cast<const void *>(&configChecksum), sizeof(configChecksum));
  62. }
  63. // third - add all detected text files from this mod into checksum
  64. const auto & filesystem = CResourceHandler::get(modName);
  65. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  66. {
  67. return resID.getType() == EResType::JSON && boost::starts_with(resID.getName(), "CONFIG");
  68. });
  69. for (const ResourcePath & file : files)
  70. {
  71. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  72. modChecksum.process_bytes(static_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  73. }
  74. return modChecksum.checksum();
  75. }
  76. double ModsState::getInstalledModSizeMegabytes(const TModID & modName) const
  77. {
  78. ResourcePath resDir(getModDirectory(modName), EResType::DIRECTORY);
  79. std::string path = CResourceHandler::get()->getResourceName(resDir)->string();
  80. size_t sizeBytes = 0;
  81. for(boost::filesystem::recursive_directory_iterator it(path); it != boost::filesystem::recursive_directory_iterator(); ++it)
  82. {
  83. if(!boost::filesystem::is_directory(*it))
  84. sizeBytes += boost::filesystem::file_size(*it);
  85. }
  86. double sizeMegabytes = sizeBytes / static_cast<double>(1024*1024);
  87. return sizeMegabytes;
  88. }
  89. std::vector<TModID> ModsState::scanModsDirectory(const std::string & modDir) const
  90. {
  91. size_t depth = boost::range::count(modDir, '/');
  92. const auto & modScanFilter = [&](const ResourcePath & id) -> bool
  93. {
  94. if(id.getType() != EResType::DIRECTORY)
  95. return false;
  96. if(!boost::algorithm::starts_with(id.getName(), modDir))
  97. return false;
  98. if(boost::range::count(id.getName(), '/') != depth)
  99. return false;
  100. return true;
  101. };
  102. auto list = CResourceHandler::get("initial")->getFilteredFiles(modScanFilter);
  103. //storage for found mods
  104. std::vector<TModID> foundMods;
  105. for(const auto & entry : list)
  106. {
  107. std::string name = entry.getName();
  108. name.erase(0, modDir.size()); //Remove path prefix
  109. if(name.empty())
  110. continue;
  111. if(name.find('.') != std::string::npos)
  112. continue;
  113. if (ModScope::isScopeReserved(boost::to_lower_copy(name)))
  114. continue;
  115. if(!CResourceHandler::get("initial")->existsResource(JsonPath::builtin(entry.getName() + "/MOD")))
  116. continue;
  117. foundMods.push_back(name);
  118. }
  119. return foundMods;
  120. }
  121. ///////////////////////////////////////////////////////////////////////////////
  122. ModsPresetState::ModsPresetState()
  123. {
  124. static const JsonPath settingsPath = JsonPath::builtin("config/modSettings.json");
  125. if(CResourceHandler::get("local")->existsResource(ResourcePath(settingsPath)))
  126. {
  127. modConfig = JsonNode(settingsPath);
  128. }
  129. else
  130. {
  131. // Probably new install. Create initial configuration
  132. CResourceHandler::get("local")->createResource(settingsPath.getOriginalName() + ".json");
  133. }
  134. if(modConfig["presets"].isNull())
  135. {
  136. modConfig["activePreset"] = JsonNode("default");
  137. if(modConfig["activeMods"].isNull())
  138. createInitialPreset(); // new install
  139. else
  140. importInitialPreset(); // 1.5 format import
  141. }
  142. }
  143. void ModsPresetState::createInitialPreset()
  144. {
  145. // TODO: scan mods directory for all its content? Probably unnecessary since this looks like new install, but who knows?
  146. modConfig["presets"]["default"]["mods"].Vector().emplace_back("vcmi");
  147. }
  148. void ModsPresetState::importInitialPreset()
  149. {
  150. JsonNode preset;
  151. for(const auto & mod : modConfig["activeMods"].Struct())
  152. {
  153. if(mod.second["active"].Bool())
  154. preset["mods"].Vector().emplace_back(mod.first);
  155. for(const auto & submod : mod.second["mods"].Struct())
  156. preset["settings"][mod.first][submod.first] = submod.second["active"];
  157. }
  158. modConfig["presets"]["default"] = preset;
  159. }
  160. const JsonNode & ModsPresetState::getActivePresetConfig() const
  161. {
  162. const std::string & currentPresetName = modConfig["activePreset"].String();
  163. const JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  164. return currentPreset;
  165. }
  166. TModList ModsPresetState::getActiveRootMods() const
  167. {
  168. const JsonNode & modsToActivateJson = getActivePresetConfig()["mods"];
  169. auto modsToActivate = modsToActivateJson.convertTo<std::vector<TModID>>();
  170. modsToActivate.push_back(ModScope::scopeBuiltin());
  171. return modsToActivate;
  172. }
  173. std::map<TModID, bool> ModsPresetState::getModSettings(const TModID & modID) const
  174. {
  175. const JsonNode & modSettingsJson = getActivePresetConfig()["settings"][modID];
  176. auto modSettings = modSettingsJson.convertTo<std::map<TModID, bool>>();
  177. return modSettings;
  178. }
  179. std::optional<uint32_t> ModsPresetState::getValidatedChecksum(const TModID & modName) const
  180. {
  181. const JsonNode & node = modConfig["validatedMods"][modName];
  182. if (node.isNull())
  183. return std::nullopt;
  184. else
  185. return node.Integer();
  186. }
  187. void ModsPresetState::setModActive(const TModID & modID, bool isActive)
  188. {
  189. size_t dotPos = modID.find('.');
  190. if(dotPos != std::string::npos)
  191. {
  192. std::string rootMod = modID.substr(0, dotPos);
  193. std::string settingID = modID.substr(dotPos + 1);
  194. setSettingActive(rootMod, settingID, isActive);
  195. }
  196. else
  197. {
  198. if (isActive)
  199. addRootMod(modID);
  200. else
  201. eraseRootMod(modID);
  202. }
  203. }
  204. void ModsPresetState::addRootMod(const TModID & modName)
  205. {
  206. const std::string & currentPresetName = modConfig["activePreset"].String();
  207. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  208. if (!vstd::contains(currentPreset["mods"].Vector(), JsonNode(modName)))
  209. currentPreset["mods"].Vector().emplace_back(modName);
  210. }
  211. void ModsPresetState::setSettingActive(const TModID & modName, const TModID & settingName, bool isActive)
  212. {
  213. const std::string & currentPresetName = modConfig["activePreset"].String();
  214. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  215. currentPreset["settings"][modName][settingName].Bool() = isActive;
  216. }
  217. void ModsPresetState::eraseRootMod(const TModID & modName)
  218. {
  219. const std::string & currentPresetName = modConfig["activePreset"].String();
  220. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  221. vstd::erase(currentPreset["mods"].Vector(), JsonNode(modName));
  222. }
  223. void ModsPresetState::eraseModSetting(const TModID & modName, const TModID & settingName)
  224. {
  225. const std::string & currentPresetName = modConfig["activePreset"].String();
  226. JsonNode & currentPreset = modConfig["presets"][currentPresetName];
  227. currentPreset["settings"][modName].Struct().erase(modName);
  228. }
  229. std::vector<TModID> ModsPresetState::getActiveMods() const
  230. {
  231. TModList activeRootMods = getActiveRootMods();
  232. TModList allActiveMods;
  233. for(const auto & activeMod : activeRootMods)
  234. {
  235. allActiveMods.push_back(activeMod);
  236. for(const auto & submod : getModSettings(activeMod))
  237. if(submod.second)
  238. allActiveMods.push_back(activeMod + '.' + submod.first);
  239. }
  240. return allActiveMods;
  241. }
  242. void ModsPresetState::setValidatedChecksum(const TModID & modName, std::optional<uint32_t> value)
  243. {
  244. if (value.has_value())
  245. modConfig["validatedMods"][modName].Integer() = *value;
  246. else
  247. modConfig["validatedMods"].Struct().erase(modName);
  248. }
  249. void ModsPresetState::saveConfigurationState() const
  250. {
  251. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  252. file << modConfig.toCompactString();
  253. }
  254. ModsStorage::ModsStorage(const std::vector<TModID> & modsToLoad, const JsonNode & repositoryList)
  255. {
  256. JsonNode coreModConfig(JsonPath::builtin("config/gameConfig.json"));
  257. coreModConfig.setModScope(ModScope::scopeBuiltin());
  258. mods.try_emplace(ModScope::scopeBuiltin(), ModScope::scopeBuiltin(), coreModConfig, JsonNode());
  259. for(auto modID : modsToLoad)
  260. {
  261. if(ModScope::isScopeReserved(modID))
  262. continue;
  263. JsonNode modConfig(getModDescriptionFile(modID));
  264. modConfig.setModScope(modID);
  265. if(modConfig["modType"].isNull())
  266. {
  267. logMod->error("Can not load mod %s - invalid mod config file!", modID);
  268. continue;
  269. }
  270. mods.try_emplace(modID, modID, modConfig, repositoryList[modID]);
  271. }
  272. for(const auto & mod : repositoryList.Struct())
  273. {
  274. if (vstd::contains(modsToLoad, mod.first))
  275. continue;
  276. if (mod.second["modType"].isNull() || mod.second["name"].isNull())
  277. continue;
  278. mods.try_emplace(mod.first, mod.first, JsonNode(), mod.second);
  279. }
  280. }
  281. const ModDescription & ModsStorage::getMod(const TModID & fullID) const
  282. {
  283. return mods.at(fullID);
  284. }
  285. TModList ModsStorage::getAllMods() const
  286. {
  287. TModList result;
  288. for (const auto & mod : mods)
  289. result.push_back(mod.first);
  290. return result;
  291. }
  292. ModManager::ModManager()
  293. :ModManager(JsonNode())
  294. {
  295. }
  296. ModManager::ModManager(const JsonNode & repositoryList)
  297. : modsState(std::make_unique<ModsState>())
  298. , modsPreset(std::make_unique<ModsPresetState>())
  299. {
  300. modsStorage = std::make_unique<ModsStorage>(modsState->getInstalledMods(), repositoryList);
  301. eraseMissingModsFromPreset();
  302. addNewModsToPreset();
  303. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  304. depedencyResolver = std::make_unique<ModDependenciesResolver>(desiredModList, *modsStorage);
  305. }
  306. ModManager::~ModManager() = default;
  307. const ModDescription & ModManager::getModDescription(const TModID & modID) const
  308. {
  309. assert(boost::to_lower_copy(modID) == modID);
  310. return modsStorage->getMod(modID);
  311. }
  312. bool ModManager::isModActive(const TModID & modID) const
  313. {
  314. return vstd::contains(getActiveMods(), modID);
  315. }
  316. const TModList & ModManager::getActiveMods() const
  317. {
  318. return depedencyResolver->getActiveMods();
  319. }
  320. uint32_t ModManager::computeChecksum(const TModID & modName) const
  321. {
  322. return modsState->computeChecksum(modName);
  323. }
  324. std::optional<uint32_t> ModManager::getValidatedChecksum(const TModID & modName) const
  325. {
  326. return modsPreset->getValidatedChecksum(modName);
  327. }
  328. void ModManager::setValidatedChecksum(const TModID & modName, std::optional<uint32_t> value)
  329. {
  330. modsPreset->setValidatedChecksum(modName, value);
  331. }
  332. void ModManager::saveConfigurationState() const
  333. {
  334. modsPreset->saveConfigurationState();
  335. }
  336. TModList ModManager::getAllMods() const
  337. {
  338. return modsStorage->getAllMods();
  339. }
  340. double ModManager::getInstalledModSizeMegabytes(const TModID & modName) const
  341. {
  342. return modsState->getInstalledModSizeMegabytes(modName);
  343. }
  344. void ModManager::eraseMissingModsFromPreset()
  345. {
  346. const TModList & installedMods = modsState->getInstalledMods();
  347. const TModList & rootMods = modsPreset->getActiveRootMods();
  348. for(const auto & rootMod : rootMods)
  349. {
  350. if(!vstd::contains(installedMods, rootMod))
  351. {
  352. modsPreset->eraseRootMod(rootMod);
  353. continue;
  354. }
  355. const auto & modSettings = modsPreset->getModSettings(rootMod);
  356. for(const auto & modSetting : modSettings)
  357. {
  358. TModID fullModID = rootMod + '.' + modSetting.first;
  359. if(!vstd::contains(installedMods, fullModID))
  360. {
  361. modsPreset->eraseModSetting(rootMod, modSetting.first);
  362. continue;
  363. }
  364. }
  365. }
  366. }
  367. void ModManager::addNewModsToPreset()
  368. {
  369. const TModList & installedMods = modsState->getInstalledMods();
  370. for(const auto & modID : installedMods)
  371. {
  372. size_t dotPos = modID.find('.');
  373. if(dotPos == std::string::npos)
  374. continue; // only look up submods aka mod settings
  375. std::string rootMod = modID.substr(0, dotPos);
  376. std::string settingID = modID.substr(dotPos + 1);
  377. const auto & modSettings = modsPreset->getModSettings(rootMod);
  378. if (!modSettings.count(settingID))
  379. modsPreset->setSettingActive(rootMod, settingID, modsStorage->getMod(modID).keepDisabled());
  380. }
  381. }
  382. TModList ModManager::collectDependenciesRecursive(const TModID & modID) const
  383. {
  384. TModList result;
  385. TModList toTest;
  386. toTest.push_back(modID);
  387. while (!toTest.empty())
  388. {
  389. TModID currentModID = toTest.back();
  390. const auto & currentMod = getModDescription(currentModID);
  391. toTest.pop_back();
  392. result.push_back(currentModID);
  393. if (!currentMod.isInstalled())
  394. throw std::runtime_error("Unable to enable mod " + modID + "! Dependency " + currentModID + " is not installed!");
  395. for (const auto & dependency : currentMod.getDependencies())
  396. {
  397. if (!vstd::contains(result, dependency))
  398. toTest.push_back(dependency);
  399. }
  400. }
  401. return result;
  402. }
  403. void ModManager::tryEnableMods(const TModList & modList)
  404. {
  405. TModList requiredActiveMods;
  406. TModList additionalActiveMods = getActiveMods();
  407. for (const auto & modName : modList)
  408. {
  409. for (const auto & dependency : collectDependenciesRecursive(modName))
  410. if (!vstd::contains(requiredActiveMods, dependency))
  411. requiredActiveMods.push_back(dependency);
  412. assert(!vstd::contains(additionalActiveMods, modName));
  413. assert(vstd::contains(requiredActiveMods, modName));// FIXME: fails on attempt to enable broken mod / translation to other language
  414. }
  415. ModDependenciesResolver testResolver(requiredActiveMods, *modsStorage);
  416. assert(testResolver.getBrokenMods().empty());
  417. testResolver.tryAddMods(additionalActiveMods, *modsStorage);
  418. for (const auto & modName : modList)
  419. {
  420. assert(vstd::contains(testResolver.getActiveMods(), modName));
  421. if (!vstd::contains(testResolver.getActiveMods(), modName))
  422. throw std::runtime_error("Failed to enable mod! Mod " + modName + " remains disabled!");
  423. }
  424. updatePreset(testResolver);
  425. }
  426. void ModManager::tryDisableMod(const TModID & modName)
  427. {
  428. auto desiredActiveMods = getActiveMods();
  429. assert(vstd::contains(desiredActiveMods, modName));
  430. vstd::erase(desiredActiveMods, modName);
  431. ModDependenciesResolver testResolver(desiredActiveMods, *modsStorage);
  432. if (vstd::contains(testResolver.getActiveMods(), modName))
  433. throw std::runtime_error("Failed to disable mod! Mod " + modName + " remains enabled!");
  434. updatePreset(testResolver);
  435. }
  436. void ModManager::updatePreset(const ModDependenciesResolver & testResolver)
  437. {
  438. const auto & newActiveMods = testResolver.getActiveMods();
  439. const auto & newBrokenMods = testResolver.getBrokenMods();
  440. for (const auto & modID : newActiveMods)
  441. {
  442. assert(vstd::contains(modsState->getInstalledMods(), modID));
  443. modsPreset->setModActive(modID, true);
  444. }
  445. for (const auto & modID : newBrokenMods)
  446. modsPreset->setModActive(modID, false);
  447. std::vector<TModID> desiredModList = modsPreset->getActiveMods();
  448. depedencyResolver = std::make_unique<ModDependenciesResolver>(desiredModList, *modsStorage);
  449. // TODO: check activation status of submods of new mods
  450. modsPreset->saveConfigurationState();
  451. }
  452. ModDependenciesResolver::ModDependenciesResolver(const TModList & modsToResolve, const ModsStorage & storage)
  453. {
  454. tryAddMods(modsToResolve, storage);
  455. }
  456. const TModList & ModDependenciesResolver::getActiveMods() const
  457. {
  458. return activeMods;
  459. }
  460. const TModList & ModDependenciesResolver::getBrokenMods() const
  461. {
  462. return brokenMods;
  463. }
  464. void ModDependenciesResolver::tryAddMods(TModList modsToResolve, const ModsStorage & storage)
  465. {
  466. // Topological sort algorithm.
  467. boost::range::sort(modsToResolve); // Sort mods per name
  468. std::vector<TModID> sortedValidMods(activeMods.begin(), activeMods.end()); // Vector keeps order of elements (LIFO)
  469. std::set<TModID> resolvedModIDs(activeMods.begin(), activeMods.end()); // Use a set for validation for performance reason, but set does not keep order of elements
  470. std::set<TModID> notResolvedModIDs(modsToResolve.begin(), modsToResolve.end()); // Use a set for validation for performance reason
  471. // Mod is resolved if it has no dependencies or all its dependencies are already resolved
  472. auto isResolved = [&](const ModDescription & mod) -> bool
  473. {
  474. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage())
  475. return false;
  476. if(mod.getDependencies().size() > resolvedModIDs.size())
  477. return false;
  478. for(const TModID & dependency : mod.getDependencies())
  479. if(!vstd::contains(resolvedModIDs, dependency))
  480. return false;
  481. for(const TModID & softDependency : mod.getSoftDependencies())
  482. if(vstd::contains(notResolvedModIDs, softDependency))
  483. return false;
  484. for(const TModID & conflict : mod.getConflicts())
  485. if(vstd::contains(resolvedModIDs, conflict))
  486. return false;
  487. for(const TModID & reverseConflict : resolvedModIDs)
  488. if(vstd::contains(storage.getMod(reverseConflict).getConflicts(), mod.getID()))
  489. return false;
  490. return true;
  491. };
  492. while(true)
  493. {
  494. std::set<TModID> resolvedOnCurrentTreeLevel;
  495. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  496. {
  497. if(isResolved(storage.getMod(*it)))
  498. {
  499. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node children will be resolved on the next iteration
  500. sortedValidMods.push_back(*it);
  501. it = modsToResolve.erase(it);
  502. continue;
  503. }
  504. it++;
  505. }
  506. if(!resolvedOnCurrentTreeLevel.empty())
  507. {
  508. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  509. for(const auto & it : resolvedOnCurrentTreeLevel)
  510. notResolvedModIDs.erase(it);
  511. continue;
  512. }
  513. // If there are no valid mods on the current mods tree level, no more mod can be resolved, should be ended.
  514. break;
  515. }
  516. assert(!sortedValidMods.empty());
  517. activeMods = sortedValidMods;
  518. brokenMods.insert(brokenMods.end(), modsToResolve.begin(), modsToResolve.end());
  519. }
  520. VCMI_LIB_NAMESPACE_END