]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - image_png.c
427dfd2db706fbcfa48fda7b68892e243714bd51
[xonotic/darkplaces.git] / image_png.c
1 /*
2         Copyright (C) 2006  Serge "(515)" Ziryukin, Forest "LordHavoc" Hale
3
4         This program is free software; you can redistribute it and/or
5         modify it under the terms of the GNU General Public License
6         as published by the Free Software Foundation; either version 2
7         of the License, or (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24 //[515]: png implemented into DP ONLY FOR TESTING 2d stuff with csqc
25 // so delete this bullshit :D
26 //
27 //LordHavoc: rewrote most of this.
28
29 #include "quakedef.h"
30 #include "image.h"
31 #include "image_png.h"
32
33 #ifdef __cplusplus
34 #ifdef WIN64
35 typedef _JBTYPE *qpng_jmpbuf_t;
36 #elif defined(MACOSX) || defined(WIN32)
37 typedef int *qpng_jmpbuf_t;
38 #else
39 typedef __jmp_buf_tag *qpng_jmpbuf_t;
40 #endif
41 #else
42 typedef void *qpng_jmpbuf_t;
43 #endif
44 // why not: typedef jmp_buf qpng_jmpbuf_t;
45
46 static void                             (*qpng_set_sig_bytes)           (void*, int);
47 static int                              (*qpng_sig_cmp)                         (const unsigned char*, size_t, size_t);
48 static void*                    (*qpng_create_read_struct)      (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
49 static void*                    (*qpng_create_write_struct)     (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
50 static void*                    (*qpng_create_info_struct)      (void*);
51 static void                             (*qpng_read_info)                       (void*, void*);
52 static void                             (*qpng_set_compression_level)   (void*, int);
53 static void                             (*qpng_set_filter)                      (void*, int, int);
54 static void                             (*qpng_set_expand)                      (void*);
55 static void                             (*qpng_set_palette_to_rgb)      (void*);
56 static void                             (*qpng_set_tRNS_to_alpha)       (void*);
57 static void                             (*qpng_set_gray_to_rgb)         (void*);
58 static void                             (*qpng_set_filler)                      (void*, unsigned int, int);
59 static void                             (*qpng_set_IHDR)                        (void*, void*, unsigned long, unsigned long, int, int, int, int, int);
60 static void                             (*qpng_set_packing)                     (void*);
61 static void                             (*qpng_set_bgr)                         (void*);
62 static int                              (*qpng_set_interlace_handling)  (void*);
63 static void                             (*qpng_read_update_info)        (void*, void*);
64 static void                             (*qpng_read_image)                      (void*, unsigned char**);
65 static void                             (*qpng_read_end)                        (void*, void*);
66 static void                             (*qpng_destroy_read_struct)     (void**, void**, void**);
67 static void                             (*qpng_destroy_write_struct)    (void**, void**);
68 static void                             (*qpng_set_read_fn)                     (void*, void*, void(*)(void *png, unsigned char *data, size_t length));
69 static void                             (*qpng_set_write_fn)            (void*, void*, void(*)(void *png, unsigned char *data, size_t length), void(*)(void *png));
70 static unsigned int             (*qpng_get_valid)                       (void*, void*, unsigned int);
71 static unsigned int             (*qpng_get_rowbytes)            (void*, void*);
72 static unsigned char    (*qpng_get_channels)            (void*, void*);
73 static unsigned char    (*qpng_get_bit_depth)           (void*, void*);
74 static unsigned int             (*qpng_get_IHDR)                        (void*, void*, unsigned long*, unsigned long*, int *, int *, int *, int *, int *);
75 static unsigned int                     (*qpng_access_version_number)           (void); // FIXME is this return type right? It is a png_uint_32 in libpng
76 static void                             (*qpng_write_info)                      (void*, void*);
77 static void                             (*qpng_write_row)                       (void*, unsigned char*);
78 static void                             (*qpng_write_end)                       (void*, void*);
79 static qpng_jmpbuf_t                    (*qpng_jmpbuf)          (void*);
80
81 static dllfunction_t pngfuncs[] =
82 {
83         {"png_set_sig_bytes",           (void **) &qpng_set_sig_bytes},
84         {"png_sig_cmp",                         (void **) &qpng_sig_cmp},
85         {"png_create_read_struct",      (void **) &qpng_create_read_struct},
86         {"png_create_write_struct",     (void **) &qpng_create_write_struct},
87         {"png_create_info_struct",      (void **) &qpng_create_info_struct},
88         {"png_read_info",                       (void **) &qpng_read_info},
89         {"png_set_compression_level",   (void **) &qpng_set_compression_level},
90         {"png_set_filter",                      (void **) &qpng_set_filter},
91         {"png_set_expand",                      (void **) &qpng_set_expand},
92         {"png_set_palette_to_rgb",      (void **) &qpng_set_palette_to_rgb},
93         {"png_set_tRNS_to_alpha",       (void **) &qpng_set_tRNS_to_alpha},
94         {"png_set_gray_to_rgb",         (void **) &qpng_set_gray_to_rgb},
95         {"png_set_filler",                      (void **) &qpng_set_filler},
96         {"png_set_IHDR",                        (void **) &qpng_set_IHDR},
97         {"png_set_packing",                     (void **) &qpng_set_packing},
98         {"png_set_bgr",                         (void **) &qpng_set_bgr},
99         {"png_set_interlace_handling",  (void **) &qpng_set_interlace_handling},
100         {"png_read_update_info",        (void **) &qpng_read_update_info},
101         {"png_read_image",                      (void **) &qpng_read_image},
102         {"png_read_end",                        (void **) &qpng_read_end},
103         {"png_destroy_read_struct",     (void **) &qpng_destroy_read_struct},
104         {"png_destroy_write_struct",    (void **) &qpng_destroy_write_struct},
105         {"png_set_read_fn",                     (void **) &qpng_set_read_fn},
106         {"png_set_write_fn",            (void **) &qpng_set_write_fn},
107         {"png_get_valid",                       (void **) &qpng_get_valid},
108         {"png_get_rowbytes",            (void **) &qpng_get_rowbytes},
109         {"png_get_channels",            (void **) &qpng_get_channels},
110         {"png_get_bit_depth",           (void **) &qpng_get_bit_depth},
111         {"png_get_IHDR",                        (void **) &qpng_get_IHDR},
112         {"png_access_version_number",           (void **) &qpng_access_version_number},
113         {"png_write_info",                      (void **) &qpng_write_info},
114         {"png_write_row",                       (void **) &qpng_write_row},
115         {"png_write_end",                       (void **) &qpng_write_end},
116         {"png_jmpbuf",          (void **) &qpng_jmpbuf},
117         {NULL, NULL}
118 };
119
120 // Handle for PNG DLL
121 dllhandle_t png_dll = NULL;
122
123
124 /*
125 =================================================================
126
127   DLL load & unload
128
129 =================================================================
130 */
131
132 /*
133 ====================
134 PNG_OpenLibrary
135
136 Try to load the PNG DLL
137 ====================
138 */
139 qboolean PNG_OpenLibrary (void)
140 {
141         const char* dllnames [] =
142         {
143 #if WIN32
144                 "libpng15-15.dll",
145                 "libpng15.dll",
146                 "libpng14-14.dll",
147                 "libpng14.dll",
148                 "libpng12.dll",
149 #elif defined(MACOSX)
150                 "libpng15.15.dylib",
151                 "libpng14.14.dylib",
152                 "libpng12.0.dylib",
153 #else
154                 "libpng15.so.15", // WTF libtool guidelines anyone?
155                 "libpng14.so.14", // WTF libtool guidelines anyone?
156                 "libpng12.so.0",
157                 "libpng.so", // FreeBSD
158 #endif
159                 NULL
160         };
161
162         // Already loaded?
163         if (png_dll)
164                 return true;
165
166         // Load the DLL
167         return Sys_LoadLibrary (dllnames, &png_dll, pngfuncs);
168 }
169
170
171 /*
172 ====================
173 PNG_CloseLibrary
174
175 Unload the PNG DLL
176 ====================
177 */
178 void PNG_CloseLibrary (void)
179 {
180         Sys_UnloadLibrary (&png_dll);
181 }
182
183 /*
184 =================================================================
185
186         PNG decompression
187
188 =================================================================
189 */
190
191 #define PNG_LIBPNG_VER_STRING_12 "1.2.4"
192 #define PNG_LIBPNG_VER_STRING_14 "1.4.0"
193 #define PNG_LIBPNG_VER_STRING_15 "1.5.0"
194
195 #define PNG_COLOR_MASK_PALETTE    1
196 #define PNG_COLOR_MASK_COLOR      2
197 #define PNG_COLOR_MASK_ALPHA      4
198
199 #define PNG_COLOR_TYPE_GRAY 0
200 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
201 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
202 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
203 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
204
205 #define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
206 #define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
207
208 #define PNG_INFO_tRNS 0x0010
209
210 // this struct is only used for status information during loading
211 static struct
212 {
213         const unsigned char     *tmpBuf;
214         int             tmpBuflength;
215         int             tmpi;
216         //int           FBgColor;
217         //int           FTransparent;
218         unsigned int    FRowBytes;
219         //double        FGamma;
220         //double        FScreenGamma;
221         unsigned char   **FRowPtrs;
222         unsigned char   *Data;
223         //char  *Title;
224         //char  *Author;
225         //char  *Description;
226         int             BitDepth;
227         int             BytesPerPixel;
228         int             ColorType;
229         unsigned long   Height; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
230         unsigned long   Width; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
231         int             Interlace;
232         int             Compression;
233         int             Filter;
234         //double        LastModified;
235         //int           Transparent;
236         qfile_t *outfile;
237 } my_png;
238
239 //LordHavoc: removed __cdecl prefix, added overrun protection, and rewrote this to be more efficient
240 static void PNG_fReadData(void *png, unsigned char *data, size_t length)
241 {
242         size_t l;
243         l = my_png.tmpBuflength - my_png.tmpi;
244         if (l < length)
245         {
246                 Con_Printf("PNG_fReadData: overrun by %i bytes\n", (int)(length - l));
247                 // a read going past the end of the file, fill in the remaining bytes
248                 // with 0 just to be consistent
249                 memset(data + l, 0, length - l);
250                 length = l;
251         }
252         memcpy(data, my_png.tmpBuf + my_png.tmpi, length);
253         my_png.tmpi += (int)length;
254         //Com_HexDumpToConsole(data, (int)length);
255 }
256
257 static void PNG_fWriteData(void *png, unsigned char *data, size_t length)
258 {
259         FS_Write(my_png.outfile, data, length);
260 }
261
262 static void PNG_fFlushData(void *png)
263 {
264 }
265
266 static void PNG_error_fn(void *png, const char *message)
267 {
268         Con_Printf("PNG_LoadImage: error: %s\n", message);
269 }
270
271 static void PNG_warning_fn(void *png, const char *message)
272 {
273         Con_Printf("PNG_LoadImage: warning: %s\n", message);
274 }
275
276 extern int      image_width;
277 extern int      image_height;
278
279 unsigned char *PNG_LoadImage_BGRA (const unsigned char *raw, int filesize, int *miplevel)
280 {
281         unsigned int c;
282         unsigned int    y;
283         void *png, *pnginfo;
284         unsigned char *imagedata = NULL;
285         unsigned char ioBuffer[8192];
286
287         // FIXME: register an error handler so that abort() won't be called on error
288
289         // No DLL = no PNGs
290         if (!png_dll)
291                 return NULL;
292
293         if(qpng_sig_cmp(raw, 0, filesize))
294                 return NULL;
295         png = (void *)qpng_create_read_struct(
296                 (qpng_access_version_number() / 100 == 102) ? PNG_LIBPNG_VER_STRING_12 :
297                 (qpng_access_version_number() / 100 == 104) ? PNG_LIBPNG_VER_STRING_14 :
298                 PNG_LIBPNG_VER_STRING_15, // nasty hack... whatever
299                 0, PNG_error_fn, PNG_warning_fn
300         );
301         if(!png)
302                 return NULL;
303
304         // this must be memset before the setjmp error handler, because it relies
305         // on the fields in this struct for cleanup
306         memset(&my_png, 0, sizeof(my_png));
307
308         // NOTE: this relies on jmp_buf being the first thing in the png structure
309         // created by libpng! (this is correct for libpng 1.2.x)
310         if (setjmp(qpng_jmpbuf(png)))
311         {
312                 if (my_png.Data)
313                         Mem_Free(my_png.Data);
314                 my_png.Data = NULL;
315                 if (my_png.FRowPtrs)
316                         Mem_Free(my_png.FRowPtrs);
317                 my_png.FRowPtrs = NULL;
318                 qpng_destroy_read_struct(&png, &pnginfo, 0);
319                 return NULL;
320         }
321         //
322
323         pnginfo = qpng_create_info_struct(png);
324         if(!pnginfo)
325         {
326                 qpng_destroy_read_struct(&png, &pnginfo, 0);
327                 return NULL;
328         }
329         qpng_set_sig_bytes(png, 0);
330
331         my_png.tmpBuf = raw;
332         my_png.tmpBuflength = filesize;
333         my_png.tmpi = 0;
334         //my_png.Data           = NULL;
335         //my_png.FRowPtrs       = NULL;
336         //my_png.Height         = 0;
337         //my_png.Width          = 0;
338         my_png.ColorType        = PNG_COLOR_TYPE_RGB;
339         //my_png.Interlace      = 0;
340         //my_png.Compression    = 0;
341         //my_png.Filter         = 0;
342         qpng_set_read_fn(png, ioBuffer, PNG_fReadData);
343         qpng_read_info(png, pnginfo);
344         qpng_get_IHDR(png, pnginfo, &my_png.Width, &my_png.Height,&my_png.BitDepth, &my_png.ColorType, &my_png.Interlace, &my_png.Compression, &my_png.Filter);
345
346         // this check guards against pngconf.h with unsigned int *width/height parameters on big endian systems by detecting the strange values and shifting them down 32bits
347         // (if it's little endian the unwritten bytes are the most significant
348         //  ones and we don't worry about that)
349         //
350         // this is only necessary because of retarded 64bit png_uint_32 types in libpng 1.2, which can (conceivably) vary by platform
351 #if LONG_MAX > 4000000000
352         if (my_png.Width > LONG_MAX || my_png.Height > LONG_MAX)
353         {
354                 my_png.Width >>= 32;
355                 my_png.Height >>= 32;
356         }
357 #endif
358
359         if (my_png.ColorType == PNG_COLOR_TYPE_PALETTE)
360                 qpng_set_palette_to_rgb(png);
361         if (my_png.ColorType == PNG_COLOR_TYPE_GRAY || my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
362                 qpng_set_gray_to_rgb(png);
363         if (qpng_get_valid(png, pnginfo, PNG_INFO_tRNS))
364                 qpng_set_tRNS_to_alpha(png);
365         if (my_png.BitDepth == 8 && !(my_png.ColorType  & PNG_COLOR_MASK_ALPHA))
366                 qpng_set_filler(png, 255, 1);
367         if (( my_png.ColorType == PNG_COLOR_TYPE_GRAY) || (my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA ))
368                 qpng_set_gray_to_rgb(png);
369         if (my_png.BitDepth < 8)
370                 qpng_set_expand(png);
371
372         qpng_read_update_info(png, pnginfo);
373
374         my_png.FRowBytes = qpng_get_rowbytes(png, pnginfo);
375         my_png.BytesPerPixel = qpng_get_channels(png, pnginfo);
376
377         my_png.FRowPtrs = (unsigned char **)Mem_Alloc(tempmempool, my_png.Height * sizeof(*my_png.FRowPtrs));
378         if (my_png.FRowPtrs)
379         {
380                 imagedata = (unsigned char *)Mem_Alloc(tempmempool, my_png.Height * my_png.FRowBytes);
381                 if(imagedata)
382                 {
383                         my_png.Data = imagedata;
384                         for(y = 0;y < my_png.Height;y++)
385                                 my_png.FRowPtrs[y] = my_png.Data + y * my_png.FRowBytes;
386                         qpng_read_image(png, my_png.FRowPtrs);
387                 }
388                 else
389                 {
390                         Con_Printf("PNG_LoadImage : not enough memory\n");
391                         qpng_destroy_read_struct(&png, &pnginfo, 0);
392                         Mem_Free(my_png.FRowPtrs);
393                         return NULL;
394                 }
395                 Mem_Free(my_png.FRowPtrs);
396                 my_png.FRowPtrs = NULL;
397         }
398         else
399         {
400                 Con_Printf("PNG_LoadImage : not enough memory\n");
401                 qpng_destroy_read_struct(&png, &pnginfo, 0);
402                 return NULL;
403         }
404
405         qpng_read_end(png, pnginfo);
406         qpng_destroy_read_struct(&png, &pnginfo, 0);
407
408         image_width = (int)my_png.Width;
409         image_height = (int)my_png.Height;
410
411         if (my_png.BitDepth != 8)
412         {
413                 Con_Printf ("PNG_LoadImage : bad color depth\n");
414                 Mem_Free(imagedata);
415                 return NULL;
416         }
417
418         // swizzle RGBA to BGRA
419         for (y = 0;y < (unsigned int)(image_width*image_height*4);y += 4)
420         {
421                 c = imagedata[y+0];
422                 imagedata[y+0] = imagedata[y+2];
423                 imagedata[y+2] = c;
424         }
425
426         return imagedata;
427 }
428
429 /*
430 =================================================================
431
432         PNG compression
433
434 =================================================================
435 */
436
437 #define Z_BEST_SPEED 1
438 #define Z_BEST_COMPRESSION 9
439 #define PNG_INTERLACE_NONE 0
440 #define PNG_INTERLACE_ADAM7 1
441 #define PNG_FILTER_TYPE_BASE 0
442 #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
443 #define PNG_COMPRESSION_TYPE_BASE 0
444 #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
445 #define PNG_NO_FILTERS     0x00
446 #define PNG_FILTER_NONE    0x08
447 #define PNG_FILTER_SUB     0x10
448 #define PNG_FILTER_UP      0x20
449 #define PNG_FILTER_AVG     0x40
450 #define PNG_FILTER_PAETH   0x80
451 #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
452                          PNG_FILTER_AVG | PNG_FILTER_PAETH)
453
454 /*
455 ====================
456 PNG_SaveImage_preflipped
457
458 Save a preflipped PNG image to a file
459 ====================
460 */
461 qboolean PNG_SaveImage_preflipped (const char *filename, int width, int height, qboolean has_alpha, unsigned char *data)
462 {
463         unsigned int offset, linesize;
464         qfile_t* file = NULL;
465         void *png, *pnginfo;
466         unsigned char ioBuffer[8192];
467         int passes, i, j;
468
469         // No DLL = no JPEGs
470         if (!png_dll)
471         {
472                 Con_Print("You need the libpng library to save PNG images\n");
473                 return false;
474         }
475
476         png = (void *)qpng_create_write_struct( 
477                 (qpng_access_version_number() / 100 == 102) ? PNG_LIBPNG_VER_STRING_12 : PNG_LIBPNG_VER_STRING_14, // nasty hack to support both libpng12 and libpng14
478                 0, PNG_error_fn, PNG_warning_fn
479         );
480         if(!png)
481                 return false;
482         pnginfo = (void *)qpng_create_info_struct(png);
483         if(!pnginfo)
484         {
485                  qpng_destroy_write_struct(&png, NULL);
486                  return false;
487         }
488
489         // this must be memset before the setjmp error handler, because it relies
490         // on the fields in this struct for cleanup
491         memset(&my_png, 0, sizeof(my_png));
492
493         // NOTE: this relies on jmp_buf being the first thing in the png structure
494         // created by libpng! (this is correct for libpng 1.2.x)
495 #ifdef __cplusplus
496 #ifdef WIN64
497         if (setjmp((_JBTYPE *)png))
498 #elif defined(MACOSX) || defined(WIN32)
499         if (setjmp((int *)png))
500 #else
501         if (setjmp((__jmp_buf_tag *)png))
502 #endif
503 #else
504         if (setjmp(png))
505 #endif
506         {
507                 qpng_destroy_write_struct(&png, &pnginfo);
508                 return false;
509         }
510
511         // Open the file
512         file = FS_OpenRealFile(filename, "wb", true);
513         if (!file)
514                 return false;
515         my_png.outfile = file;
516         qpng_set_write_fn(png, ioBuffer, PNG_fWriteData, PNG_fFlushData);
517
518         //qpng_set_compression_level(png, Z_BEST_COMPRESSION);
519         qpng_set_compression_level(png, Z_BEST_SPEED);
520         qpng_set_IHDR(png, pnginfo, width, height, 8, has_alpha ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB, PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
521         qpng_set_filter(png, 0, PNG_NO_FILTERS);
522         qpng_write_info(png, pnginfo);
523         qpng_set_packing(png);
524         qpng_set_bgr(png);
525
526         passes = qpng_set_interlace_handling(png);
527
528         linesize = width * (has_alpha ? 4 : 3);
529         offset = linesize * (height - 1);
530         for(i = 0; i < passes; ++i)
531                 for(j = 0; j < height; ++j)
532                         qpng_write_row(png, &data[offset - j * linesize]);
533
534         qpng_write_end(png, NULL);
535         qpng_destroy_write_struct(&png, &pnginfo);
536
537         FS_Close (file);
538
539         return true;
540 }