ImageLoader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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/ImageLoader.h>
  6. #include <AnKi/Resource/Stb.h>
  7. #include <AnKi/Util/Logger.h>
  8. #include <AnKi/Util/Filesystem.h>
  9. namespace anki {
  10. inline constexpr U8 kTgaHeaderUncompressed[12] = {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  11. inline constexpr U8 kTgaHeaderCompressed[12] = {0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  12. static PtrSize calcRawTexelSize(const ImageBinaryColorFormat cf)
  13. {
  14. PtrSize out;
  15. switch(cf)
  16. {
  17. case ImageBinaryColorFormat::kRgb8:
  18. out = 3;
  19. break;
  20. case ImageBinaryColorFormat::kRgba8:
  21. out = 4;
  22. break;
  23. case ImageBinaryColorFormat::kSrgb8:
  24. out = 3;
  25. break;
  26. case ImageBinaryColorFormat::kRgbFloat:
  27. out = 3 * sizeof(F32);
  28. break;
  29. case ImageBinaryColorFormat::kRgbaFloat:
  30. out = 4 * sizeof(F32);
  31. break;
  32. default:
  33. ANKI_ASSERT(0);
  34. out = 0;
  35. }
  36. return out;
  37. }
  38. static PtrSize calcS3tcBlockSize(const ImageBinaryColorFormat cf)
  39. {
  40. PtrSize out;
  41. switch(cf)
  42. {
  43. case ImageBinaryColorFormat::kRgb8:
  44. out = 8;
  45. break;
  46. case ImageBinaryColorFormat::kRgba8:
  47. out = 16;
  48. break;
  49. case ImageBinaryColorFormat::kSrgb8:
  50. out = 8;
  51. break;
  52. case ImageBinaryColorFormat::kRgbFloat:
  53. out = 16;
  54. break;
  55. default:
  56. ANKI_ASSERT(0);
  57. out = 0;
  58. }
  59. return out;
  60. }
  61. /// Get the size in bytes of a single surface
  62. static PtrSize calcSurfaceSize(const U32 width32, const U32 height32, const ImageBinaryDataCompression comp, const ImageBinaryColorFormat cf,
  63. UVec2 astcBlockSize)
  64. {
  65. const PtrSize width = width32;
  66. const PtrSize height = height32;
  67. PtrSize out = 0;
  68. ANKI_ASSERT(width >= 4 || height >= 4);
  69. switch(comp)
  70. {
  71. case ImageBinaryDataCompression::kRaw:
  72. out = width * height * calcRawTexelSize(cf);
  73. break;
  74. case ImageBinaryDataCompression::kS3tc:
  75. out = (width / 4) * (height / 4) * calcS3tcBlockSize(cf);
  76. break;
  77. case ImageBinaryDataCompression::kEtc:
  78. out = (width / 4) * (height / 4) * 8;
  79. break;
  80. case ImageBinaryDataCompression::kAstc:
  81. out = (width / astcBlockSize.x()) * (height / astcBlockSize.y()) * 16;
  82. break;
  83. default:
  84. ANKI_ASSERT(0);
  85. }
  86. ANKI_ASSERT(out > 0);
  87. return out;
  88. }
  89. /// Get the size in bytes of a single volume
  90. static PtrSize calcVolumeSize(const U width, const U height, const U depth, const ImageBinaryDataCompression comp, const ImageBinaryColorFormat cf)
  91. {
  92. PtrSize out = 0;
  93. ANKI_ASSERT(width >= 4 || height >= 4 || depth >= 4);
  94. switch(comp)
  95. {
  96. case ImageBinaryDataCompression::kRaw:
  97. out = width * height * depth * calcRawTexelSize(cf);
  98. break;
  99. default:
  100. ANKI_ASSERT(0);
  101. }
  102. ANKI_ASSERT(out > 0);
  103. return out;
  104. }
  105. /// Calculate the size of a compressed or uncomressed color data
  106. static PtrSize calcSizeOfSegment(const ImageBinaryHeader& header, ImageBinaryDataCompression comp)
  107. {
  108. PtrSize out = 0;
  109. U32 width = header.m_width;
  110. U32 height = header.m_height;
  111. U32 mips = header.m_mipmapCount;
  112. ANKI_ASSERT(mips > 0);
  113. if(header.m_type != ImageBinaryType::k3D)
  114. {
  115. U32 surfCountPerMip = 0;
  116. switch(header.m_type)
  117. {
  118. case ImageBinaryType::k2D:
  119. surfCountPerMip = 1;
  120. break;
  121. case ImageBinaryType::kCube:
  122. surfCountPerMip = 6;
  123. break;
  124. case ImageBinaryType::k2DArray:
  125. surfCountPerMip = header.m_depthOrLayerCount;
  126. break;
  127. default:
  128. ANKI_ASSERT(0);
  129. break;
  130. }
  131. while(mips-- != 0)
  132. {
  133. out +=
  134. calcSurfaceSize(width, height, comp, header.m_colorFormat, UVec2(header.m_astcBlockSizeX, header.m_astcBlockSizeY)) * surfCountPerMip;
  135. width /= 2;
  136. height /= 2;
  137. }
  138. }
  139. else
  140. {
  141. U depth = header.m_depthOrLayerCount;
  142. while(mips-- != 0)
  143. {
  144. out += calcVolumeSize(width, height, depth, comp, header.m_colorFormat);
  145. width /= 2;
  146. height /= 2;
  147. depth /= 2;
  148. }
  149. }
  150. return out;
  151. }
  152. class ImageLoader::FileInterface
  153. {
  154. public:
  155. virtual Error read(void* buff, PtrSize size) = 0;
  156. virtual Error seek(PtrSize offset, FileSeekOrigin origin) = 0;
  157. virtual PtrSize getSize() const
  158. {
  159. ANKI_ASSERT(!"Not Implemented");
  160. return kMaxPtrSize;
  161. }
  162. };
  163. class ImageLoader::RsrcFile : public FileInterface
  164. {
  165. public:
  166. ResourceFilePtr m_rfile;
  167. Error read(void* buff, PtrSize size) final
  168. {
  169. return m_rfile->read(buff, size);
  170. }
  171. Error seek(PtrSize offset, FileSeekOrigin origin) final
  172. {
  173. return m_rfile->seek(offset, origin);
  174. }
  175. PtrSize getSize() const final
  176. {
  177. return m_rfile->getSize();
  178. }
  179. };
  180. class ImageLoader::SystemFile : public FileInterface
  181. {
  182. public:
  183. File m_file;
  184. Error read(void* buff, PtrSize size) final
  185. {
  186. return m_file.read(buff, size);
  187. }
  188. Error seek(PtrSize offset, FileSeekOrigin origin) final
  189. {
  190. return m_file.seek(offset, origin);
  191. }
  192. PtrSize getSize() const final
  193. {
  194. return m_file.getSize();
  195. }
  196. };
  197. Error ImageLoader::loadAnkiImage(FileInterface& file, U32 maxImageSize, ImageBinaryDataCompression& preferredCompression,
  198. DynamicArray<ImageLoaderSurface, MemoryPoolPtrWrapper<BaseMemoryPool>>& surfaces,
  199. DynamicArray<ImageLoaderVolume, MemoryPoolPtrWrapper<BaseMemoryPool>>& volumes, U32& width, U32& height, U32& depth,
  200. U32& layerCount, U32& mipCount, ImageBinaryType& imageType, ImageBinaryColorFormat& colorFormat,
  201. UVec2& astcBlockSize)
  202. {
  203. //
  204. // Read and check the header
  205. //
  206. ImageBinaryHeader header;
  207. ANKI_CHECK(file.read(&header, sizeof(ImageBinaryHeader)));
  208. if(std::memcmp(&header.m_magic[0], kImageMagic, sizeof(kImageMagic) - 1) != 0)
  209. {
  210. ANKI_RESOURCE_LOGE("Wrong magic word");
  211. return Error::kUserData;
  212. }
  213. if(header.m_width == 0 || !isPowerOfTwo(header.m_width) || header.m_height == 0 || !isPowerOfTwo(header.m_height))
  214. {
  215. ANKI_RESOURCE_LOGE("Incorrect width/height value");
  216. return Error::kUserData;
  217. }
  218. if(header.m_depthOrLayerCount < 1 || header.m_depthOrLayerCount > 4096)
  219. {
  220. ANKI_RESOURCE_LOGE("Zero or too big depth or layerCount");
  221. return Error::kUserData;
  222. }
  223. if(header.m_type < ImageBinaryType::k2D || header.m_type > ImageBinaryType::k2DArray)
  224. {
  225. ANKI_RESOURCE_LOGE("Incorrect header: image type");
  226. return Error::kUserData;
  227. }
  228. if(header.m_colorFormat < ImageBinaryColorFormat::kRgb8 || header.m_colorFormat > ImageBinaryColorFormat::kRgbaFloat)
  229. {
  230. ANKI_RESOURCE_LOGE("Incorrect header: color format");
  231. return Error::kUserData;
  232. }
  233. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kAstc))
  234. {
  235. if((header.m_astcBlockSizeX != 8 && header.m_astcBlockSizeX != 4) || (header.m_astcBlockSizeY != 8 && header.m_astcBlockSizeY != 4))
  236. {
  237. ANKI_RESOURCE_LOGE("Incorrect header: ASTC block size");
  238. return Error::kUserData;
  239. }
  240. }
  241. if(!(header.m_compressionMask & preferredCompression))
  242. {
  243. // Fallback
  244. preferredCompression = ImageBinaryDataCompression::kRaw;
  245. if(!(header.m_compressionMask & preferredCompression))
  246. {
  247. ANKI_RESOURCE_LOGE("File does not contain raw compression");
  248. return Error::kUserData;
  249. }
  250. }
  251. if(header.m_isNormal != 0 && header.m_isNormal != 1)
  252. {
  253. ANKI_RESOURCE_LOGE("Incorrect header: normal");
  254. return Error::kUserData;
  255. }
  256. // Set a few things
  257. colorFormat = header.m_colorFormat;
  258. imageType = header.m_type;
  259. astcBlockSize = UVec2(header.m_astcBlockSizeX, header.m_astcBlockSizeY);
  260. U32 faceCount = 1;
  261. switch(header.m_type)
  262. {
  263. case ImageBinaryType::k2D:
  264. depth = 1;
  265. layerCount = 1;
  266. break;
  267. case ImageBinaryType::kCube:
  268. depth = 1;
  269. layerCount = 1;
  270. faceCount = 6;
  271. break;
  272. case ImageBinaryType::k3D:
  273. depth = header.m_depthOrLayerCount;
  274. layerCount = 1;
  275. break;
  276. case ImageBinaryType::k2DArray:
  277. depth = 1;
  278. layerCount = header.m_depthOrLayerCount;
  279. break;
  280. default:
  281. ANKI_ASSERT(0);
  282. }
  283. //
  284. // Move file pointer
  285. //
  286. PtrSize skipSize = 0;
  287. if(preferredCompression == ImageBinaryDataCompression::kRaw)
  288. {
  289. // Do nothing
  290. }
  291. else if(preferredCompression == ImageBinaryDataCompression::kS3tc)
  292. {
  293. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  294. {
  295. // If raw compression is present then skip it
  296. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  297. }
  298. }
  299. else if(preferredCompression == ImageBinaryDataCompression::kEtc)
  300. {
  301. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  302. {
  303. // If raw compression is present then skip it
  304. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  305. }
  306. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kS3tc))
  307. {
  308. // If s3tc compression is present then skip it
  309. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kS3tc);
  310. }
  311. }
  312. else if(preferredCompression == ImageBinaryDataCompression::kAstc)
  313. {
  314. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  315. {
  316. // If raw compression is present then skip it
  317. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  318. }
  319. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kS3tc))
  320. {
  321. // If s3tc compression is present then skip it
  322. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kS3tc);
  323. }
  324. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kEtc))
  325. {
  326. // If ETC compression is present then skip it
  327. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kEtc);
  328. }
  329. }
  330. if(skipSize)
  331. {
  332. ANKI_CHECK(file.seek(skipSize, FileSeekOrigin::kCurrent));
  333. }
  334. //
  335. // It's time to read
  336. //
  337. // Allocate the surfaces
  338. mipCount = 0;
  339. if(header.m_type != ImageBinaryType::k3D)
  340. {
  341. // Read all surfaces
  342. U32 mipWidth = header.m_width;
  343. U32 mipHeight = header.m_height;
  344. for(U32 mip = 0; mip < header.m_mipmapCount; mip++)
  345. {
  346. for(U32 l = 0; l < layerCount; l++)
  347. {
  348. for(U32 f = 0; f < faceCount; ++f)
  349. {
  350. const PtrSize dataSize = calcSurfaceSize(mipWidth, mipHeight, preferredCompression, header.m_colorFormat,
  351. UVec2(header.m_astcBlockSizeX, header.m_astcBlockSizeY));
  352. // Check if this mipmap can be skipped because of size
  353. if(max(mipWidth, mipHeight) <= maxImageSize || mip == header.m_mipmapCount - 1)
  354. {
  355. ImageLoaderSurface& surf = *surfaces.emplaceBack(surfaces.getMemoryPool());
  356. surf.m_width = mipWidth;
  357. surf.m_height = mipHeight;
  358. surf.m_data.resize(dataSize);
  359. ANKI_CHECK(file.read(&surf.m_data[0], dataSize));
  360. mipCount = max(header.m_mipmapCount - mip, mipCount);
  361. }
  362. else
  363. {
  364. ANKI_CHECK(file.seek(dataSize, FileSeekOrigin::kCurrent));
  365. }
  366. }
  367. }
  368. mipWidth /= 2;
  369. mipHeight /= 2;
  370. }
  371. width = surfaces[0].m_width;
  372. height = surfaces[0].m_height;
  373. depth = kMaxU32;
  374. }
  375. else
  376. {
  377. U32 mipWidth = header.m_width;
  378. U32 mipHeight = header.m_height;
  379. U32 mipDepth = header.m_depthOrLayerCount;
  380. for(U32 mip = 0; mip < header.m_mipmapCount; mip++)
  381. {
  382. const U32 dataSize = U32(calcVolumeSize(mipWidth, mipHeight, mipDepth, preferredCompression, header.m_colorFormat));
  383. // Check if this mipmap can be skipped because of size
  384. if(max(max(mipWidth, mipHeight), mipDepth) <= maxImageSize || mip == header.m_mipmapCount - 1)
  385. {
  386. ImageLoaderVolume& vol = *volumes.emplaceBack(surfaces.getMemoryPool());
  387. vol.m_width = mipWidth;
  388. vol.m_height = mipHeight;
  389. vol.m_depth = mipDepth;
  390. vol.m_data.resize(dataSize);
  391. ANKI_CHECK(file.read(&vol.m_data[0], dataSize));
  392. mipCount = max(header.m_mipmapCount - mip, mipCount);
  393. }
  394. else
  395. {
  396. ANKI_CHECK(file.seek(dataSize, FileSeekOrigin::kCurrent));
  397. }
  398. mipWidth /= 2;
  399. mipHeight /= 2;
  400. mipDepth /= 2;
  401. }
  402. width = volumes[0].m_width;
  403. height = volumes[0].m_height;
  404. depth = volumes[0].m_depth;
  405. }
  406. return Error::kNone;
  407. }
  408. Error ImageLoader::loadStb(Bool isFloat, FileInterface& fs, U32& width, U32& height,
  409. DynamicArray<U8, MemoryPoolPtrWrapper<BaseMemoryPool>, PtrSize>& data)
  410. {
  411. // Read the file
  412. DynamicArray<U8, MemoryPoolPtrWrapper<BaseMemoryPool>, PtrSize> fileData(data.getMemoryPool());
  413. const PtrSize fileSize = fs.getSize();
  414. fileData.resize(fileSize);
  415. ANKI_CHECK(fs.read(&fileData[0], fileSize));
  416. // Use STB to read the image
  417. int stbw, stbh, comp;
  418. stbi_set_flip_vertically_on_load_thread(false);
  419. U8* stbdata;
  420. if(isFloat)
  421. {
  422. stbdata = reinterpret_cast<U8*>(stbi_loadf_from_memory(&fileData[0], I32(fileSize), &stbw, &stbh, &comp, 4));
  423. }
  424. else
  425. {
  426. stbdata = reinterpret_cast<U8*>(stbi_load_from_memory(&fileData[0], I32(fileSize), &stbw, &stbh, &comp, 4));
  427. }
  428. if(!stbdata)
  429. {
  430. ANKI_RESOURCE_LOGE("STB failed to read image");
  431. return Error::kFunctionFailed;
  432. }
  433. // Store it
  434. width = U32(stbw);
  435. height = U32(stbh);
  436. const U32 componentSize = (isFloat) ? sizeof(F32) : sizeof(U8);
  437. data.resize(width * height * 4 * componentSize);
  438. memcpy(&data[0], stbdata, data.getSize());
  439. // Cleanup
  440. stbi_image_free(stbdata);
  441. return Error::kNone;
  442. }
  443. Error ImageLoader::load(ResourceFilePtr rfile, const CString& filename, U32 maxImageSize)
  444. {
  445. RsrcFile file;
  446. file.m_rfile = std::move(rfile);
  447. const Error err = loadInternal(file, filename, maxImageSize);
  448. if(err)
  449. {
  450. ANKI_RESOURCE_LOGE("Failed to read image: %s", filename.cstr());
  451. }
  452. return err;
  453. }
  454. Error ImageLoader::load(const CString& filename, U32 maxImageSize)
  455. {
  456. SystemFile file;
  457. ANKI_CHECK(file.m_file.open(filename, FileOpenFlag::kRead | FileOpenFlag::kBinary));
  458. const Error err = loadInternal(file, filename, maxImageSize);
  459. if(err)
  460. {
  461. ANKI_RESOURCE_LOGE("Failed to read image: %s", filename.cstr());
  462. }
  463. return err;
  464. }
  465. Error ImageLoader::loadInternal(FileInterface& file, const CString& filename, U32 maxImageSize)
  466. {
  467. // get the extension
  468. String ext;
  469. getFilepathExtension(filename, ext);
  470. if(ext.isEmpty())
  471. {
  472. ANKI_RESOURCE_LOGE("Failed to get filename extension");
  473. return Error::kUserData;
  474. }
  475. MemoryPoolPtrWrapper<BaseMemoryPool> pool = m_surfaces.getMemoryPool();
  476. // load from this extension
  477. m_imageType = ImageBinaryType::k2D;
  478. m_compression = ImageBinaryDataCompression::kRaw;
  479. if(ext == "ankitex")
  480. {
  481. #if ANKI_PLATFORM_MOBILE
  482. m_compression = ImageBinaryDataCompression::kAstc;
  483. #else
  484. m_compression = ImageBinaryDataCompression::kS3tc;
  485. #endif
  486. ANKI_CHECK(loadAnkiImage(file, maxImageSize, m_compression, m_surfaces, m_volumes, m_width, m_height, m_depth, m_layerCount, m_mipmapCount,
  487. m_imageType, m_colorFormat, m_astcBlockSize));
  488. }
  489. else if(ext == "png" || ext == "jpg" || ext == "tga")
  490. {
  491. m_surfaces.resize(1, pool);
  492. m_mipmapCount = 1;
  493. m_depth = 1;
  494. m_layerCount = 1;
  495. m_colorFormat = ImageBinaryColorFormat::kRgba8;
  496. ANKI_CHECK(loadStb(false, file, m_surfaces[0].m_width, m_surfaces[0].m_height, m_surfaces[0].m_data));
  497. m_width = m_surfaces[0].m_width;
  498. m_height = m_surfaces[0].m_height;
  499. }
  500. else if(ext == "hdr")
  501. {
  502. m_surfaces.resize(1, pool);
  503. m_mipmapCount = 1;
  504. m_depth = 1;
  505. m_layerCount = 1;
  506. m_colorFormat = ImageBinaryColorFormat::kRgbaFloat;
  507. ANKI_CHECK(loadStb(true, file, m_surfaces[0].m_width, m_surfaces[0].m_height, m_surfaces[0].m_data));
  508. m_width = m_surfaces[0].m_width;
  509. m_height = m_surfaces[0].m_height;
  510. }
  511. else
  512. {
  513. ANKI_RESOURCE_LOGE("Unsupported extension: %s", &ext[0]);
  514. return Error::kUserData;
  515. }
  516. return Error::kNone;
  517. }
  518. const ImageLoaderSurface& ImageLoader::getSurface(U32 level, U32 face, U32 layer) const
  519. {
  520. ANKI_ASSERT(level < m_mipmapCount);
  521. U32 idx = 0;
  522. switch(m_imageType)
  523. {
  524. case ImageBinaryType::k2D:
  525. idx = level;
  526. break;
  527. case ImageBinaryType::kCube:
  528. ANKI_ASSERT(face < 6);
  529. idx = level * 6 + face;
  530. break;
  531. case ImageBinaryType::k3D:
  532. ANKI_ASSERT(0 && "Can't use that for 3D images");
  533. break;
  534. case ImageBinaryType::k2DArray:
  535. idx = level * m_layerCount + layer;
  536. break;
  537. default:
  538. ANKI_ASSERT(0);
  539. }
  540. return m_surfaces[idx];
  541. }
  542. const ImageLoaderVolume& ImageLoader::getVolume(U32 level) const
  543. {
  544. ANKI_ASSERT(m_imageType == ImageBinaryType::k3D);
  545. return m_volumes[level];
  546. }
  547. } // end namespace anki