ResourceFilesystem.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Resource/ResourceFilesystem.h>
  6. #include <AnKi/Util/Filesystem.h>
  7. #include <AnKi/Core/ConfigSet.h>
  8. #include <AnKi/Util/Tracer.h>
  9. #include <ZLib/contrib/minizip/unzip.h>
  10. namespace anki {
  11. /// C resource file
  12. class CResourceFile final : public ResourceFile
  13. {
  14. public:
  15. File m_file;
  16. CResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  17. : ResourceFile(alloc)
  18. {
  19. }
  20. ANKI_USE_RESULT Error read(void* buff, PtrSize size) override
  21. {
  22. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  23. return m_file.read(buff, size);
  24. }
  25. ANKI_USE_RESULT Error readAllText(StringAuto& out) override
  26. {
  27. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  28. return m_file.readAllText(out);
  29. }
  30. ANKI_USE_RESULT Error readU32(U32& u) override
  31. {
  32. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  33. return m_file.readU32(u);
  34. }
  35. ANKI_USE_RESULT Error readF32(F32& f) override
  36. {
  37. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  38. return m_file.readF32(f);
  39. }
  40. ANKI_USE_RESULT Error seek(PtrSize offset, FileSeekOrigin origin) override
  41. {
  42. return m_file.seek(offset, origin);
  43. }
  44. PtrSize getSize() const override
  45. {
  46. return m_file.getSize();
  47. }
  48. };
  49. /// ZIP file
  50. class ZipResourceFile final : public ResourceFile
  51. {
  52. public:
  53. unzFile m_archive = nullptr;
  54. PtrSize m_size = 0;
  55. ZipResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  56. : ResourceFile(alloc)
  57. {
  58. }
  59. ~ZipResourceFile()
  60. {
  61. if(m_archive)
  62. {
  63. // It's open
  64. unzClose(m_archive);
  65. m_archive = nullptr;
  66. m_size = 0;
  67. }
  68. }
  69. ANKI_USE_RESULT Error open(const CString& archive, const CString& archivedFname)
  70. {
  71. // Open archive
  72. m_archive = unzOpen(&archive[0]);
  73. if(m_archive == nullptr)
  74. {
  75. ANKI_RESOURCE_LOGE("Failed to open archive");
  76. return Error::FILE_ACCESS;
  77. }
  78. // Locate archived
  79. const int caseSensitive = 1;
  80. if(unzLocateFile(m_archive, &archivedFname[0], caseSensitive) != UNZ_OK)
  81. {
  82. ANKI_RESOURCE_LOGE("Failed to locate file in archive");
  83. return Error::FILE_ACCESS;
  84. }
  85. // Open file
  86. if(unzOpenCurrentFile(m_archive) != UNZ_OK)
  87. {
  88. ANKI_RESOURCE_LOGE("unzOpenCurrentFile() failed");
  89. return Error::FILE_ACCESS;
  90. }
  91. // Get size just in case
  92. unz_file_info zinfo;
  93. zinfo.uncompressed_size = 0;
  94. unzGetCurrentFileInfo(m_archive, &zinfo, nullptr, 0, nullptr, 0, nullptr, 0);
  95. m_size = zinfo.uncompressed_size;
  96. ANKI_ASSERT(m_size != 0);
  97. return Error::NONE;
  98. }
  99. void close()
  100. {
  101. if(m_archive)
  102. {
  103. unzClose(m_archive);
  104. m_archive = nullptr;
  105. m_size = 0;
  106. }
  107. }
  108. ANKI_USE_RESULT Error read(void* buff, PtrSize size) override
  109. {
  110. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  111. I64 readSize = unzReadCurrentFile(m_archive, buff, U32(size));
  112. if(I64(size) != readSize)
  113. {
  114. ANKI_RESOURCE_LOGE("File read failed");
  115. return Error::FILE_ACCESS;
  116. }
  117. return Error::NONE;
  118. }
  119. ANKI_USE_RESULT Error readAllText(StringAuto& out) override
  120. {
  121. ANKI_ASSERT(m_size);
  122. out.create('?', m_size);
  123. return read(&out[0], m_size);
  124. }
  125. ANKI_USE_RESULT Error readU32(U32& u) override
  126. {
  127. // Assume machine and file have same endianness
  128. ANKI_CHECK(read(&u, sizeof(u)));
  129. return Error::NONE;
  130. }
  131. ANKI_USE_RESULT Error readF32(F32& u) override
  132. {
  133. // Assume machine and file have same endianness
  134. ANKI_CHECK(read(&u, sizeof(u)));
  135. return Error::NONE;
  136. }
  137. ANKI_USE_RESULT Error seek(PtrSize offset, FileSeekOrigin origin) override
  138. {
  139. // Rewind if needed
  140. if(origin == FileSeekOrigin::BEGINNING)
  141. {
  142. if(unzCloseCurrentFile(m_archive) || unzOpenCurrentFile(m_archive))
  143. {
  144. ANKI_RESOURCE_LOGE("Rewind failed");
  145. return Error::FUNCTION_FAILED;
  146. }
  147. }
  148. // Move forward by reading dummy data
  149. Array<char, 128> buff;
  150. while(offset != 0)
  151. {
  152. PtrSize toRead = min<PtrSize>(offset, sizeof(buff));
  153. ANKI_CHECK(read(&buff[0], toRead));
  154. offset -= toRead;
  155. }
  156. return Error::NONE;
  157. }
  158. PtrSize getSize() const override
  159. {
  160. ANKI_ASSERT(m_size > 0);
  161. return m_size;
  162. }
  163. };
  164. ResourceFilesystem::~ResourceFilesystem()
  165. {
  166. for(Path& p : m_paths)
  167. {
  168. p.m_files.destroy(m_alloc);
  169. p.m_path.destroy(m_alloc);
  170. }
  171. m_paths.destroy(m_alloc);
  172. m_cacheDir.destroy(m_alloc);
  173. }
  174. Error ResourceFilesystem::init(const ConfigSet& config, const CString& cacheDir)
  175. {
  176. StringListAuto paths(m_alloc);
  177. paths.splitString(config.getString("rsrc_dataPaths"), ':');
  178. StringListAuto excludedStrings(m_alloc);
  179. excludedStrings.splitString(config.getString("rsrc_dataPathExcludedStrings"), ':');
  180. // Workaround the fact that : is used in drives in Windows
  181. #if ANKI_OS_WINDOWS
  182. StringListAuto paths2(m_alloc);
  183. StringListAuto::Iterator it = paths.getBegin();
  184. while(it != paths.getEnd())
  185. {
  186. const String& s = *it;
  187. StringListAuto::Iterator it2 = it + 1;
  188. if(s.getLength() == 1 && (s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') && it2 != paths.getEnd())
  189. {
  190. paths2.pushBackSprintf("%s:%s", s.cstr(), it2->cstr());
  191. ++it;
  192. }
  193. else
  194. {
  195. paths2.pushBack(s);
  196. }
  197. ++it;
  198. }
  199. paths.destroy();
  200. paths = std::move(paths2);
  201. #endif
  202. if(paths.getSize() < 1)
  203. {
  204. ANKI_RESOURCE_LOGE("Config option \"rsrc_dataPaths\" is empty");
  205. return Error::USER_DATA;
  206. }
  207. #if ANKI_OS_ANDROID
  208. // Add the files of the .apk
  209. ANKI_CHECK(addNewPath("APK package", excludedStrings, true));
  210. #endif
  211. for(auto& path : paths)
  212. {
  213. ANKI_CHECK(addNewPath(path.toCString(), excludedStrings));
  214. }
  215. addCachePath(cacheDir);
  216. return Error::NONE;
  217. }
  218. void ResourceFilesystem::addCachePath(const CString& path)
  219. {
  220. Path p;
  221. p.m_path.create(m_alloc, path);
  222. p.m_isCache = true;
  223. m_paths.emplaceBack(m_alloc, std::move(p));
  224. }
  225. Error ResourceFilesystem::addNewPath(const CString& filepath, const StringListAuto& excludedStrings, Bool special)
  226. {
  227. U32 fileCount = 0; // Count files manually because it's slower to get that number from the list
  228. static const CString extension(".ankizip");
  229. auto rejectPath = [&](CString p) -> Bool {
  230. for(const String& s : excludedStrings)
  231. {
  232. if(p.find(s) != CString::NPOS)
  233. {
  234. return true;
  235. }
  236. }
  237. return false;
  238. };
  239. PtrSize pos;
  240. Path path;
  241. if(special)
  242. {
  243. // Android apk, read the file that contains the directory structure
  244. // Read the file
  245. File dirStructure;
  246. ANKI_CHECK(dirStructure.open("DirStructure.txt", FileOpenFlag::READ | FileOpenFlag::SPECIAL));
  247. StringAuto txt(m_alloc);
  248. ANKI_CHECK(dirStructure.readAllText(txt));
  249. StringListAuto filenames(m_alloc);
  250. filenames.splitString(txt, '\n');
  251. // Create the Path
  252. for(const String& filename : filenames)
  253. {
  254. if(!rejectPath(filename))
  255. {
  256. path.m_files.pushBack(m_alloc, filename);
  257. ++fileCount;
  258. }
  259. }
  260. path.m_isSpecial = true;
  261. }
  262. else if((pos = filepath.find(extension)) != CString::NPOS && pos == filepath.getLength() - extension.getLength())
  263. {
  264. // It's an archive
  265. // Open
  266. unzFile zfile = unzOpen(&filepath[0]);
  267. if(!zfile)
  268. {
  269. ANKI_RESOURCE_LOGE("Failed to open archive");
  270. return Error::FILE_ACCESS;
  271. }
  272. // List files
  273. if(unzGoToFirstFile(zfile) != UNZ_OK)
  274. {
  275. unzClose(zfile);
  276. ANKI_RESOURCE_LOGE("unzGoToFirstFile() failed. Empty archive?");
  277. return Error::FILE_ACCESS;
  278. }
  279. do
  280. {
  281. Array<char, 1024> filename;
  282. unz_file_info info;
  283. if(unzGetCurrentFileInfo(zfile, &info, &filename[0], filename.getSize(), nullptr, 0, nullptr, 0) != UNZ_OK)
  284. {
  285. unzClose(zfile);
  286. ANKI_RESOURCE_LOGE("unzGetCurrentFileInfo() failed");
  287. return Error::FILE_ACCESS;
  288. }
  289. const Bool itsADir = info.uncompressed_size == 0;
  290. if(!itsADir && !rejectPath(&filename[0]))
  291. {
  292. path.m_files.pushBackSprintf(m_alloc, "%s", &filename[0]);
  293. ++fileCount;
  294. }
  295. } while(unzGoToNextFile(zfile) == UNZ_OK);
  296. unzClose(zfile);
  297. path.m_isArchive = true;
  298. }
  299. else
  300. {
  301. // It's simple directory
  302. ANKI_CHECK(walkDirectoryTree(filepath, m_alloc, [&, this](const CString& fname, Bool isDir) -> Error {
  303. if(!isDir && !rejectPath(fname))
  304. {
  305. path.m_files.pushBackSprintf(m_alloc, "%s", fname.cstr());
  306. ++fileCount;
  307. }
  308. return Error::NONE;
  309. }));
  310. }
  311. ANKI_ASSERT(path.m_files.getSize() == fileCount);
  312. if(fileCount == 0)
  313. {
  314. ANKI_RESOURCE_LOGW("Ignoring empty resource path: %s", &filepath[0]);
  315. }
  316. else
  317. {
  318. path.m_path.sprintf(m_alloc, "%s", &filepath[0]);
  319. m_paths.emplaceFront(m_alloc, std::move(path));
  320. ANKI_RESOURCE_LOGI("Added new data path \"%s\" that contains %u files", &filepath[0], fileCount);
  321. }
  322. return Error::NONE;
  323. }
  324. Error ResourceFilesystem::openFile(const ResourceFilename& filename, ResourceFilePtr& filePtr)
  325. {
  326. ResourceFile* rfile = nullptr;
  327. Error err = Error::NONE;
  328. // Search for the fname in reverse order
  329. for(const Path& p : m_paths)
  330. {
  331. // Check if it's cache
  332. if(p.m_isCache)
  333. {
  334. StringAuto newFname(m_alloc);
  335. newFname.sprintf("%s/%s", &p.m_path[0], &filename[0]);
  336. if(fileExists(newFname.toCString()))
  337. {
  338. // In cache
  339. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  340. rfile = file;
  341. err = file->m_file.open(&newFname[0], FileOpenFlag::READ);
  342. }
  343. }
  344. else
  345. {
  346. // In data path or archive
  347. for(const String& pfname : p.m_files)
  348. {
  349. if(pfname != filename)
  350. {
  351. continue;
  352. }
  353. // Found
  354. if(p.m_isArchive)
  355. {
  356. ZipResourceFile* file = m_alloc.newInstance<ZipResourceFile>(m_alloc);
  357. rfile = file;
  358. err = file->open(p.m_path.toCString(), filename);
  359. }
  360. else
  361. {
  362. StringAuto newFname(m_alloc);
  363. if(!p.m_isSpecial)
  364. {
  365. newFname.sprintf("%s/%s", &p.m_path[0], &filename[0]);
  366. }
  367. else
  368. {
  369. newFname.sprintf("%s", &filename[0]);
  370. }
  371. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  372. rfile = file;
  373. FileOpenFlag fopenFlags = FileOpenFlag::READ;
  374. if(p.m_isSpecial)
  375. {
  376. fopenFlags |= FileOpenFlag::SPECIAL;
  377. }
  378. err = file->m_file.open(&newFname[0], fopenFlags);
  379. #if 0
  380. printf("Opening asset %s\n", &newFname[0]);
  381. #endif
  382. }
  383. }
  384. } // end if cache
  385. if(rfile)
  386. {
  387. break;
  388. }
  389. } // end for all paths
  390. if(err)
  391. {
  392. m_alloc.deleteInstance(rfile);
  393. return err;
  394. }
  395. // File not found? Try to find it outside the resource dirs
  396. if(!rfile && fileExists(filename))
  397. {
  398. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  399. err = file->m_file.open(filename, FileOpenFlag::READ);
  400. if(err)
  401. {
  402. m_alloc.deleteInstance(file);
  403. return err;
  404. }
  405. rfile = file;
  406. ANKI_RESOURCE_LOGW(
  407. "Loading resource outside the resource paths/archives. This is only OK for tools and debugging: %s",
  408. filename.cstr());
  409. }
  410. if(!rfile)
  411. {
  412. ANKI_RESOURCE_LOGE("File not found: %s", &filename[0]);
  413. return Error::USER_DATA;
  414. }
  415. // Done
  416. filePtr.reset(rfile);
  417. return Error::NONE;
  418. }
  419. } // end namespace anki