bitmapSTB.cpp 16 KB

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