2
0

ModManager.cpp 18 KB

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