CModHandler.cpp 18 KB

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