CModHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * CModHandler.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 "CModHandler.h"
  12. #include "CModInfo.h"
  13. #include "ModScope.h"
  14. #include "ContentTypeHandler.h"
  15. #include "IdentifierStorage.h"
  16. #include "ModIncompatibility.h"
  17. #include "../CCreatureHandler.h"
  18. #include "../CGeneralTextHandler.h"
  19. #include "../CStopWatch.h"
  20. #include "../GameSettings.h"
  21. #include "../Languages.h"
  22. #include "../ScriptHandler.h"
  23. #include "../constants/StringConstants.h"
  24. #include "../filesystem/Filesystem.h"
  25. #include "../spells/CSpellHandler.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. static JsonNode loadModSettings(const JsonPath & path)
  28. {
  29. if (CResourceHandler::get("local")->existsResource(ResourcePath(path)))
  30. {
  31. return JsonNode(path);
  32. }
  33. // Probably new install. Create initial configuration
  34. CResourceHandler::get("local")->createResource(path.getOriginalName() + ".json");
  35. return JsonNode();
  36. }
  37. CModHandler::CModHandler()
  38. : content(std::make_shared<CContentHandler>())
  39. , coreMod(std::make_unique<CModInfo>())
  40. {
  41. }
  42. CModHandler::~CModHandler() = default;
  43. // currentList is passed by value to get current list of depending mods
  44. bool CModHandler::hasCircularDependency(const TModID & modID, std::set<TModID> currentList) const
  45. {
  46. const CModInfo & mod = allMods.at(modID);
  47. // Mod already present? We found a loop
  48. if (vstd::contains(currentList, modID))
  49. {
  50. logMod->error("Error: Circular dependency detected! Printing dependency list:");
  51. logMod->error("\t%s -> ", mod.getVerificationInfo().name);
  52. return true;
  53. }
  54. currentList.insert(modID);
  55. // recursively check every dependency of this mod
  56. for(const TModID & dependency : mod.dependencies)
  57. {
  58. if (hasCircularDependency(dependency, currentList))
  59. {
  60. logMod->error("\t%s ->\n", mod.getVerificationInfo().name); // conflict detected, print dependency list
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. // Returned vector affects the resource loaders call order (see CFilesystemList::load).
  67. // The loaders call order matters when dependent mod overrides resources in its dependencies.
  68. std::vector <TModID> CModHandler::validateAndSortDependencies(std::vector <TModID> modsToResolve) const
  69. {
  70. // Topological sort algorithm.
  71. // TODO: Investigate possible ways to improve performance.
  72. boost::range::sort(modsToResolve); // Sort mods per name
  73. std::vector <TModID> sortedValidMods; // Vector keeps order of elements (LIFO)
  74. sortedValidMods.reserve(modsToResolve.size()); // push_back calls won't cause memory reallocation
  75. std::set <TModID> resolvedModIDs; // Use a set for validation for performance reason, but set does not keep order of elements
  76. // Mod is resolved if it has not dependencies or all its dependencies are already resolved
  77. auto isResolved = [&](const CModInfo & mod) -> CModInfo::EValidationStatus
  78. {
  79. if(mod.dependencies.size() > resolvedModIDs.size())
  80. return CModInfo::PENDING;
  81. for(const TModID & dependency : mod.dependencies)
  82. {
  83. if(!vstd::contains(resolvedModIDs, dependency))
  84. return CModInfo::PENDING;
  85. }
  86. return CModInfo::PASSED;
  87. };
  88. while(true)
  89. {
  90. std::set <TModID> resolvedOnCurrentTreeLevel;
  91. for(auto it = modsToResolve.begin(); it != modsToResolve.end();) // One iteration - one level of mods tree
  92. {
  93. if(isResolved(allMods.at(*it)) == CModInfo::PASSED)
  94. {
  95. resolvedOnCurrentTreeLevel.insert(*it); // Not to the resolvedModIDs, so current node childs will be resolved on the next iteration
  96. sortedValidMods.push_back(*it);
  97. it = modsToResolve.erase(it);
  98. continue;
  99. }
  100. it++;
  101. }
  102. if(!resolvedOnCurrentTreeLevel.empty())
  103. {
  104. resolvedModIDs.insert(resolvedOnCurrentTreeLevel.begin(), resolvedOnCurrentTreeLevel.end());
  105. continue;
  106. }
  107. // If there're no valid mods on the current mods tree level, no more mod can be resolved, should be end.
  108. break;
  109. }
  110. // Left mods have unresolved dependencies, output all to log.
  111. for(const auto & brokenModID : modsToResolve)
  112. {
  113. const CModInfo & brokenMod = allMods.at(brokenModID);
  114. for(const TModID & dependency : brokenMod.dependencies)
  115. {
  116. if(!vstd::contains(resolvedModIDs, dependency))
  117. logMod->error("Mod '%s' will not work: it depends on mod '%s', which is not installed.", brokenMod.getVerificationInfo().name, dependency);
  118. }
  119. }
  120. return sortedValidMods;
  121. }
  122. std::vector<std::string> CModHandler::getModList(const std::string & path) const
  123. {
  124. std::string modDir = boost::to_upper_copy(path + "MODS/");
  125. size_t depth = boost::range::count(modDir, '/');
  126. auto list = CResourceHandler::get("initial")->getFilteredFiles([&](const ResourcePath & id) -> bool
  127. {
  128. if (id.getType() != EResType::DIRECTORY)
  129. return false;
  130. if (!boost::algorithm::starts_with(id.getName(), modDir))
  131. return false;
  132. if (boost::range::count(id.getName(), '/') != depth )
  133. return false;
  134. return true;
  135. });
  136. //storage for found mods
  137. std::vector<std::string> foundMods;
  138. for(const auto & entry : list)
  139. {
  140. std::string name = entry.getName();
  141. name.erase(0, modDir.size()); //Remove path prefix
  142. if (!name.empty())
  143. foundMods.push_back(name);
  144. }
  145. return foundMods;
  146. }
  147. void CModHandler::loadMods(const std::string & path, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  148. {
  149. for(const std::string & modName : getModList(path))
  150. loadOneMod(modName, parent, modSettings, enableMods);
  151. }
  152. void CModHandler::loadOneMod(std::string modName, const std::string & parent, const JsonNode & modSettings, bool enableMods)
  153. {
  154. boost::to_lower(modName);
  155. std::string modFullName = parent.empty() ? modName : parent + '.' + modName;
  156. if ( ModScope::isScopeReserved(modFullName))
  157. {
  158. logMod->error("Can not load mod %s - this name is reserved for internal use!", modFullName);
  159. return;
  160. }
  161. if(CResourceHandler::get("initial")->existsResource(CModInfo::getModFile(modFullName)))
  162. {
  163. CModInfo mod(modFullName, modSettings[modName], JsonNode(CModInfo::getModFile(modFullName)));
  164. if (!parent.empty()) // this is submod, add parent to dependencies
  165. mod.dependencies.insert(parent);
  166. allMods[modFullName] = mod;
  167. if (mod.isEnabled() && enableMods)
  168. activeMods.push_back(modFullName);
  169. loadMods(CModInfo::getModDir(modFullName) + '/', modFullName, modSettings[modName]["mods"], enableMods && mod.isEnabled());
  170. }
  171. }
  172. void CModHandler::loadMods(bool onlyEssential)
  173. {
  174. JsonNode modConfig;
  175. if(onlyEssential)
  176. {
  177. loadOneMod("vcmi", "", modConfig, true);//only vcmi and submods
  178. }
  179. else
  180. {
  181. modConfig = loadModSettings(JsonPath::builtin("config/modSettings.json"));
  182. loadMods("", "", modConfig["activeMods"], true);
  183. }
  184. coreMod = std::make_unique<CModInfo>(ModScope::scopeBuiltin(), modConfig[ModScope::scopeBuiltin()], JsonNode(JsonPath::builtin("config/gameConfig.json")));
  185. }
  186. std::vector<std::string> CModHandler::getAllMods()
  187. {
  188. std::vector<std::string> modlist;
  189. modlist.reserve(allMods.size());
  190. for (auto & entry : allMods)
  191. modlist.push_back(entry.first);
  192. return modlist;
  193. }
  194. std::vector<std::string> CModHandler::getActiveMods()
  195. {
  196. return activeMods;
  197. }
  198. const CModInfo & CModHandler::getModInfo(const TModID & modId) const
  199. {
  200. return allMods.at(modId);
  201. }
  202. static JsonNode genDefaultFS()
  203. {
  204. // default FS config for mods: directory "Content" that acts as H3 root directory
  205. JsonNode defaultFS;
  206. defaultFS[""].Vector().resize(2);
  207. defaultFS[""].Vector()[0]["type"].String() = "zip";
  208. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  209. defaultFS[""].Vector()[1]["type"].String() = "dir";
  210. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  211. return defaultFS;
  212. }
  213. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  214. {
  215. static const JsonNode defaultFS = genDefaultFS();
  216. if (!conf["filesystem"].isNull())
  217. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), conf["filesystem"]);
  218. else
  219. return CResourceHandler::createFileSystem(CModInfo::getModDir(modName), defaultFS);
  220. }
  221. static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  222. {
  223. boost::crc_32_type modChecksum;
  224. // first - add current VCMI version into checksum to force re-validation on VCMI updates
  225. modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  226. // second - add mod.json into checksum because filesystem does not contains this file
  227. // FIXME: remove workaround for core mod
  228. if (modName != ModScope::scopeBuiltin())
  229. {
  230. auto modConfFile = CModInfo::getModFile(modName);
  231. ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  232. modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  233. }
  234. // third - add all detected text files from this mod into checksum
  235. auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  236. {
  237. return (resID.getType() == EResType::TEXT || resID.getType() == EResType::JSON) &&
  238. ( boost::starts_with(resID.getName(), "DATA") || boost::starts_with(resID.getName(), "CONFIG"));
  239. });
  240. for (const ResourcePath & file : files)
  241. {
  242. ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  243. modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  244. }
  245. return modChecksum.checksum();
  246. }
  247. void CModHandler::loadModFilesystems()
  248. {
  249. CGeneralTextHandler::detectInstallParameters();
  250. activeMods = validateAndSortDependencies(activeMods);
  251. coreMod->updateChecksum(calculateModChecksum(ModScope::scopeBuiltin(), CResourceHandler::get(ModScope::scopeBuiltin())));
  252. for(std::string & modName : activeMods)
  253. {
  254. CModInfo & mod = allMods[modName];
  255. CResourceHandler::addFilesystem("data", modName, genModFilesystem(modName, mod.config));
  256. }
  257. }
  258. TModID CModHandler::findResourceOrigin(const ResourcePath & name)
  259. {
  260. for(const auto & modID : boost::adaptors::reverse(activeMods))
  261. {
  262. if(CResourceHandler::get(modID)->existsResource(name))
  263. return modID;
  264. }
  265. if(CResourceHandler::get("core")->existsResource(name))
  266. return "core";
  267. if(CResourceHandler::get("mapEditor")->existsResource(name))
  268. return "core"; // Workaround for loading maps via map editor
  269. assert(0);
  270. return "";
  271. }
  272. std::string CModHandler::getModLanguage(const TModID& modId) const
  273. {
  274. if ( modId == "core")
  275. return VLC->generaltexth->getInstalledLanguage();
  276. return allMods.at(modId).baseLanguage;
  277. }
  278. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  279. {
  280. auto it = allMods.find(modId);
  281. isModFound = (it != allMods.end());
  282. if(isModFound)
  283. return it->second.dependencies;
  284. logMod->error("Mod not found: '%s'", modId);
  285. return {};
  286. }
  287. void CModHandler::initializeConfig()
  288. {
  289. VLC->settingsHandler->load(coreMod->config["settings"]);
  290. for(const TModID & modName : activeMods)
  291. {
  292. const auto & mod = allMods[modName];
  293. if (!mod.config["settings"].isNull())
  294. VLC->settingsHandler->load(mod.config["settings"]);
  295. }
  296. }
  297. CModVersion CModHandler::getModVersion(TModID modName) const
  298. {
  299. if (allMods.count(modName))
  300. return allMods.at(modName).getVerificationInfo().version;
  301. return {};
  302. }
  303. bool CModHandler::validateTranslations(TModID modName) const
  304. {
  305. bool result = true;
  306. const auto & mod = allMods.at(modName);
  307. {
  308. auto fileList = mod.config["translations"].convertTo<std::vector<std::string> >();
  309. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  310. result |= VLC->generaltexth->validateTranslation(mod.baseLanguage, modName, json);
  311. }
  312. for(const auto & language : Languages::getLanguageList())
  313. {
  314. if (!language.hasTranslation)
  315. continue;
  316. if (mod.config[language.identifier].isNull())
  317. continue;
  318. if (mod.config[language.identifier]["skipValidation"].Bool())
  319. continue;
  320. auto fileList = mod.config[language.identifier]["translations"].convertTo<std::vector<std::string> >();
  321. JsonNode json = JsonUtils::assembleFromFiles(fileList);
  322. result |= VLC->generaltexth->validateTranslation(language.identifier, modName, json);
  323. }
  324. return result;
  325. }
  326. void CModHandler::loadTranslation(const TModID & modName)
  327. {
  328. const auto & mod = allMods[modName];
  329. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  330. std::string modBaseLanguage = allMods[modName].baseLanguage;
  331. auto baseTranslationList = mod.config["translations"].convertTo<std::vector<std::string> >();
  332. auto extraTranslationList = mod.config[preferredLanguage]["translations"].convertTo<std::vector<std::string> >();
  333. JsonNode baseTranslation = JsonUtils::assembleFromFiles(baseTranslationList);
  334. JsonNode extraTranslation = JsonUtils::assembleFromFiles(extraTranslationList);
  335. VLC->generaltexth->loadTranslationOverrides(modBaseLanguage, modName, baseTranslation);
  336. VLC->generaltexth->loadTranslationOverrides(preferredLanguage, modName, extraTranslation);
  337. }
  338. void CModHandler::load()
  339. {
  340. CStopWatch totalTime;
  341. CStopWatch timer;
  342. logMod->info("\tInitializing content handler: %d ms", timer.getDiff());
  343. content->init();
  344. for(const TModID & modName : activeMods)
  345. {
  346. logMod->trace("Generating checksum for %s", modName);
  347. allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  348. }
  349. // first - load virtual builtin mod that contains all data
  350. // TODO? move all data into real mods? RoE, AB, SoD, WoG
  351. content->preloadData(*coreMod);
  352. for(const TModID & modName : activeMods)
  353. content->preloadData(allMods[modName]);
  354. logMod->info("\tParsing mod data: %d ms", timer.getDiff());
  355. content->load(*coreMod);
  356. for(const TModID & modName : activeMods)
  357. content->load(allMods[modName]);
  358. #if SCRIPTING_ENABLED
  359. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  360. #endif
  361. content->loadCustom();
  362. for(const TModID & modName : activeMods)
  363. loadTranslation(modName);
  364. for(const TModID & modName : activeMods)
  365. if (!validateTranslations(modName))
  366. allMods[modName].validation = CModInfo::FAILED;
  367. logMod->info("\tLoading mod data: %d ms", timer.getDiff());
  368. VLC->creh->loadCrExpMod();
  369. VLC->identifiersHandler->finalize();
  370. logMod->info("\tResolving identifiers: %d ms", timer.getDiff());
  371. content->afterLoadFinalization();
  372. logMod->info("\tHandlers post-load finalization: %d ms ", timer.getDiff());
  373. logMod->info("\tAll game content loaded in %d ms", totalTime.getDiff());
  374. }
  375. void CModHandler::afterLoad(bool onlyEssential)
  376. {
  377. JsonNode modSettings;
  378. for (auto & modEntry : allMods)
  379. {
  380. std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  381. modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  382. }
  383. modSettings[ModScope::scopeBuiltin()] = coreMod->saveLocalData();
  384. modSettings[ModScope::scopeBuiltin()]["name"].String() = "Original game files";
  385. if(!onlyEssential)
  386. {
  387. std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  388. file << modSettings.toJson();
  389. }
  390. }
  391. void CModHandler::trySetActiveMods(const std::vector<std::pair<TModID, CModInfo::VerificationInfo>> & modList)
  392. {
  393. auto searchVerificationInfo = [&modList](const TModID & m) -> const CModInfo::VerificationInfo*
  394. {
  395. for(auto & i : modList)
  396. if(i.first == m)
  397. return &i.second;
  398. return nullptr;
  399. };
  400. std::vector<TModID> missingMods, excessiveMods;
  401. ModIncompatibility::ModListWithVersion missingModsResult;
  402. ModIncompatibility::ModList excessiveModsResult;
  403. for(const auto & m : activeMods)
  404. {
  405. if(searchVerificationInfo(m))
  406. continue;
  407. //TODO: support actual disabling of these mods
  408. if(getModInfo(m).checkModGameplayAffecting())
  409. excessiveMods.push_back(m);
  410. }
  411. for(const auto & infoPair : modList)
  412. {
  413. auto & remoteModId = infoPair.first;
  414. auto & remoteModInfo = infoPair.second;
  415. bool modAffectsGameplay = remoteModInfo.impactsGameplay;
  416. //parent mod affects gameplay if child affects too
  417. for(const auto & subInfoPair : modList)
  418. modAffectsGameplay |= (subInfoPair.second.impactsGameplay && subInfoPair.second.parent == remoteModId);
  419. if(!allMods.count(remoteModId))
  420. {
  421. if(modAffectsGameplay)
  422. missingMods.push_back(remoteModId); //mod is not installed
  423. continue;
  424. }
  425. auto & localModInfo = getModInfo(remoteModId).getVerificationInfo();
  426. modAffectsGameplay |= getModInfo(remoteModId).checkModGameplayAffecting();
  427. bool modVersionCompatible = localModInfo.version.isNull()
  428. || remoteModInfo.version.isNull()
  429. || localModInfo.version.compatible(remoteModInfo.version);
  430. bool modLocalyEnabled = vstd::contains(activeMods, remoteModId);
  431. if(modVersionCompatible && modAffectsGameplay && modLocalyEnabled)
  432. continue;
  433. if(modAffectsGameplay)
  434. missingMods.push_back(remoteModId); //incompatible mod impacts gameplay
  435. }
  436. //filter mods
  437. for(auto & m : missingMods)
  438. {
  439. if(auto * vInfo = searchVerificationInfo(m))
  440. {
  441. assert(vInfo->parent != m);
  442. if(!vInfo->parent.empty() && vstd::contains(missingMods, vInfo->parent))
  443. continue;
  444. missingModsResult.push_back({vInfo->name, vInfo->version.toString()});
  445. }
  446. }
  447. for(auto & m : excessiveMods)
  448. {
  449. auto & vInfo = getModInfo(m).getVerificationInfo();
  450. assert(vInfo.parent != m);
  451. if(!vInfo.parent.empty() && vstd::contains(excessiveMods, vInfo.parent))
  452. continue;
  453. excessiveModsResult.push_back(vInfo.name);
  454. }
  455. if(!missingModsResult.empty() || !excessiveModsResult.empty())
  456. throw ModIncompatibility(missingModsResult, excessiveModsResult);
  457. //TODO: support actual enabling of required mods
  458. }
  459. VCMI_LIB_NAMESPACE_END