ImageLoader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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, Vec4& avgColor)
  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. avgColor = Vec4(header.m_averageColor);
  257. // Set a few things
  258. colorFormat = header.m_colorFormat;
  259. imageType = header.m_type;
  260. astcBlockSize = UVec2(header.m_astcBlockSizeX, header.m_astcBlockSizeY);
  261. U32 faceCount = 1;
  262. switch(header.m_type)
  263. {
  264. case ImageBinaryType::k2D:
  265. depth = 1;
  266. layerCount = 1;
  267. break;
  268. case ImageBinaryType::kCube:
  269. depth = 1;
  270. layerCount = 1;
  271. faceCount = 6;
  272. break;
  273. case ImageBinaryType::k3D:
  274. depth = header.m_depthOrLayerCount;
  275. layerCount = 1;
  276. break;
  277. case ImageBinaryType::k2DArray:
  278. depth = 1;
  279. layerCount = header.m_depthOrLayerCount;
  280. break;
  281. default:
  282. ANKI_ASSERT(0);
  283. }
  284. //
  285. // Move file pointer
  286. //
  287. PtrSize skipSize = 0;
  288. if(preferredCompression == ImageBinaryDataCompression::kRaw)
  289. {
  290. // Do nothing
  291. }
  292. else if(preferredCompression == ImageBinaryDataCompression::kS3tc)
  293. {
  294. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  295. {
  296. // If raw compression is present then skip it
  297. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  298. }
  299. }
  300. else if(preferredCompression == ImageBinaryDataCompression::kEtc)
  301. {
  302. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  303. {
  304. // If raw compression is present then skip it
  305. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  306. }
  307. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kS3tc))
  308. {
  309. // If s3tc compression is present then skip it
  310. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kS3tc);
  311. }
  312. }
  313. else if(preferredCompression == ImageBinaryDataCompression::kAstc)
  314. {
  315. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kRaw))
  316. {
  317. // If raw compression is present then skip it
  318. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kRaw);
  319. }
  320. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kS3tc))
  321. {
  322. // If s3tc compression is present then skip it
  323. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kS3tc);
  324. }
  325. if(!!(header.m_compressionMask & ImageBinaryDataCompression::kEtc))
  326. {
  327. // If ETC compression is present then skip it
  328. skipSize += calcSizeOfSegment(header, ImageBinaryDataCompression::kEtc);
  329. }
  330. }
  331. if(skipSize)
  332. {
  333. ANKI_CHECK(file.seek(skipSize, FileSeekOrigin::kCurrent));
  334. }
  335. //
  336. // It's time to read
  337. //
  338. // Allocate the surfaces
  339. mipCount = 0;
  340. if(header.m_type != ImageBinaryType::k3D)
  341. {
  342. // Read all surfaces
  343. U32 mipWidth = header.m_width;
  344. U32 mipHeight = header.m_height;
  345. for(U32 mip = 0; mip < header.m_mipmapCount; mip++)
  346. {
  347. for(U32 l = 0; l < layerCount; l++)
  348. {
  349. for(U32 f = 0; f < faceCount; ++f)
  350. {
  351. const PtrSize dataSize = calcSurfaceSize(mipWidth, mipHeight, preferredCompression, header.m_colorFormat,
  352. UVec2(header.m_astcBlockSizeX, header.m_astcBlockSizeY));
  353. // Check if this mipmap can be skipped because of size
  354. if(max(mipWidth, mipHeight) <= maxImageSize || mip == header.m_mipmapCount - 1)
  355. {
  356. ImageLoaderSurface& surf = *surfaces.emplaceBack(surfaces.getMemoryPool());
  357. surf.m_width = mipWidth;
  358. surf.m_height = mipHeight;
  359. surf.m_data.resize(dataSize);
  360. ANKI_CHECK(file.read(&surf.m_data[0], dataSize));
  361. mipCount = max(header.m_mipmapCount - mip, mipCount);
  362. }
  363. else
  364. {
  365. ANKI_CHECK(file.seek(dataSize, FileSeekOrigin::kCurrent));
  366. }
  367. }
  368. }
  369. mipWidth /= 2;
  370. mipHeight /= 2;
  371. }
  372. width = surfaces[0].m_width;
  373. height = surfaces[0].m_height;
  374. depth = kMaxU32;
  375. }
  376. else
  377. {
  378. U32 mipWidth = header.m_width;
  379. U32 mipHeight = header.m_height;
  380. U32 mipDepth = header.m_depthOrLayerCount;
  381. for(U32 mip = 0; mip < header.m_mipmapCount; mip++)
  382. {
  383. const U32 dataSize = U32(calcVolumeSize(mipWidth, mipHeight, mipDepth, preferredCompression, header.m_colorFormat));
  384. // Check if this mipmap can be skipped because of size
  385. if(max(max(mipWidth, mipHeight), mipDepth) <= maxImageSize || mip == header.m_mipmapCount - 1)
  386. {
  387. ImageLoaderVolume& vol = *volumes.emplaceBack(surfaces.getMemoryPool());
  388. vol.m_width = mipWidth;
  389. vol.m_height = mipHeight;
  390. vol.m_depth = mipDepth;
  391. vol.m_data.resize(dataSize);
  392. ANKI_CHECK(file.read(&vol.m_data[0], dataSize));
  393. mipCount = max(header.m_mipmapCount - mip, mipCount);
  394. }
  395. else
  396. {
  397. ANKI_CHECK(file.seek(dataSize, FileSeekOrigin::kCurrent));
  398. }
  399. mipWidth /= 2;
  400. mipHeight /= 2;
  401. mipDepth /= 2;
  402. }
  403. width = volumes[0].m_width;
  404. height = volumes[0].m_height;
  405. depth = volumes[0].m_depth;
  406. }
  407. return Error::kNone;
  408. }
  409. Error ImageLoader::loadStb(Bool isFloat, FileInterface& fs, U32& width, U32& height,
  410. DynamicArray<U8, MemoryPoolPtrWrapper<BaseMemoryPool>, PtrSize>& data)
  411. {
  412. // Read the file
  413. DynamicArray<U8, MemoryPoolPtrWrapper<BaseMemoryPool>, PtrSize> fileData(data.getMemoryPool());
  414. const PtrSize fileSize = fs.getSize();
  415. fileData.resize(fileSize);
  416. ANKI_CHECK(fs.read(&fileData[0], fileSize));
  417. // Use STB to read the image
  418. int stbw, stbh, comp;
  419. stbi_set_flip_vertically_on_load_thread(false);
  420. U8* stbdata;
  421. if(isFloat)
  422. {
  423. stbdata = reinterpret_cast<U8*>(stbi_loadf_from_memory(&fileData[0], I32(fileSize), &stbw, &stbh, &comp, 4));
  424. }
  425. else
  426. {
  427. stbdata = reinterpret_cast<U8*>(stbi_load_from_memory(&fileData[0], I32(fileSize), &stbw, &stbh, &comp, 4));
  428. }
  429. if(!stbdata)
  430. {
  431. ANKI_RESOURCE_LOGE("STB failed to read image");
  432. return Error::kFunctionFailed;
  433. }
  434. // Store it
  435. width = U32(stbw);
  436. height = U32(stbh);
  437. const U32 componentSize = (isFloat) ? sizeof(F32) : sizeof(U8);
  438. data.resize(width * height * 4 * componentSize);
  439. memcpy(&data[0], stbdata, data.getSize());
  440. // Cleanup
  441. stbi_image_free(stbdata);
  442. return Error::kNone;
  443. }
  444. Error ImageLoader::load(ResourceFilePtr rfile, const CString& filename, U32 maxImageSize)
  445. {
  446. RsrcFile file;
  447. file.m_rfile = std::move(rfile);
  448. const Error err = loadInternal(file, filename, maxImageSize);
  449. if(err)
  450. {
  451. ANKI_RESOURCE_LOGE("Failed to read image: %s", filename.cstr());
  452. }
  453. return err;
  454. }
  455. Error ImageLoader::load(const CString& filename, U32 maxImageSize)
  456. {
  457. SystemFile file;
  458. ANKI_CHECK(file.m_file.open(filename, FileOpenFlag::kRead | FileOpenFlag::kBinary));
  459. const Error err = loadInternal(file, filename, maxImageSize);
  460. if(err)
  461. {
  462. ANKI_RESOURCE_LOGE("Failed to read image: %s", filename.cstr());
  463. }
  464. return err;
  465. }
  466. Error ImageLoader::loadInternal(FileInterface& file, const CString& filename, U32 maxImageSize)
  467. {
  468. // get the extension
  469. String ext;
  470. getFilepathExtension(filename, ext);
  471. if(ext.isEmpty())
  472. {
  473. ANKI_RESOURCE_LOGE("Failed to get filename extension");
  474. return Error::kUserData;
  475. }
  476. MemoryPoolPtrWrapper<BaseMemoryPool> pool = m_surfaces.getMemoryPool();
  477. // load from this extension
  478. m_imageType = ImageBinaryType::k2D;
  479. m_compression = ImageBinaryDataCompression::kRaw;
  480. if(ext == "ankitex")
  481. {
  482. #if ANKI_PLATFORM_MOBILE
  483. m_compression = ImageBinaryDataCompression::kAstc;
  484. #else
  485. m_compression = ImageBinaryDataCompression::kS3tc;
  486. #endif
  487. ANKI_CHECK(loadAnkiImage(file, maxImageSize, m_compression, m_surfaces, m_volumes, m_width, m_height, m_depth, m_layerCount, m_mipmapCount,
  488. m_imageType, m_colorFormat, m_astcBlockSize, m_avgColor));
  489. }
  490. else if(ext == "png" || ext == "jpg" || ext == "tga")
  491. {
  492. m_surfaces.resize(1, pool);
  493. m_mipmapCount = 1;
  494. m_depth = 1;
  495. m_layerCount = 1;
  496. m_colorFormat = ImageBinaryColorFormat::kRgba8;
  497. ANKI_CHECK(loadStb(false, file, m_surfaces[0].m_width, m_surfaces[0].m_height, m_surfaces[0].m_data));
  498. m_width = m_surfaces[0].m_width;
  499. m_height = m_surfaces[0].m_height;
  500. }
  501. else if(ext == "hdr")
  502. {
  503. m_surfaces.resize(1, pool);
  504. m_mipmapCount = 1;
  505. m_depth = 1;
  506. m_layerCount = 1;
  507. m_colorFormat = ImageBinaryColorFormat::kRgbaFloat;
  508. ANKI_CHECK(loadStb(true, file, m_surfaces[0].m_width, m_surfaces[0].m_height, m_surfaces[0].m_data));
  509. m_width = m_surfaces[0].m_width;
  510. m_height = m_surfaces[0].m_height;
  511. }
  512. else
  513. {
  514. ANKI_RESOURCE_LOGE("Unsupported extension: %s", &ext[0]);
  515. return Error::kUserData;
  516. }
  517. return Error::kNone;
  518. }
  519. const ImageLoaderSurface& ImageLoader::getSurface(U32 level, U32 face, U32 layer) const
  520. {
  521. ANKI_ASSERT(level < m_mipmapCount);
  522. U32 idx = 0;
  523. switch(m_imageType)
  524. {
  525. case ImageBinaryType::k2D:
  526. idx = level;
  527. break;
  528. case ImageBinaryType::kCube:
  529. ANKI_ASSERT(face < 6);
  530. idx = level * 6 + face;
  531. break;
  532. case ImageBinaryType::k3D:
  533. ANKI_ASSERT(0 && "Can't use that for 3D images");
  534. break;
  535. case ImageBinaryType::k2DArray:
  536. idx = level * m_layerCount + layer;
  537. break;
  538. default:
  539. ANKI_ASSERT(0);
  540. }
  541. return m_surfaces[idx];
  542. }
  543. const ImageLoaderVolume& ImageLoader::getVolume(U32 level) const
  544. {
  545. ANKI_ASSERT(m_imageType == ImageBinaryType::k3D);
  546. return m_volumes[level];
  547. }
  548. } // end namespace anki