CModHandler.cpp 17 KB

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