CResourceLoader.cpp 14 KB

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