CResourceLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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 CResourceHandler::clear()
  158. {
  159. delete resourceLoader;
  160. delete initialLoader;
  161. }
  162. //void CResourceLoaderFactory::setInstance(CResourceLoader * resourceLoader)
  163. //{
  164. // CResourceLoaderFactory::resourceLoader = resourceLoader;
  165. //}
  166. ResourceLocator::ResourceLocator(ISimpleResourceLoader * loader, const std::string & resourceName)
  167. : loader(loader), resourceName(resourceName)
  168. {
  169. }
  170. ISimpleResourceLoader * ResourceLocator::getLoader() const
  171. {
  172. return loader;
  173. }
  174. std::string ResourceLocator::getResourceName() const
  175. {
  176. return resourceName;
  177. }
  178. EResType::Type EResTypeHelper::getTypeFromExtension(std::string extension)
  179. {
  180. boost::to_upper(extension);
  181. static const std::map<std::string, EResType::Type> stringToRes =
  182. boost::assign::map_list_of
  183. (".TXT", EResType::TEXT)
  184. (".JSON", EResType::TEXT)
  185. (".DEF", EResType::ANIMATION)
  186. (".MSK", EResType::MASK)
  187. (".MSG", EResType::MASK)
  188. (".H3C", EResType::CAMPAIGN)
  189. (".H3M", EResType::MAP)
  190. (".FNT", EResType::BMP_FONT)
  191. (".TTF", EResType::TTF_FONT)
  192. (".BMP", EResType::IMAGE)
  193. (".JPG", EResType::IMAGE)
  194. (".PCX", EResType::IMAGE)
  195. (".PNG", EResType::IMAGE)
  196. (".TGA", EResType::IMAGE)
  197. (".WAV", EResType::SOUND)
  198. (".82M", EResType::SOUND)
  199. (".SMK", EResType::VIDEO)
  200. (".BIK", EResType::VIDEO)
  201. (".MJPG", EResType::VIDEO)
  202. (".MPG", EResType::VIDEO)
  203. (".AVI", EResType::VIDEO)
  204. (".MP3", EResType::MUSIC)
  205. (".OGG", EResType::MUSIC)
  206. (".LOD", EResType::ARCHIVE_LOD)
  207. (".PAC", EResType::ARCHIVE_LOD)
  208. (".VID", EResType::ARCHIVE_VID)
  209. (".SND", EResType::ARCHIVE_SND)
  210. (".PAL", EResType::PALETTE)
  211. (".VCGM1", EResType::CLIENT_SAVEGAME)
  212. (".VSGM1", EResType::SERVER_SAVEGAME)
  213. (".ERM", EResType::ERM)
  214. (".ERT", EResType::ERT)
  215. (".ERS", EResType::ERS);
  216. auto iter = stringToRes.find(extension);
  217. if (iter == stringToRes.end())
  218. return EResType::OTHER;
  219. return iter->second;
  220. }
  221. std::string EResTypeHelper::getEResTypeAsString(EResType::Type type)
  222. {
  223. #define MAP_ENUM(value) (EResType::value, #value)
  224. static const std::map<EResType::Type, std::string> stringToRes = boost::assign::map_list_of
  225. MAP_ENUM(TEXT)
  226. MAP_ENUM(ANIMATION)
  227. MAP_ENUM(MASK)
  228. MAP_ENUM(CAMPAIGN)
  229. MAP_ENUM(MAP)
  230. MAP_ENUM(BMP_FONT)
  231. MAP_ENUM(TTF_FONT)
  232. MAP_ENUM(IMAGE)
  233. MAP_ENUM(VIDEO)
  234. MAP_ENUM(SOUND)
  235. MAP_ENUM(MUSIC)
  236. MAP_ENUM(ARCHIVE_LOD)
  237. MAP_ENUM(ARCHIVE_SND)
  238. MAP_ENUM(ARCHIVE_VID)
  239. MAP_ENUM(PALETTE)
  240. MAP_ENUM(CLIENT_SAVEGAME)
  241. MAP_ENUM(SERVER_SAVEGAME)
  242. MAP_ENUM(DIRECTORY)
  243. MAP_ENUM(ERM)
  244. MAP_ENUM(ERT)
  245. MAP_ENUM(ERS)
  246. MAP_ENUM(OTHER);
  247. #undef MAP_ENUM
  248. auto iter = stringToRes.find(type);
  249. assert(iter != stringToRes.end());
  250. return iter->second;
  251. }
  252. void CResourceHandler::initialize()
  253. {
  254. //recurse only into specific directories
  255. auto recurseInDir = [](std::string URI, int depth)
  256. {
  257. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  258. BOOST_FOREACH(const ResourceLocator & entry, resources)
  259. {
  260. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  261. if (!filename.empty())
  262. {
  263. shared_ptr<ISimpleResourceLoader> dir(new CFilesystemLoader(filename, depth, true));
  264. initialLoader->addLoader(URI + '/', dir, false);
  265. }
  266. }
  267. };
  268. //temporary filesystem that will be used to initialize main one.
  269. //used to solve several case-sensivity issues like Mp3 vs MP3
  270. initialLoader = new CResourceLoader;
  271. resourceLoader = new CResourceLoader;
  272. shared_ptr<ISimpleResourceLoader> rootDir(new CFilesystemLoader(VCMIDirs::get().dataPath(), 0, true));
  273. initialLoader->addLoader("GLOBAL/", rootDir, false);
  274. initialLoader->addLoader("ALL/", rootDir, false);
  275. auto userDir = rootDir;
  276. //add local directory to "ALL" but only if it differs from root dir (true for linux)
  277. if (VCMIDirs::get().dataPath() != VCMIDirs::get().localPath())
  278. {
  279. userDir = shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(VCMIDirs::get().localPath(), 0, true));
  280. initialLoader->addLoader("ALL/", userDir, false);
  281. }
  282. //create "LOCAL" dir with current userDir (may be same as rootDir)
  283. initialLoader->addLoader("LOCAL/", userDir, false);
  284. recurseInDir("ALL/CONFIG", 0);// look for configs
  285. recurseInDir("ALL/DATA", 0); // look for archives
  286. recurseInDir("ALL/MODS", 2); // look for mods. Depth 2 is required for now but won't cause issues if no mods present
  287. }
  288. void CResourceHandler::loadDirectory(const std::string &prefix, const std::string &mountPoint, const JsonNode & config)
  289. {
  290. std::string URI = prefix + config["path"].String();
  291. bool writeable = config["writeable"].Bool();
  292. int depth = 16;
  293. if (!config["depth"].isNull())
  294. depth = config["depth"].Float();
  295. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  296. BOOST_FOREACH(const ResourceLocator & entry, resources)
  297. {
  298. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  299. resourceLoader->addLoader(mountPoint,
  300. shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(filename, depth)), writeable);
  301. }
  302. }
  303. void CResourceHandler::loadArchive(const std::string &prefix, const std::string &mountPoint, const JsonNode & config, EResType::Type archiveType)
  304. {
  305. std::string URI = prefix + config["path"].String();
  306. std::string filename = initialLoader->getResourceName(ResourceID(URI, archiveType));
  307. if (!filename.empty())
  308. resourceLoader->addLoader(mountPoint,
  309. shared_ptr<ISimpleResourceLoader>(new CLodArchiveLoader(filename)), false);
  310. }
  311. void CResourceHandler::loadFileSystem(const std::string & prefix, const std::string &fsConfigURI)
  312. {
  313. auto fsConfigData = initialLoader->loadData(ResourceID(fsConfigURI, EResType::TEXT));
  314. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  315. loadFileSystem(prefix, fsConfig["filesystem"]);
  316. }
  317. void CResourceHandler::loadFileSystem(const std::string & prefix, const JsonNode &fsConfig)
  318. {
  319. BOOST_FOREACH(auto & mountPoint, fsConfig.Struct())
  320. {
  321. BOOST_FOREACH(auto & entry, mountPoint.second.Vector())
  322. {
  323. CStopWatch timer;
  324. logGlobal->debugStream() << "\t\tLoading resource at " << prefix + entry["path"].String();
  325. if (entry["type"].String() == "dir")
  326. loadDirectory(prefix, mountPoint.first, entry);
  327. if (entry["type"].String() == "lod")
  328. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_LOD);
  329. if (entry["type"].String() == "snd")
  330. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_SND);
  331. if (entry["type"].String() == "vid")
  332. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_VID);
  333. logGlobal->debugStream() << "Resource loaded in " << timer.getDiff() << " ms.";
  334. }
  335. }
  336. }
  337. std::vector<std::string> CResourceHandler::getAvailableMods()
  338. {
  339. auto iterator = initialLoader->getIterator([](const ResourceID & ident) -> bool
  340. {
  341. std::string name = ident.getName();
  342. return ident.getType() == EResType::DIRECTORY
  343. && std::count(name.begin(), name.end(), '/') == 2
  344. && boost::algorithm::starts_with(name, "ALL/MODS/");
  345. });
  346. //storage for found mods
  347. std::vector<std::string> foundMods;
  348. while (iterator.hasNext())
  349. {
  350. std::string name = iterator->getName();
  351. name.erase(0, name.find_last_of('/') + 1); //Remove path prefix
  352. if (!name.empty()) // this is also triggered for "ALL/MODS/" entry
  353. foundMods.push_back(name);
  354. ++iterator;
  355. }
  356. return foundMods;
  357. }
  358. void CResourceHandler::setActiveMods(std::vector<std::string> enabledMods)
  359. {
  360. // default FS config for mods: directory "Content" that acts as H3 root directory
  361. JsonNode defaultFS;
  362. defaultFS[""].Vector().resize(1);
  363. defaultFS[""].Vector()[0]["type"].String() = "dir";
  364. defaultFS[""].Vector()[0]["path"].String() = "/Content";
  365. BOOST_FOREACH(std::string & modName, enabledMods)
  366. {
  367. ResourceID modConfFile("all/mods/" + modName + "/mod", EResType::TEXT);
  368. auto fsConfigData = initialLoader->loadData(modConfFile);
  369. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  370. if (!fsConfig["filesystem"].isNull())
  371. loadFileSystem("all/mods/" + modName, fsConfig["filesystem"]);
  372. else
  373. loadFileSystem("all/mods/" + modName, defaultFS);
  374. }
  375. }