CModHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 "ContentTypeHandler.h"
  13. #include "IdentifierStorage.h"
  14. #include "ModDescription.h"
  15. #include "ModManager.h"
  16. #include "ModScope.h"
  17. #include "../CConfigHandler.h"
  18. #include "../CCreatureHandler.h"
  19. #include "../GameSettings.h"
  20. #include "../ScriptHandler.h"
  21. #include "../VCMI_Lib.h"
  22. #include "../filesystem/Filesystem.h"
  23. #include "../json/JsonUtils.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include "../texts/Languages.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. CModHandler::CModHandler()
  28. : content(std::make_shared<CContentHandler>())
  29. , modManager(std::make_unique<ModManager>())
  30. {
  31. }
  32. CModHandler::~CModHandler() = default;
  33. std::vector<std::string> CModHandler::getAllMods() const
  34. {
  35. return modManager->getAllMods();
  36. }
  37. const std::vector<std::string> & CModHandler::getActiveMods() const
  38. {
  39. return modManager->getActiveMods();
  40. }
  41. const ModDescription & CModHandler::getModInfo(const TModID & modId) const
  42. {
  43. return modManager->getModDescription(modId);
  44. }
  45. static JsonNode genDefaultFS()
  46. {
  47. // default FS config for mods: directory "Content" that acts as H3 root directory
  48. JsonNode defaultFS;
  49. defaultFS[""].Vector().resize(2);
  50. defaultFS[""].Vector()[0]["type"].String() = "zip";
  51. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  52. defaultFS[""].Vector()[1]["type"].String() = "dir";
  53. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  54. return defaultFS;
  55. }
  56. static std::string getModDirectory(const TModID & modName)
  57. {
  58. std::string result = modName;
  59. boost::to_upper(result);
  60. boost::algorithm::replace_all(result, ".", "/MODS/");
  61. return "MODS/" + result;
  62. }
  63. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  64. {
  65. static const JsonNode defaultFS = genDefaultFS();
  66. if (!conf.isNull())
  67. return CResourceHandler::createFileSystem(getModDirectory(modName), conf);
  68. else
  69. return CResourceHandler::createFileSystem(getModDirectory(modName), defaultFS);
  70. }
  71. void CModHandler::loadModFilesystems()
  72. {
  73. CGeneralTextHandler::detectInstallParameters();
  74. const auto & activeMods = modManager->getActiveMods();
  75. std::map<TModID, ISimpleResourceLoader *> modFilesystems;
  76. for(const TModID & modName : activeMods)
  77. modFilesystems[modName] = genModFilesystem(modName, getModInfo(modName).getFilesystemConfig());
  78. for(const TModID & modName : activeMods)
  79. CResourceHandler::addFilesystem("data", modName, modFilesystems[modName]);
  80. if (settings["mods"]["validation"].String() == "full")
  81. checkModFilesystemsConflicts(modFilesystems);
  82. }
  83. void CModHandler::checkModFilesystemsConflicts(const std::map<TModID, ISimpleResourceLoader *> & modFilesystems)
  84. {
  85. for(const auto & [leftName, leftFilesystem] : modFilesystems)
  86. {
  87. for(const auto & [rightName, rightFilesystem] : modFilesystems)
  88. {
  89. if (leftName == rightName)
  90. continue;
  91. if (getModDependencies(leftName).count(rightName) || getModDependencies(rightName).count(leftName))
  92. continue;
  93. if (getModSoftDependencies(leftName).count(rightName) || getModSoftDependencies(rightName).count(leftName))
  94. continue;
  95. const auto & filter = [](const ResourcePath &path){return path.getType() != EResType::DIRECTORY && path.getType() != EResType::JSON;};
  96. std::unordered_set<ResourcePath> leftResources = leftFilesystem->getFilteredFiles(filter);
  97. std::unordered_set<ResourcePath> rightResources = rightFilesystem->getFilteredFiles(filter);
  98. for (auto const & leftFile : leftResources)
  99. {
  100. if (rightResources.count(leftFile))
  101. logMod->warn("Potential confict detected between '%s' and '%s': both mods add file '%s'", leftName, rightName, leftFile.getOriginalName());
  102. }
  103. }
  104. }
  105. }
  106. TModID CModHandler::findResourceOrigin(const ResourcePath & name) const
  107. {
  108. try
  109. {
  110. auto activeMode = modManager->getActiveMods();
  111. for(const auto & modID : boost::adaptors::reverse(activeMode))
  112. {
  113. if(CResourceHandler::get(modID)->existsResource(name))
  114. return modID;
  115. }
  116. if(CResourceHandler::get("core")->existsResource(name))
  117. return "core";
  118. if(CResourceHandler::get("mapEditor")->existsResource(name))
  119. return "core"; // Workaround for loading maps via map editor
  120. }
  121. catch( const std::out_of_range & e)
  122. {
  123. // no-op
  124. }
  125. throw std::runtime_error("Resource with name " + name.getName() + " and type " + EResTypeHelper::getEResTypeAsString(name.getType()) + " wasn't found.");
  126. }
  127. std::string CModHandler::findResourceLanguage(const ResourcePath & name) const
  128. {
  129. std::string modName = findResourceOrigin(name);
  130. std::string modLanguage = getModLanguage(modName);
  131. return modLanguage;
  132. }
  133. std::string CModHandler::findResourceEncoding(const ResourcePath & resource) const
  134. {
  135. std::string modName = findResourceOrigin(resource);
  136. std::string modLanguage = findResourceLanguage(resource);
  137. bool potentiallyUserMadeContent = resource.getType() == EResType::MAP || resource.getType() == EResType::CAMPAIGN;
  138. if (potentiallyUserMadeContent && modName == ModScope::scopeBuiltin() && modLanguage == "english")
  139. {
  140. // this might be a map or campaign that player downloaded manually and placed in Maps/ directory
  141. // in this case, this file may be in user-preferred language, and not in same language as the rest of H3 data
  142. // however at the moment we have no way to detect that for sure - file can be either in English or in user-preferred language
  143. // but since all known H3 encodings (Win125X or GBK) are supersets of ASCII, we can safely load English data using encoding of user-preferred language
  144. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  145. std::string fileEncoding = Languages::getLanguageOptions(preferredLanguage).encoding;
  146. return fileEncoding;
  147. }
  148. else
  149. {
  150. std::string fileEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  151. return fileEncoding;
  152. }
  153. }
  154. std::string CModHandler::getModLanguage(const TModID& modId) const
  155. {
  156. if(modId == "core")
  157. return VLC->generaltexth->getInstalledLanguage();
  158. if(modId == "map")
  159. return VLC->generaltexth->getPreferredLanguage();
  160. return getModInfo(modId).getBaseLanguage();
  161. }
  162. std::set<TModID> CModHandler::getModDependencies(const TModID & modId) const
  163. {
  164. bool isModFound;
  165. return getModDependencies(modId, isModFound);
  166. }
  167. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  168. {
  169. isModFound = modManager->isModActive(modId);
  170. if (isModFound)
  171. return modManager->getModDescription(modId).getDependencies();
  172. logMod->error("Mod not found: '%s'", modId);
  173. return {};
  174. }
  175. std::set<TModID> CModHandler::getModSoftDependencies(const TModID & modId) const
  176. {
  177. return modManager->getModDescription(modId).getSoftDependencies();
  178. }
  179. std::set<TModID> CModHandler::getModEnabledSoftDependencies(const TModID & modId) const
  180. {
  181. std::set<TModID> softDependencies = getModSoftDependencies(modId);
  182. vstd::erase_if(softDependencies, [this](const TModID & dependency){ return !modManager->isModActive(dependency);});
  183. return softDependencies;
  184. }
  185. void CModHandler::initializeConfig()
  186. {
  187. for(const TModID & modName : getActiveMods())
  188. {
  189. const auto & mod = getModInfo(modName);
  190. if (!mod.getLocalConfig()["settings"].isNull())
  191. VLC->settingsHandler->loadBase(mod.getLocalConfig()["settings"]);
  192. }
  193. }
  194. void CModHandler::loadTranslation(const TModID & modName)
  195. {
  196. const auto & mod = getModInfo(modName);
  197. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  198. std::string modBaseLanguage = getModInfo(modName).getBaseLanguage();
  199. JsonNode baseTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()["translations"]);
  200. JsonNode extraTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()[preferredLanguage]["translations"]);
  201. VLC->generaltexth->loadTranslationOverrides(modName, modBaseLanguage, baseTranslation);
  202. VLC->generaltexth->loadTranslationOverrides(modName, preferredLanguage, extraTranslation);
  203. }
  204. void CModHandler::load()
  205. {
  206. logMod->info("\tInitializing content handler");
  207. content->init();
  208. const auto & activeMods = getActiveMods();
  209. validationPassed.insert(activeMods.begin(), activeMods.end());
  210. for(const TModID & modName : activeMods)
  211. {
  212. modChecksums[modName] = this->modManager->computeChecksum(modName);
  213. }
  214. for(const TModID & modName : activeMods)
  215. {
  216. const auto & modInfo = getModInfo(modName);
  217. bool isValid = content->preloadData(modInfo, isModValidationNeeded(modInfo));
  218. if (isValid)
  219. logGlobal->info("\t\tParsing mod: OK (%s)", modInfo.getName());
  220. else
  221. logGlobal->warn("\t\tParsing mod: Issues found! (%s)", modInfo.getName());
  222. if (!isValid)
  223. validationPassed.erase(modName);
  224. }
  225. logMod->info("\tParsing mod data");
  226. for(const TModID & modName : activeMods)
  227. {
  228. const auto & modInfo = getModInfo(modName);
  229. bool isValid = content->load(getModInfo(modName), isModValidationNeeded(getModInfo(modName)));
  230. if (isValid)
  231. logGlobal->info("\t\tLoading mod: OK (%s)", modInfo.getName());
  232. else
  233. logGlobal->warn("\t\tLoading mod: Issues found! (%s)", modInfo.getName());
  234. if (!isValid)
  235. validationPassed.erase(modName);
  236. }
  237. #if SCRIPTING_ENABLED
  238. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  239. #endif
  240. content->loadCustom();
  241. for(const TModID & modName : activeMods)
  242. loadTranslation(modName);
  243. logMod->info("\tLoading mod data");
  244. VLC->creh->loadCrExpMod();
  245. VLC->identifiersHandler->finalize();
  246. logMod->info("\tResolving identifiers");
  247. content->afterLoadFinalization();
  248. logMod->info("\tHandlers post-load finalization");
  249. logMod->info("\tAll game content loaded");
  250. }
  251. void CModHandler::afterLoad(bool onlyEssential)
  252. {
  253. JsonNode modSettings;
  254. for (const auto & modEntry : getActiveMods())
  255. {
  256. if (validationPassed.count(modEntry))
  257. modManager->setValidatedChecksum(modEntry, modChecksums.at(modEntry));
  258. else
  259. modManager->setValidatedChecksum(modEntry, std::nullopt);
  260. }
  261. modManager->saveConfigurationState();
  262. }
  263. bool CModHandler::isModValidationNeeded(const ModDescription & mod) const
  264. {
  265. if (settings["mods"]["validation"].String() == "full")
  266. return true;
  267. if (modManager->getValidatedChecksum(mod.getID()) == modChecksums.at(mod.getID()))
  268. return false;
  269. if (settings["mods"]["validation"].String() == "off")
  270. return false;
  271. return true;
  272. }
  273. VCMI_LIB_NAMESPACE_END