CModHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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->getActiveMods();// TODO: currently identical to active
  36. }
  37. std::vector<std::string> CModHandler::getActiveMods() const
  38. {
  39. return modManager->getActiveMods();
  40. }
  41. std::string CModHandler::getModLoadErrors() const
  42. {
  43. return ""; // TODO: modLoadErrors->toString();
  44. }
  45. const ModDescription & CModHandler::getModInfo(const TModID & modId) const
  46. {
  47. return modManager->getModDescription(modId);
  48. }
  49. static JsonNode genDefaultFS()
  50. {
  51. // default FS config for mods: directory "Content" that acts as H3 root directory
  52. JsonNode defaultFS;
  53. defaultFS[""].Vector().resize(2);
  54. defaultFS[""].Vector()[0]["type"].String() = "zip";
  55. defaultFS[""].Vector()[0]["path"].String() = "/Content.zip";
  56. defaultFS[""].Vector()[1]["type"].String() = "dir";
  57. defaultFS[""].Vector()[1]["path"].String() = "/Content";
  58. return defaultFS;
  59. }
  60. static std::string getModDirectory(const TModID & modName)
  61. {
  62. std::string result = modName;
  63. boost::to_upper(result);
  64. boost::algorithm::replace_all(result, ".", "/MODS/");
  65. return "MODS/" + result;
  66. }
  67. static ISimpleResourceLoader * genModFilesystem(const std::string & modName, const JsonNode & conf)
  68. {
  69. static const JsonNode defaultFS = genDefaultFS();
  70. if (!conf.isNull())
  71. return CResourceHandler::createFileSystem(getModDirectory(modName), conf);
  72. else
  73. return CResourceHandler::createFileSystem(getModDirectory(modName), defaultFS);
  74. }
  75. //static ui32 calculateModChecksum(const std::string & modName, ISimpleResourceLoader * filesystem)
  76. //{
  77. // boost::crc_32_type modChecksum;
  78. // // first - add current VCMI version into checksum to force re-validation on VCMI updates
  79. // modChecksum.process_bytes(reinterpret_cast<const void*>(GameConstants::VCMI_VERSION.data()), GameConstants::VCMI_VERSION.size());
  80. //
  81. // // second - add mod.json into checksum because filesystem does not contains this file
  82. // // FIXME: remove workaround for core mod
  83. // if (modName != ModScope::scopeBuiltin())
  84. // {
  85. // auto modConfFile = CModInfo::getModFile(modName);
  86. // ui32 configChecksum = CResourceHandler::get("initial")->load(modConfFile)->calculateCRC32();
  87. // modChecksum.process_bytes(reinterpret_cast<const void *>(&configChecksum), sizeof(configChecksum));
  88. // }
  89. // // third - add all detected text files from this mod into checksum
  90. // auto files = filesystem->getFilteredFiles([](const ResourcePath & resID)
  91. // {
  92. // return (resID.getType() == EResType::TEXT || resID.getType() == EResType::JSON) &&
  93. // ( boost::starts_with(resID.getName(), "DATA") || boost::starts_with(resID.getName(), "CONFIG"));
  94. // });
  95. //
  96. // for (const ResourcePath & file : files)
  97. // {
  98. // ui32 fileChecksum = filesystem->load(file)->calculateCRC32();
  99. // modChecksum.process_bytes(reinterpret_cast<const void *>(&fileChecksum), sizeof(fileChecksum));
  100. // }
  101. // return modChecksum.checksum();
  102. //}
  103. void CModHandler::loadModFilesystems()
  104. {
  105. CGeneralTextHandler::detectInstallParameters();
  106. const auto & activeMods = modManager->getActiveMods();
  107. std::map<TModID, ISimpleResourceLoader *> modFilesystems;
  108. for(const TModID & modName : activeMods)
  109. modFilesystems[modName] = genModFilesystem(modName, getModInfo(modName).getFilesystemConfig());
  110. for(const TModID & modName : activeMods)
  111. CResourceHandler::addFilesystem("data", modName, modFilesystems[modName]);
  112. if (settings["mods"]["validation"].String() == "full")
  113. checkModFilesystemsConflicts(modFilesystems);
  114. }
  115. void CModHandler::checkModFilesystemsConflicts(const std::map<TModID, ISimpleResourceLoader *> & modFilesystems)
  116. {
  117. for(const auto & [leftName, leftFilesystem] : modFilesystems)
  118. {
  119. for(const auto & [rightName, rightFilesystem] : modFilesystems)
  120. {
  121. if (leftName == rightName)
  122. continue;
  123. if (getModDependencies(leftName).count(rightName) || getModDependencies(rightName).count(leftName))
  124. continue;
  125. if (getModSoftDependencies(leftName).count(rightName) || getModSoftDependencies(rightName).count(leftName))
  126. continue;
  127. const auto & filter = [](const ResourcePath &path){return path.getType() != EResType::DIRECTORY && path.getType() != EResType::JSON;};
  128. std::unordered_set<ResourcePath> leftResources = leftFilesystem->getFilteredFiles(filter);
  129. std::unordered_set<ResourcePath> rightResources = rightFilesystem->getFilteredFiles(filter);
  130. for (auto const & leftFile : leftResources)
  131. {
  132. if (rightResources.count(leftFile))
  133. logMod->warn("Potential confict detected between '%s' and '%s': both mods add file '%s'", leftName, rightName, leftFile.getOriginalName());
  134. }
  135. }
  136. }
  137. }
  138. TModID CModHandler::findResourceOrigin(const ResourcePath & name) const
  139. {
  140. try
  141. {
  142. auto activeMode = modManager->getActiveMods();
  143. for(const auto & modID : boost::adaptors::reverse(activeMode))
  144. {
  145. if(CResourceHandler::get(modID)->existsResource(name))
  146. return modID;
  147. }
  148. if(CResourceHandler::get("core")->existsResource(name))
  149. return "core";
  150. if(CResourceHandler::get("mapEditor")->existsResource(name))
  151. return "core"; // Workaround for loading maps via map editor
  152. }
  153. catch( const std::out_of_range & e)
  154. {
  155. // no-op
  156. }
  157. throw std::runtime_error("Resource with name " + name.getName() + " and type " + EResTypeHelper::getEResTypeAsString(name.getType()) + " wasn't found.");
  158. }
  159. std::string CModHandler::findResourceLanguage(const ResourcePath & name) const
  160. {
  161. std::string modName = findResourceOrigin(name);
  162. std::string modLanguage = getModLanguage(modName);
  163. return modLanguage;
  164. }
  165. std::string CModHandler::findResourceEncoding(const ResourcePath & resource) const
  166. {
  167. std::string modName = findResourceOrigin(resource);
  168. std::string modLanguage = findResourceLanguage(resource);
  169. bool potentiallyUserMadeContent = resource.getType() == EResType::MAP || resource.getType() == EResType::CAMPAIGN;
  170. if (potentiallyUserMadeContent && modName == ModScope::scopeBuiltin() && modLanguage == "english")
  171. {
  172. // this might be a map or campaign that player downloaded manually and placed in Maps/ directory
  173. // in this case, this file may be in user-preferred language, and not in same language as the rest of H3 data
  174. // however at the moment we have no way to detect that for sure - file can be either in English or in user-preferred language
  175. // 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
  176. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  177. std::string fileEncoding = Languages::getLanguageOptions(preferredLanguage).encoding;
  178. return fileEncoding;
  179. }
  180. else
  181. {
  182. std::string fileEncoding = Languages::getLanguageOptions(modLanguage).encoding;
  183. return fileEncoding;
  184. }
  185. }
  186. std::string CModHandler::getModLanguage(const TModID& modId) const
  187. {
  188. if(modId == "core")
  189. return VLC->generaltexth->getInstalledLanguage();
  190. if(modId == "map")
  191. return VLC->generaltexth->getPreferredLanguage();
  192. return getModInfo(modId).getBaseLanguage();
  193. }
  194. std::set<TModID> CModHandler::getModDependencies(const TModID & modId) const
  195. {
  196. bool isModFound;
  197. return getModDependencies(modId, isModFound);
  198. }
  199. std::set<TModID> CModHandler::getModDependencies(const TModID & modId, bool & isModFound) const
  200. {
  201. isModFound = modManager->isModActive(modId);
  202. if (isModFound)
  203. return modManager->getModDescription(modId).getDependencies();
  204. logMod->error("Mod not found: '%s'", modId);
  205. return {};
  206. }
  207. std::set<TModID> CModHandler::getModSoftDependencies(const TModID & modId) const
  208. {
  209. return modManager->getModDescription(modId).getSoftDependencies();
  210. }
  211. std::set<TModID> CModHandler::getModEnabledSoftDependencies(const TModID & modId) const
  212. {
  213. std::set<TModID> softDependencies = getModSoftDependencies(modId);
  214. vstd::erase_if(softDependencies, [&](const TModID & dependency){ return !modManager->isModActive(dependency);});
  215. return softDependencies;
  216. }
  217. void CModHandler::initializeConfig()
  218. {
  219. for(const TModID & modName : getActiveMods())
  220. {
  221. const auto & mod = getModInfo(modName);
  222. if (!mod.getLocalConfig()["settings"].isNull())
  223. VLC->settingsHandler->loadBase(mod.getLocalConfig()["settings"]);
  224. }
  225. }
  226. void CModHandler::loadTranslation(const TModID & modName)
  227. {
  228. const auto & mod = getModInfo(modName);
  229. std::string preferredLanguage = VLC->generaltexth->getPreferredLanguage();
  230. std::string modBaseLanguage = getModInfo(modName).getBaseLanguage();
  231. JsonNode baseTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()["translations"]);
  232. JsonNode extraTranslation = JsonUtils::assembleFromFiles(mod.getLocalConfig()[preferredLanguage]["translations"]);
  233. VLC->generaltexth->loadTranslationOverrides(modName, modBaseLanguage, baseTranslation);
  234. VLC->generaltexth->loadTranslationOverrides(modName, preferredLanguage, extraTranslation);
  235. }
  236. void CModHandler::load()
  237. {
  238. logMod->info("\tInitializing content handler");
  239. content->init();
  240. // for(const TModID & modName : getActiveMods())
  241. // {
  242. // logMod->trace("Generating checksum for %s", modName);
  243. // allMods[modName].updateChecksum(calculateModChecksum(modName, CResourceHandler::get(modName)));
  244. // }
  245. for(const TModID & modName : getActiveMods())
  246. content->preloadData(getModInfo(modName));
  247. logMod->info("\tParsing mod data");
  248. for(const TModID & modName : getActiveMods())
  249. content->load(getModInfo(modName));
  250. #if SCRIPTING_ENABLED
  251. VLC->scriptHandler->performRegistration(VLC);//todo: this should be done before any other handlers load
  252. #endif
  253. content->loadCustom();
  254. for(const TModID & modName : getActiveMods())
  255. loadTranslation(modName);
  256. logMod->info("\tLoading mod data");
  257. VLC->creh->loadCrExpMod();
  258. VLC->identifiersHandler->finalize();
  259. logMod->info("\tResolving identifiers");
  260. content->afterLoadFinalization();
  261. logMod->info("\tHandlers post-load finalization");
  262. logMod->info("\tAll game content loaded");
  263. }
  264. void CModHandler::afterLoad(bool onlyEssential)
  265. {
  266. //JsonNode modSettings;
  267. //for (auto & modEntry : getActiveMods())
  268. //{
  269. // std::string pointer = "/" + boost::algorithm::replace_all_copy(modEntry.first, ".", "/mods/");
  270. // modSettings["activeMods"].resolvePointer(pointer) = modEntry.second.saveLocalData();
  271. //}
  272. //modSettings[ModScope::scopeBuiltin()] = coreMod->saveLocalData();
  273. //modSettings[ModScope::scopeBuiltin()]["name"].String() = "Original game files";
  274. //if(!onlyEssential)
  275. //{
  276. // std::fstream file(CResourceHandler::get()->getResourceName(ResourcePath("config/modSettings.json"))->c_str(), std::ofstream::out | std::ofstream::trunc);
  277. // file << modSettings.toString();
  278. //}
  279. }
  280. VCMI_LIB_NAMESPACE_END