image_loader_png.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*************************************************************************/
  2. /* image_loader_png.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "image_loader_png.h"
  31. #include "os/os.h"
  32. #include "print_string.h"
  33. #include <string.h>
  34. void ImageLoaderPNG::_read_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  35. FileAccess *f = (FileAccess *)png_get_io_ptr(png_ptr);
  36. f->get_buffer((uint8_t *)data, p_length);
  37. }
  38. /*
  39. png_structp png_ptr = png_create_read_struct_2
  40. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  41. user_error_fn, user_warning_fn, (png_voidp)
  42. user_mem_ptr, user_malloc_fn, user_free_fn);
  43. */
  44. static png_voidp _png_malloc_fn(png_structp png_ptr, png_size_t size) {
  45. return memalloc(size);
  46. }
  47. static void _png_free_fn(png_structp png_ptr, png_voidp ptr) {
  48. memfree(ptr);
  49. }
  50. static void _png_error_function(png_structp, png_const_charp text) {
  51. ERR_PRINT(text);
  52. }
  53. static void _png_warn_function(png_structp, png_const_charp text) {
  54. WARN_PRINT(text);
  55. }
  56. typedef void(PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  57. Error ImageLoaderPNG::_load_image(void *rf_up, png_rw_ptr p_func, Ref<Image> p_image) {
  58. png_structp png;
  59. png_infop info;
  60. //png = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
  61. png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, _png_error_function, _png_warn_function, (png_voidp)NULL,
  62. _png_malloc_fn, _png_free_fn);
  63. ERR_FAIL_COND_V(!png, ERR_OUT_OF_MEMORY);
  64. info = png_create_info_struct(png);
  65. if (!info) {
  66. png_destroy_read_struct(&png, NULL, NULL);
  67. ERR_PRINT("Out of Memory");
  68. return ERR_OUT_OF_MEMORY;
  69. }
  70. if (setjmp(png_jmpbuf(png))) {
  71. png_destroy_read_struct(&png, NULL, NULL);
  72. ERR_PRINT("PNG Corrupted");
  73. return ERR_FILE_CORRUPT;
  74. }
  75. png_set_read_fn(png, (void *)rf_up, p_func);
  76. png_uint_32 width, height;
  77. int depth, color;
  78. png_read_info(png, info);
  79. png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
  80. //https://svn.gov.pt/projects/ccidadao/repository/middleware-offline/trunk/_src/eidmw/FreeImagePTEiD/Source/FreeImage/PluginPNG.cpp
  81. //png_get_text(png,info,)
  82. /*
  83. printf("Image width:%i\n", width);
  84. printf("Image Height:%i\n", height);
  85. printf("Bit depth:%i\n", depth);
  86. printf("Color type:%i\n", color);
  87. */
  88. bool update_info = false;
  89. if (depth < 8) { //only bit dept 8 per channel is handled
  90. png_set_packing(png);
  91. update_info = true;
  92. };
  93. if (png_get_color_type(png, info) == PNG_COLOR_TYPE_PALETTE) {
  94. png_set_palette_to_rgb(png);
  95. update_info = true;
  96. }
  97. if (depth > 8) {
  98. png_set_strip_16(png);
  99. update_info = true;
  100. }
  101. if (png_get_valid(png, info, PNG_INFO_tRNS)) {
  102. //png_set_expand_gray_1_2_4_to_8(png);
  103. png_set_tRNS_to_alpha(png);
  104. update_info = true;
  105. }
  106. if (update_info) {
  107. png_read_update_info(png, info);
  108. png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
  109. }
  110. int components = 0;
  111. Image::Format fmt;
  112. switch (color) {
  113. case PNG_COLOR_TYPE_GRAY: {
  114. fmt = Image::FORMAT_L8;
  115. components = 1;
  116. } break;
  117. case PNG_COLOR_TYPE_GRAY_ALPHA: {
  118. fmt = Image::FORMAT_LA8;
  119. components = 2;
  120. } break;
  121. case PNG_COLOR_TYPE_RGB: {
  122. fmt = Image::FORMAT_RGB8;
  123. components = 3;
  124. } break;
  125. case PNG_COLOR_TYPE_RGB_ALPHA: {
  126. fmt = Image::FORMAT_RGBA8;
  127. components = 4;
  128. } break;
  129. default: {
  130. ERR_PRINT("INVALID PNG TYPE");
  131. png_destroy_read_struct(&png, &info, NULL);
  132. return ERR_UNAVAILABLE;
  133. } break;
  134. }
  135. //int rowsize = png_get_rowbytes(png, info);
  136. int rowsize = components * width;
  137. PoolVector<uint8_t> dstbuff;
  138. dstbuff.resize(rowsize * height);
  139. PoolVector<uint8_t>::Write dstbuff_write = dstbuff.write();
  140. uint8_t *data = dstbuff_write.ptr();
  141. uint8_t **row_p = memnew_arr(uint8_t *, height);
  142. for (unsigned int i = 0; i < height; i++) {
  143. row_p[i] = &data[components * width * i];
  144. }
  145. png_read_image(png, (png_bytep *)row_p);
  146. memdelete_arr(row_p);
  147. p_image->create(width, height, 0, fmt, dstbuff);
  148. png_destroy_read_struct(&png, &info, NULL);
  149. return OK;
  150. }
  151. Error ImageLoaderPNG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
  152. Error err = _load_image(f, _read_png_data, p_image);
  153. f->close();
  154. return err;
  155. }
  156. void ImageLoaderPNG::get_recognized_extensions(List<String> *p_extensions) const {
  157. p_extensions->push_back("png");
  158. }
  159. struct PNGReadStatus {
  160. uint32_t offset;
  161. uint32_t size;
  162. const unsigned char *image;
  163. };
  164. static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  165. PNGReadStatus *rstatus;
  166. rstatus = (PNGReadStatus *)png_get_io_ptr(png_ptr);
  167. png_size_t to_read = p_length;
  168. if (rstatus->size >= 0) {
  169. to_read = MIN(p_length, rstatus->size - rstatus->offset);
  170. }
  171. memcpy(data, &rstatus->image[rstatus->offset], to_read);
  172. rstatus->offset += to_read;
  173. if (to_read < p_length) {
  174. memset(&data[to_read], 0, p_length - to_read);
  175. }
  176. }
  177. static Ref<Image> _load_mem_png(const uint8_t *p_png, int p_size) {
  178. PNGReadStatus prs;
  179. prs.image = p_png;
  180. prs.offset = 0;
  181. prs.size = p_size;
  182. Ref<Image> img;
  183. img.instance();
  184. Error err = ImageLoaderPNG::_load_image(&prs, user_read_data, img);
  185. ERR_FAIL_COND_V(err, Ref<Image>());
  186. return img;
  187. }
  188. static Ref<Image> _lossless_unpack_png(const PoolVector<uint8_t> &p_data) {
  189. int len = p_data.size();
  190. ERR_FAIL_COND_V(len < 4, Ref<Image>());
  191. PoolVector<uint8_t>::Read r = p_data.read();
  192. ERR_FAIL_COND_V(r[0] != 'P' || r[1] != 'N' || r[2] != 'G' || r[3] != ' ', Ref<Image>());
  193. return _load_mem_png(&r[4], len - 4);
  194. }
  195. static void _write_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  196. PoolVector<uint8_t> &v = *(PoolVector<uint8_t> *)png_get_io_ptr(png_ptr);
  197. int vs = v.size();
  198. v.resize(vs + p_length);
  199. PoolVector<uint8_t>::Write w = v.write();
  200. copymem(&w[vs], data, p_length);
  201. //print_line("png write: "+itos(p_length));
  202. }
  203. static PoolVector<uint8_t> _lossless_pack_png(const Ref<Image> &p_image) {
  204. Ref<Image> img = p_image->duplicate();
  205. if (img->is_compressed())
  206. img->decompress();
  207. ERR_FAIL_COND_V(img->is_compressed(), PoolVector<uint8_t>());
  208. png_structp png_ptr;
  209. png_infop info_ptr;
  210. png_bytep *row_pointers;
  211. /* initialize stuff */
  212. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  213. ERR_FAIL_COND_V(!png_ptr, PoolVector<uint8_t>());
  214. info_ptr = png_create_info_struct(png_ptr);
  215. ERR_FAIL_COND_V(!info_ptr, PoolVector<uint8_t>());
  216. if (setjmp(png_jmpbuf(png_ptr))) {
  217. ERR_FAIL_V(PoolVector<uint8_t>());
  218. }
  219. PoolVector<uint8_t> ret;
  220. ret.push_back('P');
  221. ret.push_back('N');
  222. ret.push_back('G');
  223. ret.push_back(' ');
  224. png_set_write_fn(png_ptr, &ret, _write_png_data, NULL);
  225. /* write header */
  226. if (setjmp(png_jmpbuf(png_ptr))) {
  227. ERR_FAIL_V(PoolVector<uint8_t>());
  228. }
  229. int pngf = 0;
  230. int cs = 0;
  231. switch (img->get_format()) {
  232. case Image::FORMAT_L8: {
  233. pngf = PNG_COLOR_TYPE_GRAY;
  234. cs = 1;
  235. } break;
  236. case Image::FORMAT_LA8: {
  237. pngf = PNG_COLOR_TYPE_GRAY_ALPHA;
  238. cs = 2;
  239. } break;
  240. case Image::FORMAT_RGB8: {
  241. pngf = PNG_COLOR_TYPE_RGB;
  242. cs = 3;
  243. } break;
  244. case Image::FORMAT_RGBA8: {
  245. pngf = PNG_COLOR_TYPE_RGB_ALPHA;
  246. cs = 4;
  247. } break;
  248. default: {
  249. if (img->detect_alpha()) {
  250. img->convert(Image::FORMAT_RGBA8);
  251. pngf = PNG_COLOR_TYPE_RGB_ALPHA;
  252. cs = 4;
  253. } else {
  254. img->convert(Image::FORMAT_RGB8);
  255. pngf = PNG_COLOR_TYPE_RGB;
  256. cs = 3;
  257. }
  258. }
  259. }
  260. int w = img->get_width();
  261. int h = img->get_height();
  262. png_set_IHDR(png_ptr, info_ptr, w, h,
  263. 8, pngf, PNG_INTERLACE_NONE,
  264. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  265. png_write_info(png_ptr, info_ptr);
  266. /* write bytes */
  267. if (setjmp(png_jmpbuf(png_ptr))) {
  268. ERR_FAIL_V(PoolVector<uint8_t>());
  269. }
  270. PoolVector<uint8_t>::Read r = img->get_data().read();
  271. row_pointers = (png_bytep *)memalloc(sizeof(png_bytep) * h);
  272. for (int i = 0; i < h; i++) {
  273. row_pointers[i] = (png_bytep)&r[i * w * cs];
  274. }
  275. png_write_image(png_ptr, row_pointers);
  276. memfree(row_pointers);
  277. /* end write */
  278. if (setjmp(png_jmpbuf(png_ptr))) {
  279. ERR_FAIL_V(PoolVector<uint8_t>());
  280. }
  281. png_write_end(png_ptr, NULL);
  282. return ret;
  283. }
  284. ImageLoaderPNG::ImageLoaderPNG() {
  285. Image::_png_mem_loader_func = _load_mem_png;
  286. Image::lossless_unpacker = _lossless_unpack_png;
  287. Image::lossless_packer = _lossless_pack_png;
  288. }