CModHandler.cpp 16 KB

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