CResourceLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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::FONT)
  186. (".BMP", EResType::IMAGE)
  187. (".JPG", EResType::IMAGE)
  188. (".PCX", EResType::IMAGE)
  189. (".PNG", EResType::IMAGE)
  190. (".TGA", EResType::IMAGE)
  191. (".WAV", EResType::SOUND)
  192. (".82M", EResType::SOUND)
  193. (".SMK", EResType::VIDEO)
  194. (".BIK", EResType::VIDEO)
  195. (".MJPG", EResType::VIDEO)
  196. (".MP3", EResType::MUSIC)
  197. (".OGG", EResType::MUSIC)
  198. (".LOD", EResType::ARCHIVE)
  199. (".PAC", EResType::ARCHIVE)
  200. (".VID", EResType::ARCHIVE)
  201. (".SND", EResType::ARCHIVE)
  202. (".PAL", EResType::PALETTE)
  203. (".VCGM1", EResType::CLIENT_SAVEGAME)
  204. (".VLGM1", EResType::LIB_SAVEGAME)
  205. (".VSGM1", EResType::SERVER_SAVEGAME);
  206. auto iter = stringToRes.find(extension);
  207. if (iter == stringToRes.end())
  208. return EResType::OTHER;
  209. return iter->second;
  210. }
  211. std::string EResTypeHelper::getEResTypeAsString(EResType::Type type)
  212. {
  213. #define MAP_ENUM(value) (EResType::value, #value)
  214. static const std::map<EResType::Type, std::string> stringToRes = boost::assign::map_list_of
  215. MAP_ENUM(TEXT)
  216. MAP_ENUM(ANIMATION)
  217. MAP_ENUM(MASK)
  218. MAP_ENUM(CAMPAIGN)
  219. MAP_ENUM(MAP)
  220. MAP_ENUM(FONT)
  221. MAP_ENUM(IMAGE)
  222. MAP_ENUM(VIDEO)
  223. MAP_ENUM(SOUND)
  224. MAP_ENUM(MUSIC)
  225. MAP_ENUM(ARCHIVE)
  226. MAP_ENUM(PALETTE)
  227. MAP_ENUM(CLIENT_SAVEGAME)
  228. MAP_ENUM(LIB_SAVEGAME)
  229. MAP_ENUM(SERVER_SAVEGAME)
  230. MAP_ENUM(DIRECTORY)
  231. MAP_ENUM(OTHER);
  232. #undef MAP_ENUM
  233. auto iter = stringToRes.find(type);
  234. assert(iter != stringToRes.end());
  235. return iter->second;
  236. }
  237. void CResourceHandler::initialize()
  238. {
  239. //recurse only into specific directories
  240. auto recurseInDir = [](std::string URI, int depth)
  241. {
  242. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  243. BOOST_FOREACH(const ResourceLocator & entry, resources)
  244. {
  245. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  246. if (!filename.empty())
  247. {
  248. shared_ptr<ISimpleResourceLoader> dir(new CFilesystemLoader(filename, depth, true));
  249. initialLoader->addLoader(URI + '/', dir, false);
  250. }
  251. }
  252. };
  253. //temporary filesystem that will be used to initialize main one.
  254. //used to solve several case-sensivity issues like Mp3 vs MP3
  255. initialLoader = new CResourceLoader;
  256. resourceLoader = new CResourceLoader;
  257. shared_ptr<ISimpleResourceLoader> rootDir(new CFilesystemLoader(GameConstants::DATA_DIR, 0, true));
  258. initialLoader->addLoader("GLOBAL/", rootDir, false);
  259. initialLoader->addLoader("ALL/", rootDir, false);
  260. auto userDir = rootDir;
  261. //add local directory to "ALL" but only if it differs from root dir (true for linux)
  262. if (GameConstants::DATA_DIR != GVCMIDirs.UserPath)
  263. {
  264. userDir = shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(GVCMIDirs.UserPath, 0, true));
  265. initialLoader->addLoader("ALL/", userDir, false);
  266. }
  267. //create "LOCAL" dir with current userDir (may be same as rootDir)
  268. initialLoader->addLoader("LOCAL/", userDir, false);
  269. recurseInDir("ALL/CONFIG", 0);// look for configs
  270. recurseInDir("ALL/DATA", 0); // look for archives
  271. recurseInDir("ALL/MODS", 2); // look for mods. Depth 2 is required for now but won't cause issues if no mods present
  272. }
  273. void CResourceHandler::loadFileSystem(const std::string fsConfigURI)
  274. {
  275. auto fsConfigData = initialLoader->loadData(ResourceID(fsConfigURI, EResType::TEXT));
  276. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  277. BOOST_FOREACH(auto & mountPoint, fsConfig["filesystem"].Struct())
  278. {
  279. BOOST_FOREACH(auto & entry, mountPoint.second.Vector())
  280. {
  281. CStopWatch timer;
  282. tlog5 << "\t\tLoading resource at " << entry["path"].String();
  283. std::string URI = entry["path"].String();
  284. if (entry["type"].String() == "dir")
  285. {
  286. bool writeable = entry["writeable"].Bool();
  287. int depth = 16;
  288. if (!entry["depth"].isNull())
  289. depth = entry["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.first,
  295. shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(filename, depth)), writeable);
  296. }
  297. }
  298. if (entry["type"].String() == "file")
  299. {
  300. std::string filename = initialLoader->getResourceName(ResourceID(URI, EResType::ARCHIVE));
  301. if (!filename.empty())
  302. resourceLoader->addLoader(mountPoint.first,
  303. shared_ptr<ISimpleResourceLoader>(new CLodArchiveLoader(filename)), false);
  304. }
  305. tlog5 << " took " << timer.getDiff() << " ms.\n";
  306. }
  307. }
  308. }
  309. void CResourceHandler::loadModsFilesystems()
  310. {
  311. auto iterator = initialLoader->getIterator([](const ResourceID & ident) -> bool
  312. {
  313. std::string name = ident.getName();
  314. return ident.getType() == EResType::TEXT
  315. && std::count(name.begin(), name.end(), '/') == 3
  316. && boost::algorithm::starts_with(name, "ALL/MODS/")
  317. && boost::algorithm::ends_with(name, "FILESYSTEM");
  318. });
  319. //sorted storage for found mods
  320. //implements basic load order (entries in hashtable are basically random)
  321. std::set<std::string> foundMods;
  322. while (iterator.hasNext())
  323. {
  324. foundMods.insert(iterator->getName());
  325. ++iterator;
  326. }
  327. BOOST_FOREACH(const std::string & entry, foundMods)
  328. {
  329. tlog1 << "\t\tFound mod filesystem: " << entry << "\n";
  330. loadFileSystem(entry);
  331. }
  332. }