]> icculus.org git repositories - divverent/darkplaces.git/blob - image_png.c
new cvar: scr_screenshot_png (and obvious PNG screenshotting code to support it)
[divverent/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 static void                             (*qpng_set_sig_bytes)           (void*, int);
34 static int                              (*qpng_sig_cmp)                         (const unsigned char*, size_t, size_t);
35 static void*                    (*qpng_create_read_struct)      (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
36 static void*                    (*qpng_create_write_struct)     (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
37 static void*                    (*qpng_create_info_struct)      (void*);
38 static void                             (*qpng_read_info)                       (void*, void*);
39 static void                             (*qpng_set_compression_level)   (void*, int);
40 static void                             (*qpng_set_expand)                      (void*);
41 static void                             (*qpng_set_gray_1_2_4_to_8)     (void*);
42 static void                             (*qpng_set_palette_to_rgb)      (void*);
43 static void                             (*qpng_set_tRNS_to_alpha)       (void*);
44 static void                             (*qpng_set_gray_to_rgb)         (void*);
45 static void                             (*qpng_set_filler)                      (void*, unsigned int, int);
46 static void                             (*qpng_set_IHDR)                        (void*, void*, unsigned long, unsigned long, int, int, int, int, int);
47 static void                             (*qpng_set_packing)                     (void*);
48 static void                             (*qpng_set_bgr)                         (void*);
49 static int                              (*qpng_set_interlace_handling)  (void*);
50 static void                             (*qpng_read_update_info)        (void*, void*);
51 static void                             (*qpng_read_image)                      (void*, unsigned char**);
52 static void                             (*qpng_read_end)                        (void*, void*);
53 static void                             (*qpng_destroy_read_struct)     (void**, void**, void**);
54 static void                             (*qpng_destroy_write_struct)    (void**, void**);
55 static void                             (*qpng_set_read_fn)                     (void*, void*, void(*)(void *png, unsigned char *data, size_t length));
56 static void                             (*qpng_set_write_fn)            (void*, void*, void(*)(void *png, unsigned char *data, size_t length), void(*)(void *png));
57 static unsigned int             (*qpng_get_valid)                       (void*, void*, unsigned int);
58 static unsigned int             (*qpng_get_rowbytes)            (void*, void*);
59 static unsigned char    (*qpng_get_channels)            (void*, void*);
60 static unsigned char    (*qpng_get_bit_depth)           (void*, void*);
61 static unsigned int             (*qpng_get_IHDR)                        (void*, void*, unsigned long*, unsigned long*, int *, int *, int *, int *, int *);
62 static char*                    (*qpng_get_libpng_ver)          (void*);
63 static void                             (*qpng_write_info)                      (void*, void*);
64 static void                             (*qpng_write_row)                       (void*, unsigned char*);
65 static void                             (*qpng_write_end)                       (void*, void*);
66
67 static dllfunction_t pngfuncs[] =
68 {
69         {"png_set_sig_bytes",           (void **) &qpng_set_sig_bytes},
70         {"png_sig_cmp",                         (void **) &qpng_sig_cmp},
71         {"png_create_read_struct",      (void **) &qpng_create_read_struct},
72         {"png_create_write_struct",     (void **) &qpng_create_write_struct},
73         {"png_create_info_struct",      (void **) &qpng_create_info_struct},
74         {"png_read_info",                       (void **) &qpng_read_info},
75         {"png_set_compression_level",   (void **) &qpng_set_compression_level},
76         {"png_set_expand",                      (void **) &qpng_set_expand},
77         {"png_set_gray_1_2_4_to_8",     (void **) &qpng_set_gray_1_2_4_to_8},
78         {"png_set_palette_to_rgb",      (void **) &qpng_set_palette_to_rgb},
79         {"png_set_tRNS_to_alpha",       (void **) &qpng_set_tRNS_to_alpha},
80         {"png_set_gray_to_rgb",         (void **) &qpng_set_gray_to_rgb},
81         {"png_set_filler",                      (void **) &qpng_set_filler},
82         {"png_set_IHDR",                        (void **) &qpng_set_IHDR},
83         {"png_set_packing",                     (void **) &qpng_set_packing},
84         {"png_set_bgr",                         (void **) &qpng_set_bgr},
85         {"png_set_interlace_handling",  (void **) &qpng_set_interlace_handling},
86         {"png_read_update_info",        (void **) &qpng_read_update_info},
87         {"png_read_image",                      (void **) &qpng_read_image},
88         {"png_read_end",                        (void **) &qpng_read_end},
89         {"png_destroy_read_struct",     (void **) &qpng_destroy_read_struct},
90         {"png_destroy_write_struct",    (void **) &qpng_destroy_write_struct},
91         {"png_set_read_fn",                     (void **) &qpng_set_read_fn},
92         {"png_set_write_fn",            (void **) &qpng_set_write_fn},
93         {"png_get_valid",                       (void **) &qpng_get_valid},
94         {"png_get_rowbytes",            (void **) &qpng_get_rowbytes},
95         {"png_get_channels",            (void **) &qpng_get_channels},
96         {"png_get_bit_depth",           (void **) &qpng_get_bit_depth},
97         {"png_get_IHDR",                        (void **) &qpng_get_IHDR},
98         {"png_get_libpng_ver",          (void **) &qpng_get_libpng_ver},
99         {"png_write_info",                      (void **) &qpng_write_info},
100         {"png_write_row",                       (void **) &qpng_write_row},
101         {"png_write_end",                       (void **) &qpng_write_end},
102         {NULL, NULL}
103 };
104
105 // Handle for PNG DLL
106 dllhandle_t png_dll = NULL;
107
108
109 /*
110 =================================================================
111
112   DLL load & unload
113
114 =================================================================
115 */
116
117 /*
118 ====================
119 PNG_OpenLibrary
120
121 Try to load the PNG DLL
122 ====================
123 */
124 qboolean PNG_OpenLibrary (void)
125 {
126         const char* dllnames [] =
127         {
128 #if WIN32
129                 "libpng12.dll",
130 #elif defined(MACOSX)
131                 "libpng12.0.dylib",
132 #else
133                 "libpng12.so.0",
134                 "libpng.so", // FreeBSD
135 #endif
136                 NULL
137         };
138
139         // Already loaded?
140         if (png_dll)
141                 return true;
142
143         // Load the DLL
144         return Sys_LoadLibrary (dllnames, &png_dll, pngfuncs);
145 }
146
147
148 /*
149 ====================
150 PNG_CloseLibrary
151
152 Unload the PNG DLL
153 ====================
154 */
155 void PNG_CloseLibrary (void)
156 {
157         Sys_UnloadLibrary (&png_dll);
158 }
159
160 /*
161 =================================================================
162
163         PNG decompression
164
165 =================================================================
166 */
167
168 #define PNG_LIBPNG_VER_STRING "1.2.4"
169
170 #define PNG_COLOR_MASK_PALETTE    1
171 #define PNG_COLOR_MASK_COLOR      2
172 #define PNG_COLOR_MASK_ALPHA      4
173
174 #define PNG_COLOR_TYPE_GRAY 0
175 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
176 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
177 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
178 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
179
180 #define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
181 #define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
182
183 #define PNG_INFO_tRNS 0x0010
184
185 // this struct is only used for status information during loading
186 static struct
187 {
188         const unsigned char     *tmpBuf;
189         int             tmpBuflength;
190         int             tmpi;
191         //int           FBgColor;
192         //int           FTransparent;
193         unsigned int    FRowBytes;
194         //double        FGamma;
195         //double        FScreenGamma;
196         unsigned char   **FRowPtrs;
197         unsigned char   *Data;
198         //char  *Title;
199         //char  *Author;
200         //char  *Description;
201         int             BitDepth;
202         int             BytesPerPixel;
203         int             ColorType;
204         unsigned long   Height; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
205         unsigned long   Width; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
206         int             Interlace;
207         int             Compression;
208         int             Filter;
209         //double        LastModified;
210         //int           Transparent;
211         qfile_t *outfile;
212 } my_png;
213
214 //LordHavoc: removed __cdecl prefix, added overrun protection, and rewrote this to be more efficient
215 void PNG_fReadData(void *png, unsigned char *data, size_t length)
216 {
217         size_t l;
218         l = my_png.tmpBuflength - my_png.tmpi;
219         if (l < length)
220         {
221                 Con_Printf("PNG_fReadData: overrun by %i bytes\n", (int)(length - l));
222                 // a read going past the end of the file, fill in the remaining bytes
223                 // with 0 just to be consistent
224                 memset(data + l, 0, length - l);
225                 length = l;
226         }
227         memcpy(data, my_png.tmpBuf + my_png.tmpi, length);
228         my_png.tmpi += (int)length;
229         //Com_HexDumpToConsole(data, (int)length);
230 }
231
232 void PNG_fWriteData(void *png, unsigned char *data, size_t length)
233 {
234         FS_Write(my_png.outfile, data, length);
235 }
236
237 void PNG_fFlushData(void *png)
238 {
239 }
240
241 void PNG_error_fn(void *png, const char *message)
242 {
243         Con_Printf("PNG_LoadImage: error: %s\n", message);
244 }
245
246 void PNG_warning_fn(void *png, const char *message)
247 {
248         Con_Printf("PNG_LoadImage: warning: %s\n", message);
249 }
250
251 extern int      image_width;
252 extern int      image_height;
253
254 unsigned char *PNG_LoadImage_BGRA (const unsigned char *raw, int filesize)
255 {
256         unsigned int c;
257         unsigned int    y;
258         void *png, *pnginfo;
259         unsigned char *imagedata = NULL;
260         unsigned char ioBuffer[8192];
261
262         // FIXME: register an error handler so that abort() won't be called on error
263
264         // No DLL = no PNGs
265         if (!png_dll)
266                 return NULL;
267
268         if(qpng_sig_cmp(raw, 0, filesize))
269                 return NULL;
270         png = (void *)qpng_create_read_struct(PNG_LIBPNG_VER_STRING, 0, PNG_error_fn, PNG_warning_fn);
271         if(!png)
272                 return NULL;
273
274         // this must be memset before the setjmp error handler, because it relies
275         // on the fields in this struct for cleanup
276         memset(&my_png, 0, sizeof(my_png));
277
278         // NOTE: this relies on jmp_buf being the first thing in the png structure
279         // created by libpng! (this is correct for libpng 1.2.x)
280 #ifdef __cplusplus
281 #if defined(MACOSX) || defined(WIN32)
282         if (setjmp((int *)png))
283 #else
284         if (setjmp((__jmp_buf_tag *)png))
285 #endif
286 #else
287         if (setjmp(png))
288 #endif
289         {
290                 if (my_png.Data)
291                         Mem_Free(my_png.Data);
292                 my_png.Data = NULL;
293                 if (my_png.FRowPtrs)
294                         Mem_Free(my_png.FRowPtrs);
295                 my_png.FRowPtrs = NULL;
296                 qpng_destroy_read_struct(&png, &pnginfo, 0);
297                 return NULL;
298         }
299         //
300
301         pnginfo = qpng_create_info_struct(png);
302         if(!pnginfo)
303         {
304                 qpng_destroy_read_struct(&png, &pnginfo, 0);
305                 return NULL;
306         }
307         qpng_set_sig_bytes(png, 0);
308
309         my_png.tmpBuf = raw;
310         my_png.tmpBuflength = filesize;
311         my_png.tmpi = 0;
312         //my_png.Data           = NULL;
313         //my_png.FRowPtrs       = NULL;
314         //my_png.Height         = 0;
315         //my_png.Width          = 0;
316         my_png.ColorType        = PNG_COLOR_TYPE_RGB;
317         //my_png.Interlace      = 0;
318         //my_png.Compression    = 0;
319         //my_png.Filter         = 0;
320         qpng_set_read_fn(png, ioBuffer, PNG_fReadData);
321         qpng_read_info(png, pnginfo);
322         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);
323
324         // 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
325         // (if it's little endian the unwritten bytes are the most significant
326         //  ones and we don't worry about that)
327         //
328         // this is only necessary because of retarded 64bit png_uint_32 types in libpng 1.2, which can (conceivably) vary by platform
329 #if LONG_MAX > 4000000000
330         if (my_png.Width > LONG_MAX || my_png.Height > LONG_MAX)
331         {
332                 my_png.Width >>= 32;
333                 my_png.Height >>= 32;
334         }
335 #endif
336
337         if (my_png.ColorType == PNG_COLOR_TYPE_PALETTE)
338                 qpng_set_palette_to_rgb(png);
339         if (my_png.ColorType == PNG_COLOR_TYPE_GRAY || my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
340         {
341                 qpng_set_gray_to_rgb(png);
342                 if (my_png.BitDepth < 8)
343                         qpng_set_gray_1_2_4_to_8(png);
344         }
345
346         if (qpng_get_valid(png, pnginfo, PNG_INFO_tRNS))
347                 qpng_set_tRNS_to_alpha(png);
348         if (my_png.BitDepth == 8 && !(my_png.ColorType  & PNG_COLOR_MASK_ALPHA))
349                 qpng_set_filler(png, 255, 1);
350         if (( my_png.ColorType == PNG_COLOR_TYPE_GRAY) || (my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA ))
351                 qpng_set_gray_to_rgb(png);
352         if (my_png.BitDepth < 8)
353                 qpng_set_expand(png);
354
355         qpng_read_update_info(png, pnginfo);
356
357         my_png.FRowBytes = qpng_get_rowbytes(png, pnginfo);
358         my_png.BytesPerPixel = qpng_get_channels(png, pnginfo);
359
360         my_png.FRowPtrs = (unsigned char **)Mem_Alloc(tempmempool, my_png.Height * sizeof(*my_png.FRowPtrs));
361         if (my_png.FRowPtrs)
362         {
363                 imagedata = (unsigned char *)Mem_Alloc(tempmempool, my_png.Height * my_png.FRowBytes);
364                 if(imagedata)
365                 {
366                         my_png.Data = imagedata;
367                         for(y = 0;y < my_png.Height;y++)
368                                 my_png.FRowPtrs[y] = my_png.Data + y * my_png.FRowBytes;
369                         qpng_read_image(png, my_png.FRowPtrs);
370                 }
371                 else
372                 {
373                         Con_Printf("PNG_LoadImage : not enough memory\n");
374                         qpng_destroy_read_struct(&png, &pnginfo, 0);
375                         Mem_Free(my_png.FRowPtrs);
376                         return NULL;
377                 }
378                 Mem_Free(my_png.FRowPtrs);
379                 my_png.FRowPtrs = NULL;
380         }
381         else
382         {
383                 Con_Printf("PNG_LoadImage : not enough memory\n");
384                 qpng_destroy_read_struct(&png, &pnginfo, 0);
385                 return NULL;
386         }
387
388         qpng_read_end(png, pnginfo);
389         qpng_destroy_read_struct(&png, &pnginfo, 0);
390
391         image_width = (int)my_png.Width;
392         image_height = (int)my_png.Height;
393
394         if (my_png.BitDepth != 8)
395         {
396                 Con_Printf ("PNG_LoadImage : bad color depth\n");
397                 Mem_Free(imagedata);
398                 return NULL;
399         }
400
401         // swizzle RGBA to BGRA
402         for (y = 0;y < (unsigned int)(image_width*image_height*4);y += 4)
403         {
404                 c = imagedata[y+0];
405                 imagedata[y+0] = imagedata[y+2];
406                 imagedata[y+2] = c;
407         }
408
409         return imagedata;
410 }
411
412 /*
413 =================================================================
414
415         PNG compression
416
417 =================================================================
418 */
419
420 #define Z_BEST_COMPRESSION 9
421 #define PNG_INTERLACE_ADAM7 1
422 #define PNG_FILTER_TYPE_BASE 0
423 #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
424 #define PNG_COMPRESSION_TYPE_BASE 0
425 #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
426
427
428 /*
429 ====================
430 PNG_SaveImage_preflipped
431
432 Save a preflipped PNG image to a file
433 ====================
434 */
435 qboolean PNG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
436 {
437         unsigned int offset, linesize;
438         qfile_t* file = NULL;
439         void *png, *pnginfo;
440         unsigned char ioBuffer[8192];
441         int passes, i, j;
442
443         // No DLL = no JPEGs
444         if (!png_dll)
445         {
446                 Con_Print("You need the libpng library to save PNG images\n");
447                 return false;
448         }
449
450         png = (void *)qpng_create_write_struct(PNG_LIBPNG_VER_STRING, 0, PNG_error_fn, PNG_warning_fn);
451         if(!png)
452                 return false;
453         pnginfo = (void *)qpng_create_info_struct(png);
454         if(!pnginfo)
455         {
456                  qpng_destroy_write_struct(&png, NULL);
457                  return false;
458         }
459
460         // this must be memset before the setjmp error handler, because it relies
461         // on the fields in this struct for cleanup
462         memset(&my_png, 0, sizeof(my_png));
463
464         // NOTE: this relies on jmp_buf being the first thing in the png structure
465         // created by libpng! (this is correct for libpng 1.2.x)
466 #ifdef __cplusplus
467 #if defined(MACOSX) || defined(WIN32)
468         if (setjmp((int *)png))
469 #else
470         if (setjmp((__jmp_buf_tag *)png))
471 #endif
472 #else
473         if (setjmp(png))
474 #endif
475         {
476                 qpng_destroy_write_struct(&png, &pnginfo);
477                 return false;
478         }
479
480         // Open the file
481         file = FS_OpenRealFile(filename, "wb", true);
482         if (!file)
483                 return false;
484         my_png.outfile = file;
485         qpng_set_write_fn(png, ioBuffer, PNG_fWriteData, PNG_fFlushData);
486
487         qpng_set_compression_level(png, Z_BEST_COMPRESSION);
488
489         qpng_set_IHDR(png, pnginfo, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
490         qpng_write_info(png, pnginfo);
491         qpng_set_packing(png);
492         qpng_set_bgr(png);
493
494         passes = qpng_set_interlace_handling(png);
495
496         linesize = width * 3;
497         offset = linesize * (height - 1);
498         for(i = 0; i < passes; ++i)
499                 for(j = 0; j < height; ++j)
500                         qpng_write_row(png, &data[offset - j * linesize]);
501
502         qpng_write_end(png, NULL);
503         qpng_destroy_write_struct(&png, &pnginfo);
504
505         FS_Close (file);
506         return true;
507 }