ResourceFilesystem.cpp 11 KB

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