CModHandler.cpp 18 KB

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