2
0

CModHandler.cpp 11 KB

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