CResourceLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #include "StdInc.h"
  2. #include "CResourceLoader.h"
  3. #include "CFileInfo.h"
  4. #include "CLodArchiveLoader.h"
  5. #include "CFilesystemLoader.h"
  6. //For filesystem initialization
  7. #include "../JsonNode.h"
  8. #include "../GameConstants.h"
  9. #include "../VCMIDirs.h"
  10. #include "../CStopWatch.h"
  11. CResourceLoader * CResourceHandler::resourceLoader = nullptr;
  12. CResourceLoader * CResourceHandler::initialLoader = nullptr;
  13. ResourceID::ResourceID()
  14. :type(EResType::OTHER)
  15. {
  16. }
  17. ResourceID::ResourceID(std::string name)
  18. {
  19. CFileInfo info(std::move(name));
  20. setName(info.getStem());
  21. setType(info.getType());
  22. }
  23. ResourceID::ResourceID(std::string name, EResType::Type type)
  24. {
  25. setName(std::move(name));
  26. setType(type);
  27. }
  28. ResourceID::ResourceID(const std::string & prefix, const std::string & name, EResType::Type type)
  29. {
  30. this->name = name;
  31. size_t dotPos = this->name.find_last_of("/.");
  32. if(dotPos != std::string::npos && this->name[dotPos] == '.')
  33. this->name.erase(dotPos);
  34. this->name = prefix + this->name;
  35. setType(type);
  36. }
  37. std::string ResourceID::getName() const
  38. {
  39. return name;
  40. }
  41. EResType::Type ResourceID::getType() const
  42. {
  43. return type;
  44. }
  45. void ResourceID::setName(std::string name)
  46. {
  47. this->name = std::move(name);
  48. size_t dotPos = this->name.find_last_of("/.");
  49. if(dotPos != std::string::npos && this->name[dotPos] == '.')
  50. this->name.erase(dotPos);
  51. // strangely enough but this line takes 40-50% of filesystem loading time
  52. boost::to_upper(this->name);
  53. }
  54. void ResourceID::setType(EResType::Type type)
  55. {
  56. this->type = type;
  57. }
  58. CResourceLoader::CResourceLoader()
  59. {
  60. }
  61. std::unique_ptr<CInputStream> CResourceLoader::load(const ResourceID & resourceIdent) const
  62. {
  63. auto resource = resources.find(resourceIdent);
  64. if(resource == resources.end())
  65. {
  66. throw std::runtime_error("Resource with name " + resourceIdent.getName() + " and type "
  67. + EResTypeHelper::getEResTypeAsString(resourceIdent.getType()) + " wasn't found.");
  68. }
  69. // get the last added resource(most overriden)
  70. const ResourceLocator & locator = resource->second.back();
  71. // load the resource and return it
  72. return locator.getLoader()->load(locator.getResourceName());
  73. }
  74. std::pair<std::unique_ptr<ui8[]>, ui64> CResourceLoader::loadData(const ResourceID & resourceIdent) const
  75. {
  76. auto stream = load(resourceIdent);
  77. std::unique_ptr<ui8[]> data(new ui8[stream->getSize()]);
  78. size_t readSize = stream->read(data.get(), stream->getSize());
  79. assert(readSize == stream->getSize());
  80. return std::make_pair(std::move(data), stream->getSize());
  81. }
  82. ResourceLocator CResourceLoader::getResource(const ResourceID & resourceIdent) const
  83. {
  84. auto resource = resources.find(resourceIdent);
  85. if (resource == resources.end())
  86. return ResourceLocator(nullptr, "");
  87. return resource->second.back();
  88. }
  89. const std::vector<ResourceLocator> & CResourceLoader::getResourcesWithName(const ResourceID & resourceIdent) const
  90. {
  91. static const std::vector<ResourceLocator> emptyList;
  92. auto resource = resources.find(resourceIdent);
  93. if (resource == resources.end())
  94. return emptyList;
  95. return resource->second;
  96. }
  97. std::string CResourceLoader::getResourceName(const ResourceID & resourceIdent) const
  98. {
  99. auto locator = getResource(resourceIdent);
  100. if (locator.getLoader())
  101. return locator.getLoader()->getOrigin() + '/' + locator.getResourceName();
  102. return "";
  103. }
  104. bool CResourceLoader::existsResource(const ResourceID & resourceIdent) const
  105. {
  106. return resources.find(resourceIdent) != resources.end();
  107. }
  108. bool CResourceLoader::createResource(std::string URI)
  109. {
  110. std::string filename = URI;
  111. boost::to_upper(URI);
  112. BOOST_REVERSE_FOREACH (const LoaderEntry & entry, loaders)
  113. {
  114. if (entry.writeable && boost::algorithm::starts_with(URI, entry.prefix))
  115. {
  116. // remove loader prefix from filename
  117. filename = filename.substr(entry.prefix.size());
  118. if (!entry.loader->createEntry(filename))
  119. return false; //or continue loop?
  120. resources[ResourceID(URI)].push_back(ResourceLocator(entry.loader.get(), filename));
  121. }
  122. }
  123. return false;
  124. }
  125. void CResourceLoader::addLoader(std::string mountPoint, shared_ptr<ISimpleResourceLoader> loader, bool writeable)
  126. {
  127. LoaderEntry loaderEntry;
  128. loaderEntry.loader = loader;
  129. loaderEntry.prefix = mountPoint;
  130. loaderEntry.writeable = writeable;
  131. loaders.push_back(loaderEntry);
  132. // Get entries and add them to the resources list
  133. const boost::unordered_map<ResourceID, std::string> & entries = loader->getEntries();
  134. boost::to_upper(mountPoint);
  135. BOOST_FOREACH (auto & entry, entries)
  136. {
  137. // Create identifier and locator and add them to the resources list
  138. ResourceID ident(mountPoint, entry.first.getName(), entry.first.getType());
  139. ResourceLocator locator(loader.get(), entry.second);
  140. resources[ident].push_back(locator);
  141. }
  142. }
  143. CResourceLoader * CResourceHandler::get()
  144. {
  145. if(resourceLoader != nullptr)
  146. {
  147. return resourceLoader;
  148. }
  149. else
  150. {
  151. std::stringstream string;
  152. string << "Error: Resource loader wasn't initialized. "
  153. << "Make sure that you set one via CResourceLoaderFactory::initialize";
  154. throw std::runtime_error(string.str());
  155. }
  156. }
  157. //void CResourceLoaderFactory::setInstance(CResourceLoader * resourceLoader)
  158. //{
  159. // CResourceLoaderFactory::resourceLoader = resourceLoader;
  160. //}
  161. ResourceLocator::ResourceLocator(ISimpleResourceLoader * loader, const std::string & resourceName)
  162. : loader(loader), resourceName(resourceName)
  163. {
  164. }
  165. ISimpleResourceLoader * ResourceLocator::getLoader() const
  166. {
  167. return loader;
  168. }
  169. std::string ResourceLocator::getResourceName() const
  170. {
  171. return resourceName;
  172. }
  173. EResType::Type EResTypeHelper::getTypeFromExtension(std::string extension)
  174. {
  175. boost::to_upper(extension);
  176. static const std::map<std::string, EResType::Type> stringToRes =
  177. boost::assign::map_list_of
  178. (".TXT", EResType::TEXT)
  179. (".JSON", EResType::TEXT)
  180. (".DEF", EResType::ANIMATION)
  181. (".MSK", EResType::MASK)
  182. (".MSG", EResType::MASK)
  183. (".H3C", EResType::CAMPAIGN)
  184. (".H3M", EResType::MAP)
  185. (".FNT", EResType::BMP_FONT)
  186. (".TTF", EResType::TTF_FONT)
  187. (".BMP", EResType::IMAGE)
  188. (".JPG", EResType::IMAGE)
  189. (".PCX", EResType::IMAGE)
  190. (".PNG", EResType::IMAGE)
  191. (".TGA", EResType::IMAGE)
  192. (".WAV", EResType::SOUND)
  193. (".82M", EResType::SOUND)
  194. (".SMK", EResType::VIDEO)
  195. (".BIK", EResType::VIDEO)
  196. (".MJPG", EResType::VIDEO)
  197. (".MPG", EResType::VIDEO)
  198. (".AVI", EResType::VIDEO)
  199. (".MP3", EResType::MUSIC)
  200. (".OGG", EResType::MUSIC)
  201. (".LOD", EResType::ARCHIVE_LOD)
  202. (".PAC", EResType::ARCHIVE_LOD)
  203. (".VID", EResType::ARCHIVE_VID)
  204. (".SND", EResType::ARCHIVE_SND)
  205. (".PAL", EResType::PALETTE)
  206. (".VCGM1", EResType::CLIENT_SAVEGAME)
  207. (".VSGM1", EResType::SERVER_SAVEGAME)
  208. (".ERM", EResType::ERM)
  209. (".ERT", EResType::ERT)
  210. (".ERS", EResType::ERS);
  211. auto iter = stringToRes.find(extension);
  212. if (iter == stringToRes.end())
  213. return EResType::OTHER;
  214. return iter->second;
  215. }
  216. std::string EResTypeHelper::getEResTypeAsString(EResType::Type type)
  217. {
  218. #define MAP_ENUM(value) (EResType::value, #value)
  219. static const std::map<EResType::Type, std::string> stringToRes = boost::assign::map_list_of
  220. MAP_ENUM(TEXT)
  221. MAP_ENUM(ANIMATION)
  222. MAP_ENUM(MASK)
  223. MAP_ENUM(CAMPAIGN)
  224. MAP_ENUM(MAP)
  225. MAP_ENUM(BMP_FONT)
  226. MAP_ENUM(TTF_FONT)
  227. MAP_ENUM(IMAGE)
  228. MAP_ENUM(VIDEO)
  229. MAP_ENUM(SOUND)
  230. MAP_ENUM(MUSIC)
  231. MAP_ENUM(ARCHIVE_LOD)
  232. MAP_ENUM(ARCHIVE_SND)
  233. MAP_ENUM(ARCHIVE_VID)
  234. MAP_ENUM(PALETTE)
  235. MAP_ENUM(CLIENT_SAVEGAME)
  236. MAP_ENUM(SERVER_SAVEGAME)
  237. MAP_ENUM(DIRECTORY)
  238. MAP_ENUM(ERM)
  239. MAP_ENUM(ERT)
  240. MAP_ENUM(ERS)
  241. MAP_ENUM(OTHER);
  242. #undef MAP_ENUM
  243. auto iter = stringToRes.find(type);
  244. assert(iter != stringToRes.end());
  245. return iter->second;
  246. }
  247. void CResourceHandler::initialize()
  248. {
  249. //recurse only into specific directories
  250. auto recurseInDir = [](std::string URI, int depth)
  251. {
  252. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  253. BOOST_FOREACH(const ResourceLocator & entry, resources)
  254. {
  255. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  256. if (!filename.empty())
  257. {
  258. shared_ptr<ISimpleResourceLoader> dir(new CFilesystemLoader(filename, depth, true));
  259. initialLoader->addLoader(URI + '/', dir, false);
  260. }
  261. }
  262. };
  263. //temporary filesystem that will be used to initialize main one.
  264. //used to solve several case-sensivity issues like Mp3 vs MP3
  265. initialLoader = new CResourceLoader;
  266. resourceLoader = new CResourceLoader;
  267. shared_ptr<ISimpleResourceLoader> rootDir(new CFilesystemLoader(VCMIDirs::get().dataPath(), 0, true));
  268. initialLoader->addLoader("GLOBAL/", rootDir, false);
  269. initialLoader->addLoader("ALL/", rootDir, false);
  270. auto userDir = rootDir;
  271. //add local directory to "ALL" but only if it differs from root dir (true for linux)
  272. if (VCMIDirs::get().dataPath() != VCMIDirs::get().localPath())
  273. {
  274. userDir = shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(VCMIDirs::get().localPath(), 0, true));
  275. initialLoader->addLoader("ALL/", userDir, false);
  276. }
  277. //create "LOCAL" dir with current userDir (may be same as rootDir)
  278. initialLoader->addLoader("LOCAL/", userDir, false);
  279. recurseInDir("ALL/CONFIG", 0);// look for configs
  280. recurseInDir("ALL/DATA", 0); // look for archives
  281. recurseInDir("ALL/MODS", 2); // look for mods. Depth 2 is required for now but won't cause issues if no mods present
  282. }
  283. void CResourceHandler::loadDirectory(const std::string &prefix, const std::string &mountPoint, const JsonNode & config)
  284. {
  285. std::string URI = prefix + config["path"].String();
  286. bool writeable = config["writeable"].Bool();
  287. int depth = 16;
  288. if (!config["depth"].isNull())
  289. depth = config["depth"].Float();
  290. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  291. BOOST_FOREACH(const ResourceLocator & entry, resources)
  292. {
  293. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  294. resourceLoader->addLoader(mountPoint,
  295. shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(filename, depth)), writeable);
  296. }
  297. }
  298. void CResourceHandler::loadArchive(const std::string &prefix, const std::string &mountPoint, const JsonNode & config, EResType::Type archiveType)
  299. {
  300. std::string URI = prefix + config["path"].String();
  301. std::string filename = initialLoader->getResourceName(ResourceID(URI, archiveType));
  302. if (!filename.empty())
  303. resourceLoader->addLoader(mountPoint,
  304. shared_ptr<ISimpleResourceLoader>(new CLodArchiveLoader(filename)), false);
  305. }
  306. void CResourceHandler::loadFileSystem(const std::string & prefix, const std::string &fsConfigURI)
  307. {
  308. auto fsConfigData = initialLoader->loadData(ResourceID(fsConfigURI, EResType::TEXT));
  309. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  310. loadFileSystem(prefix, fsConfig["filesystem"]);
  311. }
  312. void CResourceHandler::loadFileSystem(const std::string & prefix, const JsonNode &fsConfig)
  313. {
  314. BOOST_FOREACH(auto & mountPoint, fsConfig.Struct())
  315. {
  316. BOOST_FOREACH(auto & entry, mountPoint.second.Vector())
  317. {
  318. CStopWatch timer;
  319. logGlobal->debugStream() << "\t\tLoading resource at " << prefix + entry["path"].String();
  320. if (entry["type"].String() == "dir")
  321. loadDirectory(prefix, mountPoint.first, entry);
  322. if (entry["type"].String() == "lod")
  323. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_LOD);
  324. if (entry["type"].String() == "snd")
  325. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_SND);
  326. if (entry["type"].String() == "vid")
  327. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_VID);
  328. logGlobal->debugStream() << "Resource loaded in " << timer.getDiff() << " ms.";
  329. }
  330. }
  331. }
  332. std::vector<std::string> CResourceHandler::getAvailableMods()
  333. {
  334. auto iterator = initialLoader->getIterator([](const ResourceID & ident) -> bool
  335. {
  336. std::string name = ident.getName();
  337. return ident.getType() == EResType::DIRECTORY
  338. && std::count(name.begin(), name.end(), '/') == 2
  339. && boost::algorithm::starts_with(name, "ALL/MODS/");
  340. });
  341. //storage for found mods
  342. std::vector<std::string> foundMods;
  343. while (iterator.hasNext())
  344. {
  345. std::string name = iterator->getName();
  346. name.erase(0, name.find_last_of('/') + 1); //Remove path prefix
  347. if (!name.empty()) // this is also triggered for "ALL/MODS/" entry
  348. foundMods.push_back(name);
  349. ++iterator;
  350. }
  351. return foundMods;
  352. }
  353. void CResourceHandler::setActiveMods(std::vector<std::string> enabledMods)
  354. {
  355. // default FS config for mods: directory "Content" that acts as H3 root directory
  356. JsonNode defaultFS;
  357. defaultFS[""].Vector().resize(1);
  358. defaultFS[""].Vector()[0]["type"].String() = "dir";
  359. defaultFS[""].Vector()[0]["path"].String() = "/Content";
  360. BOOST_FOREACH(std::string & modName, enabledMods)
  361. {
  362. ResourceID modConfFile("all/mods/" + modName + "/mod", EResType::TEXT);
  363. auto fsConfigData = initialLoader->loadData(modConfFile);
  364. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  365. if (!fsConfig["filesystem"].isNull())
  366. loadFileSystem("all/mods/" + modName, fsConfig["filesystem"]);
  367. else
  368. loadFileSystem("all/mods/" + modName, defaultFS);
  369. }
  370. }