bitmapSTB.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. #ifdef __clang__
  29. #define STBIWDEF static inline
  30. #endif
  31. #define STB_IMAGE_IMPLEMENTATION
  32. #define STB_IMAGE_STATIC
  33. #include "stb_image.h"
  34. #define STB_IMAGE_WRITE_IMPLEMENTATION
  35. #define STB_IMAGE_WRITE_STATIC
  36. #include "stb_image_write.h"
  37. static bool sReadSTB(const Torque::Path& path, GBitmap* bitmap);
  38. static bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len);
  39. static bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel);
  40. static bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel);
  41. // stbi_write callback / rextimmy.
  42. static void stbiWriteFunc(void* context, void* data, int size)
  43. {
  44. Stream* stream = static_cast<Stream*>(context);
  45. stream->write(size);
  46. stream->write(size, data);
  47. }
  48. static struct _privateRegisterSTB
  49. {
  50. _privateRegisterSTB()
  51. {
  52. GBitmap::Registration reg;
  53. reg.priority = 100;
  54. reg.extensions.push_back("png");
  55. reg.extensions.push_back("bmp");
  56. reg.extensions.push_back("jpg");
  57. reg.extensions.push_back("jpeg");
  58. reg.extensions.push_back("psd");
  59. reg.extensions.push_back("hdr");
  60. reg.extensions.push_back("tga");
  61. reg.readFunc = sReadSTB;
  62. reg.readStreamFunc = sReadStreamSTB;
  63. reg.writeFunc = sWriteSTB;
  64. reg.writeStreamFunc = sWriteStreamSTB;
  65. // for png only.
  66. reg.defaultCompression = 6;
  67. GBitmap::sRegisterFormat(reg);
  68. }
  69. } sStaticRegisterSTB;
  70. bool sReadSTB(const Torque::Path& path, GBitmap* bitmap)
  71. {
  72. PROFILE_SCOPE(sReadSTB);
  73. S32 x, y, n, channels;
  74. String ext = path.getExtension();
  75. U32 prevWaterMark = FrameAllocator::getWaterMark();
  76. if (!stbi_info(path.getFullPath().c_str(), &x, &y, &channels))
  77. {
  78. FrameAllocator::setWaterMark(prevWaterMark);
  79. return false;
  80. }
  81. // do this to map 2 channels to 4, 2 channel not supported by gbitmap yet..
  82. if (channels == 2)
  83. channels = 4;
  84. if (!ext.equal("png"))
  85. {
  86. if (stbi_is_16_bit(path.getFullPath().c_str()))
  87. {
  88. U16* data = stbi_load_16(path.getFullPath().c_str(), &x, &y, &n, channels);
  89. // if succesful deal make the bitmap, else try other loaders.
  90. if (data)
  91. {
  92. GFXFormat format;
  93. if (n == 1)
  94. format = GFXFormatL16;
  95. else
  96. format = GFXFormatR16G16B16A16; // not sure if this is correct.
  97. bitmap->deleteImage();
  98. // actually allocate the bitmap space...
  99. bitmap->allocateBitmap(x, y,
  100. false, // don't extrude miplevels...
  101. format); // use determined format...
  102. U16* pBase = (U16*)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. }
  110. }
  111. if (ext.equal("hdr"))
  112. {
  113. // force load to 4 channel.
  114. float* data = stbi_loadf(path.getFullPath().c_str(), &x, &y, &n, 4);
  115. unsigned char* dataChar = stbi__hdr_to_ldr(data, x, y, 4);
  116. bitmap->deleteImage();
  117. // actually allocate the bitmap space...
  118. bitmap->allocateBitmap(x, y,
  119. false,
  120. GFXFormatR8G8B8A8);
  121. U8* pBase = (U8*)bitmap->getBits();
  122. U32 rowBytes = x * y * 4;
  123. dMemcpy(pBase, dataChar, rowBytes);
  124. stbi_image_free(dataChar);
  125. FrameAllocator::setWaterMark(prevWaterMark);
  126. return true;
  127. }
  128. unsigned char* data = stbi_load(path.getFullPath().c_str(), &x, &y, &n, channels);
  129. bitmap->deleteImage();
  130. GFXFormat format;
  131. switch (channels) {
  132. case 1:
  133. format = GFXFormatA8;
  134. break;
  135. case 2:
  136. format = GFXFormatA8L8;
  137. break;
  138. case 3:
  139. format = GFXFormatR8G8B8;
  140. break;
  141. case 4:
  142. format = GFXFormatR8G8B8A8;
  143. break;
  144. default:
  145. FrameAllocator::setWaterMark(prevWaterMark);
  146. return false;
  147. }
  148. // actually allocate the bitmap space...
  149. bitmap->allocateBitmap(x, y,
  150. false, // don't extrude miplevels...
  151. format); // use determined format...
  152. U8* pBase = (U8*)bitmap->getBits();
  153. U32 rowBytes = bitmap->getByteSize();
  154. dMemcpy(pBase, data, rowBytes);
  155. stbi_image_free(data);
  156. // Check this bitmap for transparency
  157. if (channels == 4)
  158. bitmap->checkForTransparency();
  159. FrameAllocator::setWaterMark(prevWaterMark);
  160. return true;
  161. }
  162. bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len)
  163. {
  164. PROFILE_SCOPE(sReadStreamSTB);
  165. // only used for font at the moment.
  166. U8* data = new U8[len];
  167. stream.read(len, data);
  168. S32 width, height, comp = 0;
  169. if (stbi_info_from_memory(data, len, &width, &height, &comp))
  170. {
  171. const char* stbErr = stbi_failure_reason();
  172. if (!stbErr)
  173. stbErr = "Unknown Error!";
  174. Con::errorf("STB failed to get image info: %s", stbErr);
  175. return false;
  176. }
  177. S32 reqCom = comp;
  178. unsigned char* pixelData = stbi_load_from_memory((const U8*)data, (int)len, &width, &height, &comp, reqCom);
  179. if (!pixelData)
  180. {
  181. const char* stbErr = stbi_failure_reason();
  182. if (!stbErr)
  183. stbErr = "Unknown Error!";
  184. Con::errorf("sReadStreamSTB Error: %s", stbErr);
  185. return false;
  186. }
  187. bitmap->deleteImage();
  188. //work out what format we need to use - todo floating point?
  189. GFXFormat fmt = GFXFormat_FIRST;
  190. switch (comp)
  191. {
  192. case 1: fmt = GFXFormatA8; break;
  193. case 2: fmt = GFXFormatA8L8; break; //todo check this
  194. case 3: fmt = GFXFormatR8G8B8; break;
  195. case 4: fmt = GFXFormatR8G8B8A8; break;
  196. }
  197. bitmap->allocateBitmap(width, height, false, fmt);
  198. U8* pBase = bitmap->getWritableBits(0);
  199. U32 rowBytes = bitmap->getByteSize();
  200. dMemcpy(pBase, pixelData, rowBytes);
  201. dFree(data);
  202. dFree(pixelData);
  203. return true;
  204. }
  205. /**
  206. * Write bitmap to an image file.
  207. *
  208. * @param[in] path Destination image file path. File name extension determines image format.
  209. * ".bmp" for Microsoft Bitmap.
  210. * ".hdr" for High Dynamic Range (HDR).
  211. * ".jpg" or ".jpeg" for Joint Photographic Experts Group (JPEG).
  212. * ".png" for Portable Network Graphics (PNG).
  213. * ".tga" for Truevision TGA (TARGA).
  214. *
  215. *
  216. * @param[in] bitmap Source bitmap to encode image from.
  217. * @param compressionLevel Image format specific compression level.
  218. * For JPEG sets the quality level percentage, range 0 to 100.
  219. * Not used for other image formats.
  220. */
  221. bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel)
  222. {
  223. PROFILE_SCOPE(sWriteSTB);
  224. // get our data to be saved.
  225. U32 width = bitmap->getWidth();
  226. U32 height = bitmap->getHeight();
  227. U32 bytes = bitmap->getBytesPerPixel();
  228. GFXFormat format = bitmap->getFormat();
  229. String ext = path.getExtension();
  230. U32 stride = width * bytes;
  231. // we always have at least 1
  232. U32 comp = 1;
  233. if (format == GFXFormatR8G8B8)
  234. {
  235. comp = 3;
  236. }
  237. else if (format == GFXFormatR8G8B8A8 || format == GFXFormatR8G8B8X8 || format == GFXFormatR8G8B8A8_LINEAR_FORCE)
  238. {
  239. comp = 4;
  240. }
  241. if (ext.equal("png"))
  242. {
  243. stbi_write_png_compression_level = compressionLevel;
  244. if (stbi_write_png(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), 0))
  245. return true;
  246. }
  247. if (ext.equal("tga"))
  248. {
  249. if (stbi_write_tga(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  250. return true;
  251. }
  252. if (ext.equal("bmp"))
  253. {
  254. if (stbi_write_bmp(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  255. return true;
  256. }
  257. if (ext.equal("jpg") || ext.equal("jpeg"))
  258. {
  259. if (stbi_write_jpg(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), compressionLevel))
  260. return true;
  261. }
  262. if (ext.equal("hdr"))
  263. {
  264. if (stbi_write_hdr(path.getFullPath().c_str(), width, height, comp, (const F32*)bitmap->getWritableBits()))
  265. return true;
  266. }
  267. return false;
  268. }
  269. bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel)
  270. {
  271. PROFILE_SCOPE(sWriteStreamSTB);
  272. S32 width = bitmap->getWidth();
  273. S32 height = bitmap->getHeight();
  274. const U8* pPixelData = bitmap->getBits();
  275. S32 channels = bitmap->getBytesPerPixel();
  276. if (bmType == String("png"))
  277. {
  278. stbi_write_png_compression_level = compressionLevel;
  279. if (stbi_write_png_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, width * channels))
  280. return true;
  281. }
  282. else if (bmType == String("tga"))
  283. {
  284. if (stbi_write_tga_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  285. return true;
  286. }
  287. else if (bmType == String("bmp"))
  288. {
  289. if (stbi_write_bmp_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  290. return true;
  291. }
  292. else if (bmType == String("jpg") || bmType == String("jpeg"))
  293. {
  294. if (stbi_write_jpg_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, compressionLevel))
  295. return true;
  296. }
  297. else if (bmType == String("hdr"))
  298. {
  299. if (stbi_write_hdr_to_func(stbiWriteFunc, &stream, width, height, channels, (const F32*)pPixelData))
  300. return true;
  301. }
  302. return false;
  303. }