bitmapSTB.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "core/stream/fileStream.h"
  25. #include "core/stream/memStream.h"
  26. #include "core/strings/stringFunctions.h"
  27. #include "gfx/bitmap/gBitmap.h"
  28. #include "gfx/bitmap/imageUtils.h"
  29. #include "gfx/bitmap/loaders/ies/ies_loader.h"
  30. #ifdef __clang__
  31. #define STBIWDEF static inline
  32. #endif
  33. #pragma warning( push )
  34. #pragma warning( disable : 4505 ) // unreferenced function removed.
  35. #ifndef STB_IMAGE_IMPLEMENTATION
  36. #define STB_IMAGE_IMPLEMENTATION
  37. #define STB_IMAGE_STATIC
  38. #include "stb_image.h"
  39. #endif
  40. #define STB_IMAGE_WRITE_IMPLEMENTATION
  41. #define STB_IMAGE_WRITE_STATIC
  42. #include "stb_image_write.h"
  43. #pragma warning(pop)
  44. static bool sReadSTB(const Torque::Path& path, GBitmap* bitmap);
  45. static bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len);
  46. static bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel);
  47. static bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel);
  48. // stbi_write callback / rextimmy.
  49. static void stbiWriteFunc(void* context, void* data, int size)
  50. {
  51. Stream* stream = static_cast<Stream*>(context);
  52. stream->write(size);
  53. stream->write(size, data);
  54. }
  55. static struct _privateRegisterSTB
  56. {
  57. _privateRegisterSTB()
  58. {
  59. GBitmap::Registration reg;
  60. reg.priority = 100;
  61. reg.extensions.push_back("png");
  62. reg.extensions.push_back("bmp");
  63. reg.extensions.push_back("jpg");
  64. reg.extensions.push_back("jpeg");
  65. reg.extensions.push_back("psd");
  66. reg.extensions.push_back("hdr");
  67. reg.extensions.push_back("tga");
  68. reg.extensions.push_back("ies");
  69. reg.readFunc = sReadSTB;
  70. reg.readStreamFunc = sReadStreamSTB;
  71. reg.writeFunc = sWriteSTB;
  72. reg.writeStreamFunc = sWriteStreamSTB;
  73. // for png only.
  74. reg.defaultCompression = 6;
  75. GBitmap::sRegisterFormat(reg);
  76. }
  77. } sStaticRegisterSTB;
  78. bool sReadSTB(const Torque::Path& path, GBitmap* bitmap)
  79. {
  80. PROFILE_SCOPE(sReadSTB);
  81. S32 x, y, n, channels;
  82. String ext = path.getExtension();
  83. U32 prevWaterMark = FrameAllocator::getWaterMark();
  84. // if this is an ies profile we need to create a texture for it.
  85. if (ext.equal("ies"))
  86. {
  87. String textureName = path.getFullPath();
  88. textureName.replace(".ies", ".png");
  89. x = 256;
  90. y = 1;
  91. n = 4;
  92. channels = 4;
  93. GFXFormat format = GFXFormatR8G8B8A8;
  94. if (Torque::FS::IsFile(textureName.c_str()))
  95. {
  96. // if the txture already exist, load it.
  97. unsigned char* data = stbi_load(textureName.c_str(), &x, &y, &n, channels);
  98. // actually allocate the bitmap space...
  99. bitmap->allocateBitmap(x, y,
  100. false, // don't extrude miplevels...
  101. format); // use determined format...
  102. U8* pBase = (U8*)bitmap->getBits();
  103. U32 rowBytes = bitmap->getByteSize();
  104. dMemcpy(pBase, data, rowBytes);
  105. stbi_image_free(data);
  106. FrameAllocator::setWaterMark(prevWaterMark);
  107. return true;
  108. }
  109. else
  110. {
  111. FileStream* readIes = new FileStream;
  112. if (!readIes->open(path.getFullPath(), Torque::FS::File::Read))
  113. {
  114. Con::printf("Failed to open IES profile:%s", path.getFullFileName().c_str());
  115. return false;
  116. }
  117. if (readIes->getStatus() != Stream::Ok)
  118. {
  119. Con::printf("Failed to open IES profile:%s", path.getFullFileName().c_str());
  120. return false;
  121. }
  122. U32 buffSize = readIes->getStreamSize();
  123. char* buffer = new char[buffSize];
  124. readIes->read(buffSize, buffer);
  125. IESFileInfo info;
  126. IESLoadHelper IESLoader;
  127. if (!IESLoader.load(buffer, buffSize, info))
  128. {
  129. Con::printf("Failed to load IES profile:%s \n LoaderError: %s", path.getFullFileName().c_str(), info.error().c_str());
  130. return false;
  131. }
  132. float* data = new float[x*y*channels];
  133. if (!IESLoader.saveAs1D(info, data, x, channels))
  134. {
  135. Con::printf("Failed to create 2d Texture for IES profile:%s", path.getFullFileName().c_str());
  136. return false;
  137. }
  138. // use stb function to convert float data to uchar
  139. unsigned char* dataChar = stbi__hdr_to_ldr(data, x, y, channels);
  140. bitmap->deleteImage();
  141. // actually allocate the bitmap space...
  142. bitmap->allocateBitmap(x, y,
  143. false,
  144. format);
  145. U8* pBase = (U8*)bitmap->getBits();
  146. U32 rowBytes = x * y * channels;
  147. dMemcpy(pBase, dataChar, rowBytes);
  148. stbi_image_free(dataChar);
  149. FrameAllocator::setWaterMark(prevWaterMark);
  150. sWriteSTB(textureName, bitmap, 10);
  151. return true;
  152. }
  153. }
  154. if (!stbi_info(path.getFullPath().c_str(), &x, &y, &channels))
  155. {
  156. FrameAllocator::setWaterMark(prevWaterMark);
  157. const char* stbErr = stbi_failure_reason();
  158. if (!stbErr)
  159. stbErr = "Unknown Error!";
  160. Con::errorf("STB get file info: %s", stbErr);
  161. }
  162. // do this to map 2 channels to 4, 2 channel not supported by gbitmap yet..
  163. if (channels == 2)
  164. channels = 4;
  165. if (!ext.equal("png"))
  166. {
  167. if (stbi_is_16_bit(path.getFullPath().c_str()))
  168. {
  169. U16* data = stbi_load_16(path.getFullPath().c_str(), &x, &y, &n, channels);
  170. // if succesful deal make the bitmap, else try other loaders.
  171. if (data)
  172. {
  173. GFXFormat format;
  174. if (n == 1)
  175. format = GFXFormatL16;
  176. else
  177. format = GFXFormatR16G16B16A16; // not sure if this is correct.
  178. bitmap->deleteImage();
  179. // actually allocate the bitmap space...
  180. bitmap->allocateBitmap(x, y,
  181. false, // don't extrude miplevels...
  182. format); // use determined format...
  183. U16* pBase = (U16*)bitmap->getBits();
  184. U32 rowBytes = bitmap->getByteSize();
  185. dMemcpy(pBase, data, rowBytes);
  186. stbi_image_free(data);
  187. FrameAllocator::setWaterMark(prevWaterMark);
  188. return true;
  189. }
  190. }
  191. }
  192. if (ext.equal("hdr"))
  193. {
  194. // force load to 4 channel.
  195. float* data = stbi_loadf(path.getFullPath().c_str(), &x, &y, &n, 0);
  196. unsigned char* dataChar = stbi__hdr_to_ldr(data, x, y, n);
  197. bitmap->deleteImage();
  198. // actually allocate the bitmap space...
  199. bitmap->allocateBitmap(x, y,
  200. false,
  201. GFXFormatR8G8B8);
  202. U8* pBase = (U8*)bitmap->getBits();
  203. U32 rowBytes = x * y * n;
  204. dMemcpy(pBase, dataChar, rowBytes);
  205. //stbi_image_free(data);
  206. stbi_image_free(dataChar);
  207. FrameAllocator::setWaterMark(prevWaterMark);
  208. return true;
  209. }
  210. unsigned char* data = stbi_load(path.getFullPath().c_str(), &x, &y, &n, channels);
  211. bitmap->deleteImage();
  212. GFXFormat format;
  213. switch (channels) {
  214. case 1:
  215. format = GFXFormatA8;
  216. break;
  217. case 2:
  218. format = GFXFormatA8L8;
  219. break;
  220. case 3:
  221. format = GFXFormatR8G8B8;
  222. break;
  223. case 4:
  224. format = GFXFormatR8G8B8A8;
  225. break;
  226. default:
  227. FrameAllocator::setWaterMark(prevWaterMark);
  228. return false;
  229. }
  230. // actually allocate the bitmap space...
  231. bitmap->allocateBitmap(x, y,
  232. false, // don't extrude miplevels...
  233. format); // use determined format...
  234. U8* pBase = (U8*)bitmap->getBits();
  235. U32 rowBytes = bitmap->getByteSize();
  236. dMemcpy(pBase, data, rowBytes);
  237. stbi_image_free(data);
  238. // Check this bitmap for transparency
  239. if (channels == 4)
  240. bitmap->checkForTransparency();
  241. FrameAllocator::setWaterMark(prevWaterMark);
  242. return true;
  243. }
  244. bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len)
  245. {
  246. PROFILE_SCOPE(sReadStreamSTB);
  247. // only used for font at the moment.
  248. U8* data = new U8[len];
  249. stream.read(len, data);
  250. S32 width, height, comp = 0;
  251. unsigned char* pixelData = stbi_load_from_memory((const U8*)data, (int)len, &width, &height, &comp, 0);
  252. if (!pixelData)
  253. {
  254. const char* stbErr = stbi_failure_reason();
  255. if (!stbErr)
  256. stbErr = "Unknown Error!";
  257. Con::errorf("sReadStreamSTB Error: %s", stbErr);
  258. return false;
  259. }
  260. bitmap->deleteImage();
  261. //work out what format we need to use - todo floating point?
  262. GFXFormat fmt = GFXFormat_FIRST;
  263. switch (comp)
  264. {
  265. case 1: fmt = GFXFormatA8; break;
  266. case 2: fmt = GFXFormatA8L8; break; //todo check this
  267. case 3: fmt = GFXFormatR8G8B8; break;
  268. case 4: fmt = GFXFormatR8G8B8A8; break;
  269. }
  270. bitmap->allocateBitmap(width, height, false, fmt);
  271. U8* pBase = bitmap->getWritableBits(0);
  272. U32 rowBytes = bitmap->getByteSize();
  273. dMemcpy(pBase, pixelData, rowBytes);
  274. dFree(data);
  275. dFree(pixelData);
  276. return true;
  277. }
  278. /**
  279. * Write bitmap to an image file.
  280. *
  281. * @param[in] path Destination image file path. File name extension determines image format.
  282. * ".bmp" for Microsoft Bitmap.
  283. * ".hdr" for High Dynamic Range (HDR).
  284. * ".jpg" or ".jpeg" for Joint Photographic Experts Group (JPEG).
  285. * ".png" for Portable Network Graphics (PNG).
  286. * ".tga" for Truevision TGA (TARGA).
  287. *
  288. *
  289. * @param[in] bitmap Source bitmap to encode image from.
  290. * @param compressionLevel Image format specific compression level.
  291. * For JPEG sets the quality level percentage, range 0 to 100.
  292. * Not used for other image formats.
  293. */
  294. bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel)
  295. {
  296. PROFILE_SCOPE(sWriteSTB);
  297. // get our data to be saved.
  298. U32 width = bitmap->getWidth();
  299. U32 height = bitmap->getHeight();
  300. U32 bytes = bitmap->getBytesPerPixel();
  301. GFXFormat format = bitmap->getFormat();
  302. String ext = path.getExtension();
  303. // we always have at least 1
  304. U32 comp = 1;
  305. if (format == GFXFormatR8G8B8)
  306. {
  307. comp = 3;
  308. }
  309. else if (format == GFXFormatR8G8B8A8 || format == GFXFormatR8G8B8X8 || format == GFXFormatR8G8B8A8_LINEAR_FORCE)
  310. {
  311. comp = 4;
  312. }
  313. if (ext.equal("png"))
  314. {
  315. stbi_write_png_compression_level = compressionLevel;
  316. if (stbi_write_png(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), 0))
  317. return true;
  318. }
  319. if (ext.equal("tga"))
  320. {
  321. if (stbi_write_tga(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  322. return true;
  323. }
  324. if (ext.equal("bmp"))
  325. {
  326. if (stbi_write_bmp(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  327. return true;
  328. }
  329. if (ext.equal("jpg") || ext.equal("jpeg"))
  330. {
  331. if (stbi_write_jpg(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), compressionLevel))
  332. return true;
  333. }
  334. if (ext.equal("hdr"))
  335. {
  336. if (stbi_write_hdr(path.getFullPath().c_str(), width, height, comp, (const F32*)bitmap->getWritableBits()))
  337. return true;
  338. }
  339. return false;
  340. }
  341. bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel)
  342. {
  343. PROFILE_SCOPE(sWriteStreamSTB);
  344. S32 width = bitmap->getWidth();
  345. S32 height = bitmap->getHeight();
  346. const U8* pPixelData = bitmap->getBits();
  347. S32 channels = bitmap->getBytesPerPixel();
  348. if (bmType == String("png"))
  349. {
  350. stbi_write_png_compression_level = compressionLevel;
  351. if (stbi_write_png_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, width * channels))
  352. return true;
  353. }
  354. else if (bmType == String("tga"))
  355. {
  356. if (stbi_write_tga_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  357. return true;
  358. }
  359. else if (bmType == String("bmp"))
  360. {
  361. if (stbi_write_bmp_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  362. return true;
  363. }
  364. else if (bmType == String("jpg") || bmType == String("jpeg"))
  365. {
  366. if (stbi_write_jpg_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, compressionLevel))
  367. return true;
  368. }
  369. else if (bmType == String("hdr"))
  370. {
  371. if (stbi_write_hdr_to_func(stbiWriteFunc, &stream, width, height, channels, (const F32*)pPixelData))
  372. return true;
  373. }
  374. return false;
  375. }
  376. struct DeferredPNGWriterData
  377. {
  378. S32 width = 0;
  379. S32 height = 0;
  380. S32 channels = 0;
  381. dsize_t offset = 0;
  382. U8* pPixelData = NULL;
  383. GFXFormat format;
  384. Stream* pStream = NULL;
  385. };
  386. DeferredPNGWriter::DeferredPNGWriter() :
  387. mData(NULL),
  388. mActive(false)
  389. {
  390. mData = new DeferredPNGWriterData();
  391. }
  392. DeferredPNGWriter::~DeferredPNGWriter()
  393. {
  394. if (mData)
  395. {
  396. SAFE_DELETE_ARRAY(mData->pPixelData);
  397. }
  398. SAFE_DELETE(mData);
  399. }
  400. bool DeferredPNGWriter::begin(GFXFormat format, S32 width, S32 height, Stream& stream)
  401. {
  402. // ONLY RGB bitmap writing supported at this time!
  403. AssertFatal(format == GFXFormatR8G8B8 ||
  404. format == GFXFormatR8G8B8A8 ||
  405. format == GFXFormatR8G8B8X8 ||
  406. format == GFXFormatA8 ||
  407. format == GFXFormatR5G6B5, "DeferredPNGWriter::begin: ONLY RGB bitmap writing supported at this time.");
  408. if (format != GFXFormatR8G8B8 &&
  409. format != GFXFormatR8G8B8A8 &&
  410. format != GFXFormatR8G8B8X8 &&
  411. format != GFXFormatA8 &&
  412. format != GFXFormatR5G6B5)
  413. {
  414. return false;
  415. }
  416. mData->pStream = &stream;
  417. mData->width = width;
  418. mData->height = height;
  419. mData->format = format;
  420. const size_t dataSize = GFXFormat_getByteSize(format) * width * height;
  421. mData->pPixelData = new U8[dataSize];
  422. mActive = true;
  423. return true;
  424. }
  425. void DeferredPNGWriter::append(GBitmap* bitmap, U32 rows)
  426. {
  427. AssertFatal(mActive, "Cannot append to an inactive DeferredPNGWriter!");
  428. if (mData->channels == 0)
  429. {
  430. mData->channels = bitmap->getBytesPerPixel();
  431. }
  432. const dsize_t dataChuckSize = bitmap->getByteSize();
  433. const U8* pSrcData = bitmap->getBits();
  434. U8* pDstData = mData->pPixelData + mData->offset;
  435. dMemcpy(pDstData, pSrcData, dataChuckSize);
  436. mData->offset += dataChuckSize;
  437. }
  438. void DeferredPNGWriter::end()
  439. {
  440. AssertFatal(mActive, "Cannot end an inactive DeferredPNGWriter!");
  441. stbi_write_png_to_func(stbiWriteFunc, mData->pStream, mData->width, mData->height, mData->channels, mData->pPixelData, mData->width * mData->channels);
  442. mActive = false;
  443. }