]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - image.c
Fix warnings for missing prototypes.
[xonotic/darkplaces.git] / image.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "image_png.h"
6 #include "r_shadow.h"
7
8 int             image_width;
9 int             image_height;
10
11 static void Image_CopyAlphaFromBlueBGRA(unsigned char *outpixels, const unsigned char *inpixels, int w, int h)
12 {
13         int i, n;
14         n = w * h;
15         for(i = 0; i < n; ++i)
16                 outpixels[4*i+3] = inpixels[4*i]; // blue channel
17 }
18
19 #if 1
20 // written by LordHavoc in a readable way, optimized by Vic, further optimized by LordHavoc (the non-special index case), readable version preserved below this
21 void Image_CopyMux(unsigned char *outpixels, const unsigned char *inpixels, int inputwidth, int inputheight, qboolean inputflipx, qboolean inputflipy, qboolean inputflipdiagonal, int numoutputcomponents, int numinputcomponents, int *outputinputcomponentindices)
22 {
23         int index, c, x, y;
24         const unsigned char *in, *line;
25         int row_inc = (inputflipy ? -inputwidth : inputwidth) * numinputcomponents, col_inc = (inputflipx ? -1 : 1) * numinputcomponents;
26         int row_ofs = (inputflipy ? (inputheight - 1) * inputwidth * numinputcomponents : 0), col_ofs = (inputflipx ? (inputwidth - 1) * numinputcomponents : 0);
27
28         for (c = 0; c < numoutputcomponents; c++)
29                 if (outputinputcomponentindices[c] & 0x80000000)
30                         break;
31         if (c < numoutputcomponents)
32         {
33                 // special indices used
34                 if (inputflipdiagonal)
35                 {
36                         for (x = 0, line = inpixels + col_ofs; x < inputwidth; x++, line += col_inc)
37                                 for (y = 0, in = line + row_ofs; y < inputheight; y++, in += row_inc, outpixels += numoutputcomponents)
38                                         for (c = 0; c < numoutputcomponents; c++)
39                                                 outpixels[c] = ((index = outputinputcomponentindices[c]) & 0x80000000) ? index : in[index];
40                 }
41                 else
42                 {
43                         for (y = 0, line = inpixels + row_ofs; y < inputheight; y++, line += row_inc)
44                                 for (x = 0, in = line + col_ofs; x < inputwidth; x++, in += col_inc, outpixels += numoutputcomponents)
45                                         for (c = 0; c < numoutputcomponents; c++)
46                                                 outpixels[c] = ((index = outputinputcomponentindices[c]) & 0x80000000) ? index : in[index];
47                 }
48         }
49         else
50         {
51                 // special indices not used
52                 if (inputflipdiagonal)
53                 {
54                         for (x = 0, line = inpixels + col_ofs; x < inputwidth; x++, line += col_inc)
55                                 for (y = 0, in = line + row_ofs; y < inputheight; y++, in += row_inc, outpixels += numoutputcomponents)
56                                         for (c = 0; c < numoutputcomponents; c++)
57                                                 outpixels[c] = in[outputinputcomponentindices[c]];
58                 }
59                 else
60                 {
61                         for (y = 0, line = inpixels + row_ofs; y < inputheight; y++, line += row_inc)
62                                 for (x = 0, in = line + col_ofs; x < inputwidth; x++, in += col_inc, outpixels += numoutputcomponents)
63                                         for (c = 0; c < numoutputcomponents; c++)
64                                                 outpixels[c] = in[outputinputcomponentindices[c]];
65                 }
66         }
67 }
68 #else
69 // intentionally readable version
70 void Image_CopyMux(unsigned char *outpixels, const unsigned char *inpixels, int inputwidth, int inputheight, qboolean inputflipx, qboolean inputflipy, qboolean inputflipdiagonal, int numoutputcomponents, int numinputcomponents, int *outputinputcomponentindices)
71 {
72         int index, c, x, y;
73         const unsigned char *in, *inrow, *incolumn;
74         if (inputflipdiagonal)
75         {
76                 for (x = 0;x < inputwidth;x++)
77                 {
78                         for (y = 0;y < inputheight;y++)
79                         {
80                                 in = inpixels + ((inputflipy ? inputheight - 1 - y : y) * inputwidth + (inputflipx ? inputwidth - 1 - x : x)) * numinputcomponents;
81                                 for (c = 0;c < numoutputcomponents;c++)
82                                 {
83                                         index = outputinputcomponentindices[c];
84                                         if (index & 0x80000000)
85                                                 *outpixels++ = index;
86                                         else
87                                                 *outpixels++ = in[index];
88                                 }
89                         }
90                 }
91         }
92         else
93         {
94                 for (y = 0;y < inputheight;y++)
95                 {
96                         for (x = 0;x < inputwidth;x++)
97                         {
98                                 in = inpixels + ((inputflipy ? inputheight - 1 - y : y) * inputwidth + (inputflipx ? inputwidth - 1 - x : x)) * numinputcomponents;
99                                 for (c = 0;c < numoutputcomponents;c++)
100                                 {
101                                         index = outputinputcomponentindices[c];
102                                         if (index & 0x80000000)
103                                                 *outpixels++ = index;
104                                         else
105                                                 *outpixels++ = in[index];
106                                 }
107                         }
108                 }
109         }
110 }
111 #endif
112
113 void Image_GammaRemapRGB(const unsigned char *in, unsigned char *out, int pixels, const unsigned char *gammar, const unsigned char *gammag, const unsigned char *gammab)
114 {
115         while (pixels--)
116         {
117                 out[0] = gammar[in[0]];
118                 out[1] = gammag[in[1]];
119                 out[2] = gammab[in[2]];
120                 in += 3;
121                 out += 3;
122         }
123 }
124
125 // note: pal must be 32bit color
126 void Image_Copy8bitBGRA(const unsigned char *in, unsigned char *out, int pixels, const unsigned int *pal)
127 {
128         int *iout = (int *)out;
129         while (pixels >= 8)
130         {
131                 iout[0] = pal[in[0]];
132                 iout[1] = pal[in[1]];
133                 iout[2] = pal[in[2]];
134                 iout[3] = pal[in[3]];
135                 iout[4] = pal[in[4]];
136                 iout[5] = pal[in[5]];
137                 iout[6] = pal[in[6]];
138                 iout[7] = pal[in[7]];
139                 in += 8;
140                 iout += 8;
141                 pixels -= 8;
142         }
143         if (pixels & 4)
144         {
145                 iout[0] = pal[in[0]];
146                 iout[1] = pal[in[1]];
147                 iout[2] = pal[in[2]];
148                 iout[3] = pal[in[3]];
149                 in += 4;
150                 iout += 4;
151         }
152         if (pixels & 2)
153         {
154                 iout[0] = pal[in[0]];
155                 iout[1] = pal[in[1]];
156                 in += 2;
157                 iout += 2;
158         }
159         if (pixels & 1)
160                 iout[0] = pal[in[0]];
161 }
162
163 /*
164 =================================================================
165
166   PCX Loading
167
168 =================================================================
169 */
170
171 typedef struct pcx_s
172 {
173     char        manufacturer;
174     char        version;
175     char        encoding;
176     char        bits_per_pixel;
177     unsigned short      xmin,ymin,xmax,ymax;
178     unsigned short      hres,vres;
179     unsigned char       palette[48];
180     char        reserved;
181     char        color_planes;
182     unsigned short      bytes_per_line;
183     unsigned short      palette_type;
184     char        filler[58];
185 } pcx_t;
186
187 /*
188 ============
189 LoadPCX
190 ============
191 */
192 static unsigned char* LoadPCX_BGRA (const unsigned char *f, int filesize, int *miplevel)
193 {
194         pcx_t pcx;
195         unsigned char *a, *b, *image_buffer, *pbuf;
196         const unsigned char *palette, *fin, *enddata;
197         int x, y, x2, dataByte;
198
199         if (filesize < (int)sizeof(pcx) + 768)
200         {
201                 Con_Print("Bad pcx file\n");
202                 return NULL;
203         }
204
205         fin = f;
206
207         memcpy(&pcx, fin, sizeof(pcx));
208         fin += sizeof(pcx);
209
210         // LordHavoc: big-endian support ported from QF newtree
211         pcx.xmax = LittleShort (pcx.xmax);
212         pcx.xmin = LittleShort (pcx.xmin);
213         pcx.ymax = LittleShort (pcx.ymax);
214         pcx.ymin = LittleShort (pcx.ymin);
215         pcx.hres = LittleShort (pcx.hres);
216         pcx.vres = LittleShort (pcx.vres);
217         pcx.bytes_per_line = LittleShort (pcx.bytes_per_line);
218         pcx.palette_type = LittleShort (pcx.palette_type);
219
220         image_width = pcx.xmax + 1 - pcx.xmin;
221         image_height = pcx.ymax + 1 - pcx.ymin;
222         if (pcx.manufacturer != 0x0a || pcx.version != 5 || pcx.encoding != 1 || pcx.bits_per_pixel != 8 || image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
223         {
224                 Con_Print("Bad pcx file\n");
225                 return NULL;
226         }
227
228         palette = f + filesize - 768;
229
230         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width*image_height*4);
231         if (!image_buffer)
232         {
233                 Con_Printf("LoadPCX: not enough memory for %i by %i image\n", image_width, image_height);
234                 return NULL;
235         }
236         pbuf = image_buffer + image_width*image_height*3;
237         enddata = palette;
238
239         for (y = 0;y < image_height && fin < enddata;y++)
240         {
241                 a = pbuf + y * image_width;
242                 for (x = 0;x < image_width && fin < enddata;)
243                 {
244                         dataByte = *fin++;
245                         if(dataByte >= 0xC0)
246                         {
247                                 if (fin >= enddata)
248                                         break;
249                                 x2 = x + (dataByte & 0x3F);
250                                 dataByte = *fin++;
251                                 if (x2 > image_width)
252                                         x2 = image_width; // technically an error
253                                 while(x < x2)
254                                         a[x++] = dataByte;
255                         }
256                         else
257                                 a[x++] = dataByte;
258                 }
259                 while(x < image_width)
260                         a[x++] = 0;
261         }
262
263         a = image_buffer;
264         b = pbuf;
265
266         for(x = 0;x < image_width*image_height;x++)
267         {
268                 y = *b++ * 3;
269                 *a++ = palette[y+2];
270                 *a++ = palette[y+1];
271                 *a++ = palette[y];
272                 *a++ = 255;
273         }
274
275         return image_buffer;
276 }
277
278 /*
279 ============
280 LoadPCX
281 ============
282 */
283 qboolean LoadPCX_QWSkin(const unsigned char *f, int filesize, unsigned char *pixels, int outwidth, int outheight)
284 {
285         pcx_t pcx;
286         unsigned char *a;
287         const unsigned char *fin, *enddata;
288         int x, y, x2, dataByte, pcxwidth, pcxheight;
289
290         if (filesize < (int)sizeof(pcx) + 768)
291                 return false;
292
293         image_width = outwidth;
294         image_height = outheight;
295         fin = f;
296
297         memcpy(&pcx, fin, sizeof(pcx));
298         fin += sizeof(pcx);
299
300         // LordHavoc: big-endian support ported from QF newtree
301         pcx.xmax = LittleShort (pcx.xmax);
302         pcx.xmin = LittleShort (pcx.xmin);
303         pcx.ymax = LittleShort (pcx.ymax);
304         pcx.ymin = LittleShort (pcx.ymin);
305         pcx.hres = LittleShort (pcx.hres);
306         pcx.vres = LittleShort (pcx.vres);
307         pcx.bytes_per_line = LittleShort (pcx.bytes_per_line);
308         pcx.palette_type = LittleShort (pcx.palette_type);
309
310         pcxwidth = pcx.xmax + 1 - pcx.xmin;
311         pcxheight = pcx.ymax + 1 - pcx.ymin;
312         if (pcx.manufacturer != 0x0a || pcx.version != 5 || pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcxwidth > 4096 || pcxheight > 4096 || pcxwidth <= 0 || pcxheight <= 0)
313                 return false;
314
315         enddata = f + filesize - 768;
316
317         for (y = 0;y < outheight && fin < enddata;y++)
318         {
319                 a = pixels + y * outwidth;
320                 // pad the output with blank lines if needed
321                 if (y >= pcxheight)
322                 {
323                         memset(a, 0, outwidth);
324                         continue;
325                 }
326                 for (x = 0;x < pcxwidth;)
327                 {
328                         if (fin >= enddata)
329                                 return false;
330                         dataByte = *fin++;
331                         if(dataByte >= 0xC0)
332                         {
333                                 x2 = x + (dataByte & 0x3F);
334                                 if (fin >= enddata)
335                                         return false;
336                                 if (x2 > pcxwidth)
337                                         return false;
338                                 dataByte = *fin++;
339                                 for (;x < x2;x++)
340                                         if (x < outwidth)
341                                                 a[x] = dataByte;
342                         }
343                         else
344                         {
345                                 if (x < outwidth) // truncate to destination width
346                                         a[x] = dataByte;
347                                 x++;
348                         }
349                 }
350                 while(x < outwidth)
351                         a[x++] = 0;
352         }
353
354         return true;
355 }
356
357 /*
358 ============
359 LoadPCX
360 ============
361 */
362 qboolean LoadPCX_PaletteOnly(const unsigned char *f, int filesize, unsigned char *palette768b)
363 {
364         if (filesize < 768)
365                 return false;
366         memcpy(palette768b, f + filesize - 768, 768);
367         return true;
368 }
369
370 /*
371 =========================================================
372
373 TARGA LOADING
374
375 =========================================================
376 */
377
378 typedef struct _TargaHeader
379 {
380         unsigned char   id_length, colormap_type, image_type;
381         unsigned short  colormap_index, colormap_length;
382         unsigned char   colormap_size;
383         unsigned short  x_origin, y_origin, width, height;
384         unsigned char   pixel_size, attributes;
385 }
386 TargaHeader;
387
388 static void PrintTargaHeader(TargaHeader *t)
389 {
390         Con_Printf("TargaHeader:\nuint8 id_length = %i;\nuint8 colormap_type = %i;\nuint8 image_type = %i;\nuint16 colormap_index = %i;\nuint16 colormap_length = %i;\nuint8 colormap_size = %i;\nuint16 x_origin = %i;\nuint16 y_origin = %i;\nuint16 width = %i;\nuint16 height = %i;\nuint8 pixel_size = %i;\nuint8 attributes = %i;\n", t->id_length, t->colormap_type, t->image_type, t->colormap_index, t->colormap_length, t->colormap_size, t->x_origin, t->y_origin, t->width, t->height, t->pixel_size, t->attributes);
391 }
392
393 /*
394 =============
395 LoadTGA
396 =============
397 */
398 unsigned char *LoadTGA_BGRA (const unsigned char *f, int filesize, int *miplevel)
399 {
400         int x, y, pix_inc, row_inci, runlen, alphabits;
401         unsigned char *image_buffer;
402         unsigned int *pixbufi;
403         const unsigned char *fin, *enddata;
404         TargaHeader targa_header;
405         unsigned int palettei[256];
406         union
407         {
408                 unsigned int i;
409                 unsigned char b[4];
410         }
411         bgra;
412
413         if (filesize < 19)
414                 return NULL;
415
416         enddata = f + filesize;
417
418         targa_header.id_length = f[0];
419         targa_header.colormap_type = f[1];
420         targa_header.image_type = f[2];
421
422         targa_header.colormap_index = f[3] + f[4] * 256;
423         targa_header.colormap_length = f[5] + f[6] * 256;
424         targa_header.colormap_size = f[7];
425         targa_header.x_origin = f[8] + f[9] * 256;
426         targa_header.y_origin = f[10] + f[11] * 256;
427         targa_header.width = image_width = f[12] + f[13] * 256;
428         targa_header.height = image_height = f[14] + f[15] * 256;
429         targa_header.pixel_size = f[16];
430         targa_header.attributes = f[17];
431
432         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
433         {
434                 Con_Print("LoadTGA: invalid size\n");
435                 PrintTargaHeader(&targa_header);
436                 return NULL;
437         }
438
439         // advance to end of header
440         fin = f + 18;
441
442         // skip TARGA image comment (usually 0 bytes)
443         fin += targa_header.id_length;
444
445         // read/skip the colormap if present (note: according to the TARGA spec it
446         // can be present even on truecolor or greyscale images, just not used by
447         // the image data)
448         if (targa_header.colormap_type)
449         {
450                 if (targa_header.colormap_length > 256)
451                 {
452                         Con_Print("LoadTGA: only up to 256 colormap_length supported\n");
453                         PrintTargaHeader(&targa_header);
454                         return NULL;
455                 }
456                 if (targa_header.colormap_index)
457                 {
458                         Con_Print("LoadTGA: colormap_index not supported\n");
459                         PrintTargaHeader(&targa_header);
460                         return NULL;
461                 }
462                 if (targa_header.colormap_size == 24)
463                 {
464                         for (x = 0;x < targa_header.colormap_length;x++)
465                         {
466                                 bgra.b[0] = *fin++;
467                                 bgra.b[1] = *fin++;
468                                 bgra.b[2] = *fin++;
469                                 bgra.b[3] = 255;
470                                 palettei[x] = bgra.i;
471                         }
472                 }
473                 else if (targa_header.colormap_size == 32)
474                 {
475                         memcpy(palettei, fin, targa_header.colormap_length*4);
476                         fin += targa_header.colormap_length * 4;
477                 }
478                 else
479                 {
480                         Con_Print("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
481                         PrintTargaHeader(&targa_header);
482                         return NULL;
483                 }
484         }
485
486         // check our pixel_size restrictions according to image_type
487         switch (targa_header.image_type & ~8)
488         {
489         case 2:
490                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
491                 {
492                         Con_Print("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
493                         PrintTargaHeader(&targa_header);
494                         return NULL;
495                 }
496                 break;
497         case 3:
498                 // set up a palette to make the loader easier
499                 for (x = 0;x < 256;x++)
500                 {
501                         bgra.b[0] = bgra.b[1] = bgra.b[2] = x;
502                         bgra.b[3] = 255;
503                         palettei[x] = bgra.i;
504                 }
505                 // fall through to colormap case
506         case 1:
507                 if (targa_header.pixel_size != 8)
508                 {
509                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
510                         PrintTargaHeader(&targa_header);
511                         return NULL;
512                 }
513                 break;
514         default:
515                 Con_Printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
516                 PrintTargaHeader(&targa_header);
517                 return NULL;
518         }
519
520         if (targa_header.attributes & 0x10)
521         {
522                 Con_Print("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
523                 return NULL;
524         }
525
526         // number of attribute bits per pixel, we only support 0 or 8
527         alphabits = targa_header.attributes & 0x0F;
528         if (alphabits != 8 && alphabits != 0)
529         {
530                 Con_Print("LoadTGA: only 0 or 8 attribute (alpha) bits supported\n");
531                 return NULL;
532         }
533
534         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
535         if (!image_buffer)
536         {
537                 Con_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
538                 return NULL;
539         }
540
541         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
542         if ((targa_header.attributes & 0x20) == 0)
543         {
544                 pixbufi = (unsigned int*)image_buffer + (image_height - 1)*image_width;
545                 row_inci = -image_width*2;
546         }
547         else
548         {
549                 pixbufi = (unsigned int*)image_buffer;
550                 row_inci = 0;
551         }
552
553         pix_inc = 1;
554         if ((targa_header.image_type & ~8) == 2)
555                 pix_inc = (targa_header.pixel_size + 7) / 8;
556         switch (targa_header.image_type)
557         {
558         case 1: // colormapped, uncompressed
559         case 3: // greyscale, uncompressed
560                 if (fin + image_width * image_height * pix_inc > enddata)
561                         break;
562                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
563                         for (x = 0;x < image_width;x++)
564                                 *pixbufi++ = palettei[*fin++];
565                 break;
566         case 2:
567                 // BGR or BGRA, uncompressed
568                 if (fin + image_width * image_height * pix_inc > enddata)
569                         break;
570                 if (targa_header.pixel_size == 32 && alphabits)
571                 {
572                         for (y = 0;y < image_height;y++)
573                                 memcpy(pixbufi + y * (image_width + row_inci), fin + y * image_width * pix_inc, image_width*4);
574                 }
575                 else
576                 {
577                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
578                         {
579                                 for (x = 0;x < image_width;x++, fin += pix_inc)
580                                 {
581                                         bgra.b[0] = fin[0];
582                                         bgra.b[1] = fin[1];
583                                         bgra.b[2] = fin[2];
584                                         bgra.b[3] = 255;
585                                         *pixbufi++ = bgra.i;
586                                 }
587                         }
588                 }
589                 break;
590         case 9: // colormapped, RLE
591         case 11: // greyscale, RLE
592                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
593                 {
594                         for (x = 0;x < image_width;)
595                         {
596                                 if (fin >= enddata)
597                                         break; // error - truncated file
598                                 runlen = *fin++;
599                                 if (runlen & 0x80)
600                                 {
601                                         // RLE - all pixels the same color
602                                         runlen += 1 - 0x80;
603                                         if (fin + pix_inc > enddata)
604                                                 break; // error - truncated file
605                                         if (x + runlen > image_width)
606                                                 break; // error - line exceeds width
607                                         bgra.i = palettei[*fin++];
608                                         for (;runlen--;x++)
609                                                 *pixbufi++ = bgra.i;
610                                 }
611                                 else
612                                 {
613                                         // uncompressed - all pixels different color
614                                         runlen++;
615                                         if (fin + pix_inc * runlen > enddata)
616                                                 break; // error - truncated file
617                                         if (x + runlen > image_width)
618                                                 break; // error - line exceeds width
619                                         for (;runlen--;x++)
620                                                 *pixbufi++ = palettei[*fin++];
621                                 }
622                         }
623
624                         if (x != image_width)
625                         {
626                                 // pixbufi is useless now
627                                 Con_Printf("LoadTGA: corrupt file\n");
628                                 break;
629                         }
630                 }
631                 break;
632         case 10:
633                 // BGR or BGRA, RLE
634                 if (targa_header.pixel_size == 32 && alphabits)
635                 {
636                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
637                         {
638                                 for (x = 0;x < image_width;)
639                                 {
640                                         if (fin >= enddata)
641                                                 break; // error - truncated file
642                                         runlen = *fin++;
643                                         if (runlen & 0x80)
644                                         {
645                                                 // RLE - all pixels the same color
646                                                 runlen += 1 - 0x80;
647                                                 if (fin + pix_inc > enddata)
648                                                         break; // error - truncated file
649                                                 if (x + runlen > image_width)
650                                                         break; // error - line exceeds width
651                                                 bgra.b[0] = fin[0];
652                                                 bgra.b[1] = fin[1];
653                                                 bgra.b[2] = fin[2];
654                                                 bgra.b[3] = fin[3];
655                                                 fin += pix_inc;
656                                                 for (;runlen--;x++)
657                                                         *pixbufi++ = bgra.i;
658                                         }
659                                         else
660                                         {
661                                                 // uncompressed - all pixels different color
662                                                 runlen++;
663                                                 if (fin + pix_inc * runlen > enddata)
664                                                         break; // error - truncated file
665                                                 if (x + runlen > image_width)
666                                                         break; // error - line exceeds width
667                                                 for (;runlen--;x++)
668                                                 {
669                                                         bgra.b[0] = fin[0];
670                                                         bgra.b[1] = fin[1];
671                                                         bgra.b[2] = fin[2];
672                                                         bgra.b[3] = fin[3];
673                                                         fin += pix_inc;
674                                                         *pixbufi++ = bgra.i;
675                                                 }
676                                         }
677                                 }
678
679                                 if (x != image_width)
680                                 {
681                                         // pixbufi is useless now
682                                         Con_Printf("LoadTGA: corrupt file\n");
683                                         break;
684                                 }
685                         }
686                 }
687                 else
688                 {
689                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
690                         {
691                                 for (x = 0;x < image_width;)
692                                 {
693                                         if (fin >= enddata)
694                                                 break; // error - truncated file
695                                         runlen = *fin++;
696                                         if (runlen & 0x80)
697                                         {
698                                                 // RLE - all pixels the same color
699                                                 runlen += 1 - 0x80;
700                                                 if (fin + pix_inc > enddata)
701                                                         break; // error - truncated file
702                                                 if (x + runlen > image_width)
703                                                         break; // error - line exceeds width
704                                                 bgra.b[0] = fin[0];
705                                                 bgra.b[1] = fin[1];
706                                                 bgra.b[2] = fin[2];
707                                                 bgra.b[3] = 255;
708                                                 fin += pix_inc;
709                                                 for (;runlen--;x++)
710                                                         *pixbufi++ = bgra.i;
711                                         }
712                                         else
713                                         {
714                                                 // uncompressed - all pixels different color
715                                                 runlen++;
716                                                 if (fin + pix_inc * runlen > enddata)
717                                                         break; // error - truncated file
718                                                 if (x + runlen > image_width)
719                                                         break; // error - line exceeds width
720                                                 for (;runlen--;x++)
721                                                 {
722                                                         bgra.b[0] = fin[0];
723                                                         bgra.b[1] = fin[1];
724                                                         bgra.b[2] = fin[2];
725                                                         bgra.b[3] = 255;
726                                                         fin += pix_inc;
727                                                         *pixbufi++ = bgra.i;
728                                                 }
729                                         }
730                                 }
731
732                                 if (x != image_width)
733                                 {
734                                         // pixbufi is useless now
735                                         Con_Printf("LoadTGA: corrupt file\n");
736                                         break;
737                                 }
738                         }
739                 }
740                 break;
741         default:
742                 // unknown image_type
743                 break;
744         }
745
746         return image_buffer;
747 }
748
749 typedef struct q2wal_s
750 {
751         char            name[32];
752         unsigned        width, height;
753         unsigned        offsets[MIPLEVELS];             // four mip maps stored
754         char            animname[32];                   // next frame in animation chain
755         int                     flags;
756         int                     contents;
757         int                     value;
758 } q2wal_t;
759
760 static unsigned char *LoadWAL_BGRA (const unsigned char *f, int filesize, int *miplevel)
761 {
762         unsigned char *image_buffer;
763         const q2wal_t *inwal = (const q2wal_t *)f;
764
765         if (filesize < (int) sizeof(q2wal_t))
766         {
767                 Con_Print("LoadWAL: invalid WAL file\n");
768                 return NULL;
769         }
770
771         image_width = LittleLong(inwal->width);
772         image_height = LittleLong(inwal->height);
773         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
774         {
775                 Con_Printf("LoadWAL: invalid size %ix%i\n", image_width, image_height);
776                 return NULL;
777         }
778
779         if (filesize < (int) LittleLong(inwal->offsets[0]) + image_width * image_height)
780         {
781                 Con_Print("LoadWAL: invalid WAL file\n");
782                 return NULL;
783         }
784
785         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
786         if (!image_buffer)
787         {
788                 Con_Printf("LoadWAL: not enough memory for %i by %i image\n", image_width, image_height);
789                 return NULL;
790         }
791         Image_Copy8bitBGRA(f + LittleLong(inwal->offsets[0]), image_buffer, image_width * image_height, q2palette_bgra_complete);
792         return image_buffer;
793 }
794
795 qboolean LoadWAL_GetMetadata(const unsigned char *f, int filesize, int *retwidth, int *retheight, int *retflags, int *retvalue, int *retcontents, char *retanimname32c)
796 {
797         const q2wal_t *inwal = (const q2wal_t *)f;
798
799         if (filesize < (int) sizeof(q2wal_t))
800         {
801                 Con_Print("LoadWAL: invalid WAL file\n");
802                 *retwidth = 16;
803                 *retheight = 16;
804                 *retflags = 0;
805                 *retvalue = 0;
806                 *retcontents = 0;
807                 memset(retanimname32c, 0, 32);
808                 return false;
809         }
810
811         *retwidth = LittleLong(inwal->width);
812         *retheight = LittleLong(inwal->height);
813         *retflags = LittleLong(inwal->flags);
814         *retvalue = LittleLong(inwal->value);
815         *retcontents = LittleLong(inwal->contents);
816         memcpy(retanimname32c, inwal->animname, 32);
817         retanimname32c[31] = 0;
818         return true;
819 }
820
821
822 void Image_StripImageExtension (const char *in, char *out, size_t size_out)
823 {
824         const char *ext;
825
826         if (size_out == 0)
827                 return;
828
829         ext = FS_FileExtension(in);
830         if (ext && (!strcmp(ext, "tga") || !strcmp(ext, "pcx") || !strcmp(ext, "lmp") || !strcmp(ext, "png") || !strcmp(ext, "jpg") || !strcmp(ext, "wal")))
831                 FS_StripExtension(in, out, size_out);
832         else
833                 strlcpy(out, in, size_out);
834 }
835
836 static unsigned char image_linearfromsrgb[256];
837 static unsigned char image_srgbfromlinear_lightmap[256];
838
839 void Image_MakeLinearColorsFromsRGB(unsigned char *pout, const unsigned char *pin, int numpixels)
840 {
841         int i;
842         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
843         if (!image_linearfromsrgb[255])
844                 for (i = 0;i < 256;i++)
845                         image_linearfromsrgb[i] = (unsigned char)floor(Image_LinearFloatFromsRGB(i) * 255.0f + 0.5f);
846         for (i = 0;i < numpixels;i++)
847         {
848                 pout[i*4+0] = image_linearfromsrgb[pin[i*4+0]];
849                 pout[i*4+1] = image_linearfromsrgb[pin[i*4+1]];
850                 pout[i*4+2] = image_linearfromsrgb[pin[i*4+2]];
851                 pout[i*4+3] = pin[i*4+3];
852         }
853 }
854
855 void Image_MakesRGBColorsFromLinear_Lightmap(unsigned char *pout, const unsigned char *pin, int numpixels)
856 {
857         int i;
858         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
859         if (!image_srgbfromlinear_lightmap[255])
860                 for (i = 0;i < 256;i++)
861                         image_srgbfromlinear_lightmap[i] = (unsigned char)floor(bound(0.0f, Image_sRGBFloatFromLinear_Lightmap(i), 1.0f) * 255.0f + 0.5f);
862         for (i = 0;i < numpixels;i++)
863         {
864                 pout[i*4+0] = image_srgbfromlinear_lightmap[pin[i*4+0]];
865                 pout[i*4+1] = image_srgbfromlinear_lightmap[pin[i*4+1]];
866                 pout[i*4+2] = image_srgbfromlinear_lightmap[pin[i*4+2]];
867                 pout[i*4+3] = pin[i*4+3];
868         }
869 }
870
871 typedef struct imageformat_s
872 {
873         const char *formatstring;
874         unsigned char *(*loadfunc)(const unsigned char *f, int filesize, int *miplevel);
875 }
876 imageformat_t;
877
878 // GAME_TENEBRAE only
879 imageformat_t imageformats_tenebrae[] =
880 {
881         {"override/%s.tga", LoadTGA_BGRA},
882         {"override/%s.png", PNG_LoadImage_BGRA},
883         {"override/%s.jpg", JPEG_LoadImage_BGRA},
884         {"override/%s.pcx", LoadPCX_BGRA},
885         {"%s.tga", LoadTGA_BGRA},
886         {"%s.png", PNG_LoadImage_BGRA},
887         {"%s.jpg", JPEG_LoadImage_BGRA},
888         {"%s.pcx", LoadPCX_BGRA},
889         {NULL, NULL}
890 };
891
892 imageformat_t imageformats_nopath[] =
893 {
894         {"override/%s.tga", LoadTGA_BGRA},
895         {"override/%s.png", PNG_LoadImage_BGRA},
896         {"override/%s.jpg", JPEG_LoadImage_BGRA},
897         {"textures/%s.tga", LoadTGA_BGRA},
898         {"textures/%s.png", PNG_LoadImage_BGRA},
899         {"textures/%s.jpg", JPEG_LoadImage_BGRA},
900         {"%s.tga", LoadTGA_BGRA},
901         {"%s.png", PNG_LoadImage_BGRA},
902         {"%s.jpg", JPEG_LoadImage_BGRA},
903         {"%s.pcx", LoadPCX_BGRA},
904         {NULL, NULL}
905 };
906
907 // GAME_DELUXEQUAKE only
908 // VorteX: the point why i use such messy texture paths is
909 // that GtkRadiant can't detect normal/gloss textures
910 // and exclude them from texture browser
911 // so i just use additional folder to store this textures
912 imageformat_t imageformats_dq[] =
913 {
914         {"%s.tga", LoadTGA_BGRA},
915         {"%s.jpg", JPEG_LoadImage_BGRA},
916         {"texturemaps/%s.tga", LoadTGA_BGRA},
917         {"texturemaps/%s.jpg", JPEG_LoadImage_BGRA},
918         {NULL, NULL}
919 };
920
921 imageformat_t imageformats_textures[] =
922 {
923         {"%s.tga", LoadTGA_BGRA},
924         {"%s.png", PNG_LoadImage_BGRA},
925         {"%s.jpg", JPEG_LoadImage_BGRA},
926         {"%s.pcx", LoadPCX_BGRA},
927         {"%s.wal", LoadWAL_BGRA},
928         {NULL, NULL}
929 };
930
931 imageformat_t imageformats_gfx[] =
932 {
933         {"%s.tga", LoadTGA_BGRA},
934         {"%s.png", PNG_LoadImage_BGRA},
935         {"%s.jpg", JPEG_LoadImage_BGRA},
936         {"%s.pcx", LoadPCX_BGRA},
937         {NULL, NULL}
938 };
939
940 imageformat_t imageformats_other[] =
941 {
942         {"%s.tga", LoadTGA_BGRA},
943         {"%s.png", PNG_LoadImage_BGRA},
944         {"%s.jpg", JPEG_LoadImage_BGRA},
945         {"%s.pcx", LoadPCX_BGRA},
946         {NULL, NULL}
947 };
948
949 int fixtransparentpixels(unsigned char *data, int w, int h);
950 unsigned char *loadimagepixelsbgra (const char *filename, qboolean complain, qboolean allowFixtrans, qboolean convertsRGB, int *miplevel)
951 {
952         fs_offset_t filesize;
953         imageformat_t *firstformat, *format;
954         unsigned char *f, *data = NULL, *data2 = NULL;
955         char basename[MAX_QPATH], name[MAX_QPATH], name2[MAX_QPATH], *c;
956         char vabuf[1024];
957         //if (developer_memorydebug.integer)
958         //      Mem_CheckSentinelsGlobal();
959         if (developer_texturelogging.integer)
960                 Log_Printf("textures.log", "%s\n", filename);
961         Image_StripImageExtension(filename, basename, sizeof(basename)); // strip filename extensions to allow replacement by other types
962         // replace *'s with #, so commandline utils don't get confused when dealing with the external files
963         for (c = basename;*c;c++)
964                 if (*c == '*')
965                         *c = '#';
966         name[0] = 0;
967         if (strchr(basename, '/'))
968         {
969                 int i;
970                 for (i = 0;i < (int)sizeof(name)-1 && basename[i] != '/';i++)
971                         name[i] = basename[i];
972                 name[i] = 0;
973         }
974         if (gamemode == GAME_TENEBRAE)
975                 firstformat = imageformats_tenebrae;
976         else if (gamemode == GAME_DELUXEQUAKE)
977                 firstformat = imageformats_dq;
978         else if (!strcasecmp(name, "textures"))
979                 firstformat = imageformats_textures;
980         else if (!strcasecmp(name, "gfx"))
981                 firstformat = imageformats_gfx;
982         else if (!strchr(basename, '/'))
983                 firstformat = imageformats_nopath;
984         else
985                 firstformat = imageformats_other;
986         // now try all the formats in the selected list
987         for (format = firstformat;format->formatstring;format++)
988         {
989                 dpsnprintf (name, sizeof(name), format->formatstring, basename);
990                 f = FS_LoadFile(name, tempmempool, true, &filesize);
991                 if (f)
992                 {
993                         int mymiplevel = miplevel ? *miplevel : 0;
994                         image_width = 0;
995                         image_height = 0;
996                         data = format->loadfunc(f, (int)filesize, &mymiplevel);
997                         Mem_Free(f);
998                         if (data)
999                         {
1000                                 if(format->loadfunc == JPEG_LoadImage_BGRA) // jpeg can't do alpha, so let's simulate it by loading another jpeg
1001                                 {
1002                                         dpsnprintf (name2, sizeof(name2), format->formatstring, va(vabuf, sizeof(vabuf), "%s_alpha", basename));
1003                                         f = FS_LoadFile(name2, tempmempool, true, &filesize);
1004                                         if(f)
1005                                         {
1006                                                 int mymiplevel2 = miplevel ? *miplevel : 0;
1007                                                 int image_width_save = image_width;
1008                                                 int image_height_save = image_height;
1009                                                 data2 = format->loadfunc(f, (int)filesize, &mymiplevel2);
1010                                                 if(data2 && mymiplevel == mymiplevel2 && image_width == image_width_save && image_height == image_height_save)
1011                                                         Image_CopyAlphaFromBlueBGRA(data, data2, image_width, image_height);
1012                                                 else
1013                                                         Con_Printf("loadimagepixelsrgba: corrupt or invalid alpha image %s_alpha\n", basename);
1014                                                 image_width = image_width_save;
1015                                                 image_height = image_height_save;
1016                                                 if(data2)
1017                                                         Mem_Free(data2);
1018                                                 Mem_Free(f);
1019                                         }
1020                                 }
1021                                 if (developer_loading.integer)
1022                                         Con_DPrintf("loaded image %s (%dx%d)\n", name, image_width, image_height);
1023                                 if(miplevel)
1024                                         *miplevel = mymiplevel;
1025                                 //if (developer_memorydebug.integer)
1026                                 //      Mem_CheckSentinelsGlobal();
1027                                 if(allowFixtrans && r_fixtrans_auto.integer)
1028                                 {
1029                                         int n = fixtransparentpixels(data, image_width, image_height);
1030                                         if(n)
1031                                         {
1032                                                 Con_Printf("- had to fix %s (%d pixels changed)\n", name, n);
1033                                                 if(r_fixtrans_auto.integer >= 2)
1034                                                 {
1035                                                         char outfilename[MAX_QPATH], buf[MAX_QPATH];
1036                                                         Image_StripImageExtension(name, buf, sizeof(buf));
1037                                                         dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1038                                                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1039                                                         Con_Printf("- %s written.\n", outfilename);
1040                                                 }
1041                                         }
1042                                 }
1043                                 if (convertsRGB)
1044                                         Image_MakeLinearColorsFromsRGB(data, data, image_width * image_height);
1045                                 return data;
1046                         }
1047                         else
1048                                 Con_DPrintf("Error loading image %s (file loaded but decode failed)\n", name);
1049                 }
1050         }
1051         if (complain)
1052         {
1053                 Con_Printf("Couldn't load %s using ", filename);
1054                 for (format = firstformat;format->formatstring;format++)
1055                 {
1056                         dpsnprintf (name, sizeof(name), format->formatstring, basename);
1057                         Con_Printf(format == firstformat ? "\"%s\"" : (format[1].formatstring ? ", \"%s\"" : " or \"%s\".\n"), format->formatstring);
1058                 }
1059         }
1060
1061         // texture loading can take a while, so make sure we're sending keepalives
1062         CL_KeepaliveMessage(false);
1063
1064         //if (developer_memorydebug.integer)
1065         //      Mem_CheckSentinelsGlobal();
1066         return NULL;
1067 }
1068
1069 extern cvar_t gl_picmip;
1070 rtexture_t *loadtextureimage (rtexturepool_t *pool, const char *filename, qboolean complain, int flags, qboolean allowFixtrans, qboolean sRGB)
1071 {
1072         unsigned char *data;
1073         rtexture_t *rt;
1074         int miplevel = R_PicmipForFlags(flags);
1075         if (!(data = loadimagepixelsbgra (filename, complain, allowFixtrans, false, &miplevel)))
1076                 return 0;
1077         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, sRGB ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, flags, miplevel, NULL);
1078         Mem_Free(data);
1079         return rt;
1080 }
1081
1082 int fixtransparentpixels(unsigned char *data, int w, int h)
1083 {
1084         int const FIXTRANS_NEEDED = 1;
1085         int const FIXTRANS_HAS_L = 2;
1086         int const FIXTRANS_HAS_R = 4;
1087         int const FIXTRANS_HAS_U = 8;
1088         int const FIXTRANS_HAS_D = 16;
1089         int const FIXTRANS_FIXED = 32;
1090         unsigned char *fixMask = (unsigned char *) Mem_Alloc(tempmempool, w * h);
1091         int fixPixels = 0;
1092         int changedPixels = 0;
1093         int x, y;
1094
1095 #define FIXTRANS_PIXEL (y*w+x)
1096 #define FIXTRANS_PIXEL_U (((y+h-1)%h)*w+x)
1097 #define FIXTRANS_PIXEL_D (((y+1)%h)*w+x)
1098 #define FIXTRANS_PIXEL_L (y*w+((x+w-1)%w))
1099 #define FIXTRANS_PIXEL_R (y*w+((x+1)%w))
1100
1101         memset(fixMask, 0, w * h);
1102         for(y = 0; y < h; ++y)
1103                 for(x = 0; x < w; ++x)
1104                 {
1105                         if(data[FIXTRANS_PIXEL * 4 + 3] == 0)
1106                         {
1107                                 fixMask[FIXTRANS_PIXEL] |= FIXTRANS_NEEDED;
1108                                 ++fixPixels;
1109                         }
1110                         else
1111                         {
1112                                 fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1113                                 fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1114                                 fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1115                                 fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1116                         }
1117                 }
1118         if(fixPixels == w * h)
1119                 return 0; // sorry, can't do anything about this
1120         while(fixPixels)
1121         {
1122                 for(y = 0; y < h; ++y)
1123                         for(x = 0; x < w; ++x)
1124                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_NEEDED)
1125                                 {
1126                                         unsigned int sumR = 0, sumG = 0, sumB = 0, sumA = 0, sumRA = 0, sumGA = 0, sumBA = 0, cnt = 0;
1127                                         unsigned char r, g, b, a, r0, g0, b0;
1128                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_U)
1129                                         {
1130                                                 r = data[FIXTRANS_PIXEL_U * 4 + 2];
1131                                                 g = data[FIXTRANS_PIXEL_U * 4 + 1];
1132                                                 b = data[FIXTRANS_PIXEL_U * 4 + 0];
1133                                                 a = data[FIXTRANS_PIXEL_U * 4 + 3];
1134                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1135                                         }
1136                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_D)
1137                                         {
1138                                                 r = data[FIXTRANS_PIXEL_D * 4 + 2];
1139                                                 g = data[FIXTRANS_PIXEL_D * 4 + 1];
1140                                                 b = data[FIXTRANS_PIXEL_D * 4 + 0];
1141                                                 a = data[FIXTRANS_PIXEL_D * 4 + 3];
1142                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1143                                         }
1144                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_L)
1145                                         {
1146                                                 r = data[FIXTRANS_PIXEL_L * 4 + 2];
1147                                                 g = data[FIXTRANS_PIXEL_L * 4 + 1];
1148                                                 b = data[FIXTRANS_PIXEL_L * 4 + 0];
1149                                                 a = data[FIXTRANS_PIXEL_L * 4 + 3];
1150                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1151                                         }
1152                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_R)
1153                                         {
1154                                                 r = data[FIXTRANS_PIXEL_R * 4 + 2];
1155                                                 g = data[FIXTRANS_PIXEL_R * 4 + 1];
1156                                                 b = data[FIXTRANS_PIXEL_R * 4 + 0];
1157                                                 a = data[FIXTRANS_PIXEL_R * 4 + 3];
1158                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1159                                         }
1160                                         if(!cnt)
1161                                                 continue;
1162                                         r0 = data[FIXTRANS_PIXEL * 4 + 2];
1163                                         g0 = data[FIXTRANS_PIXEL * 4 + 1];
1164                                         b0 = data[FIXTRANS_PIXEL * 4 + 0];
1165                                         if(sumA)
1166                                         {
1167                                                 // there is a surrounding non-alpha pixel
1168                                                 r = (sumRA + sumA / 2) / sumA;
1169                                                 g = (sumGA + sumA / 2) / sumA;
1170                                                 b = (sumBA + sumA / 2) / sumA;
1171                                         }
1172                                         else
1173                                         {
1174                                                 // need to use a "regular" average
1175                                                 r = (sumR + cnt / 2) / cnt;
1176                                                 g = (sumG + cnt / 2) / cnt;
1177                                                 b = (sumB + cnt / 2) / cnt;
1178                                         }
1179                                         if(r != r0 || g != g0 || b != b0)
1180                                                 ++changedPixels;
1181                                         data[FIXTRANS_PIXEL * 4 + 2] = r;
1182                                         data[FIXTRANS_PIXEL * 4 + 1] = g;
1183                                         data[FIXTRANS_PIXEL * 4 + 0] = b;
1184                                         fixMask[FIXTRANS_PIXEL] |= FIXTRANS_FIXED;
1185                                 }
1186                 for(y = 0; y < h; ++y)
1187                         for(x = 0; x < w; ++x)
1188                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_FIXED)
1189                                 {
1190                                         fixMask[FIXTRANS_PIXEL] &= ~(FIXTRANS_NEEDED | FIXTRANS_FIXED);
1191                                         fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1192                                         fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1193                                         fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1194                                         fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1195                                         --fixPixels;
1196                                 }
1197         }
1198         return changedPixels;
1199 }
1200
1201 void Image_FixTransparentPixels_f(void)
1202 {
1203         const char *filename, *filename_pattern;
1204         fssearch_t *search;
1205         int i, n;
1206         char outfilename[MAX_QPATH], buf[MAX_QPATH];
1207         unsigned char *data;
1208         if(Cmd_Argc() != 2)
1209         {
1210                 Con_Printf("Usage: %s imagefile\n", Cmd_Argv(0));
1211                 return;
1212         }
1213         filename_pattern = Cmd_Argv(1);
1214         search = FS_Search(filename_pattern, true, true);
1215         if(!search)
1216                 return;
1217         for(i = 0; i < search->numfilenames; ++i)
1218         {
1219                 filename = search->filenames[i];
1220                 Con_Printf("Processing %s... ", filename);
1221                 Image_StripImageExtension(filename, buf, sizeof(buf));
1222                 dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1223                 if(!(data = loadimagepixelsbgra(filename, true, false, false, NULL)))
1224                         return;
1225                 if((n = fixtransparentpixels(data, image_width, image_height)))
1226                 {
1227                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1228                         Con_Printf("%s written (%d pixels changed).\n", outfilename, n);
1229                 }
1230                 else
1231                         Con_Printf("unchanged.\n");
1232                 Mem_Free(data);
1233         }
1234         FS_FreeSearch(search);
1235 }
1236
1237 qboolean Image_WriteTGABGR_preflipped (const char *filename, int width, int height, const unsigned char *data)
1238 {
1239         qboolean ret;
1240         unsigned char buffer[18];
1241         const void *buffers[2];
1242         fs_offset_t sizes[2];
1243
1244         memset (buffer, 0, 18);
1245         buffer[2] = 2;          // uncompressed type
1246         buffer[12] = (width >> 0) & 0xFF;
1247         buffer[13] = (width >> 8) & 0xFF;
1248         buffer[14] = (height >> 0) & 0xFF;
1249         buffer[15] = (height >> 8) & 0xFF;
1250         buffer[16] = 24;        // pixel size
1251
1252         buffers[0] = buffer;
1253         sizes[0] = 18;
1254         buffers[1] = data;
1255         sizes[1] = width*height*3;
1256         ret = FS_WriteFileInBlocks(filename, buffers, sizes, 2);
1257
1258         return ret;
1259 }
1260
1261 qboolean Image_WriteTGABGRA (const char *filename, int width, int height, const unsigned char *data)
1262 {
1263         int y;
1264         unsigned char *buffer, *out;
1265         const unsigned char *in, *end;
1266         qboolean ret;
1267
1268         buffer = (unsigned char *)Mem_Alloc(tempmempool, width*height*4 + 18);
1269
1270         memset (buffer, 0, 18);
1271         buffer[2] = 2;          // uncompressed type
1272         buffer[12] = (width >> 0) & 0xFF;
1273         buffer[13] = (width >> 8) & 0xFF;
1274         buffer[14] = (height >> 0) & 0xFF;
1275         buffer[15] = (height >> 8) & 0xFF;
1276
1277         for (y = 3;y < width*height*4;y += 4)
1278                 if (data[y] < 255)
1279                         break;
1280
1281         if (y < width*height*4)
1282         {
1283                 // save the alpha channel
1284                 buffer[16] = 32;        // pixel size
1285                 buffer[17] = 8; // 8 bits of alpha
1286
1287                 // flip upside down
1288                 out = buffer + 18;
1289                 for (y = height - 1;y >= 0;y--)
1290                 {
1291                         memcpy(out, data + y * width * 4, width * 4);
1292                         out += width*4;
1293                 }
1294         }
1295         else
1296         {
1297                 // save only the color channels
1298                 buffer[16] = 24;        // pixel size
1299                 buffer[17] = 0; // 8 bits of alpha
1300
1301                 // truncate bgra to bgr and flip upside down
1302                 out = buffer + 18;
1303                 for (y = height - 1;y >= 0;y--)
1304                 {
1305                         in = data + y * width * 4;
1306                         end = in + width * 4;
1307                         for (;in < end;in += 4)
1308                         {
1309                                 *out++ = in[0];
1310                                 *out++ = in[1];
1311                                 *out++ = in[2];
1312                         }
1313                 }
1314         }
1315         ret = FS_WriteFile (filename, buffer, out - buffer);
1316
1317         Mem_Free(buffer);
1318
1319         return ret;
1320 }
1321
1322 static void Image_Resample32LerpLine (const unsigned char *in, unsigned char *out, int inwidth, int outwidth)
1323 {
1324         int             j, xi, oldx = 0, f, fstep, endx, lerp;
1325         fstep = (int) (inwidth*65536.0f/outwidth);
1326         endx = (inwidth-1);
1327         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
1328         {
1329                 xi = f >> 16;
1330                 if (xi != oldx)
1331                 {
1332                         in += (xi - oldx) * 4;
1333                         oldx = xi;
1334                 }
1335                 if (xi < endx)
1336                 {
1337                         lerp = f & 0xFFFF;
1338                         *out++ = (unsigned char) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
1339                         *out++ = (unsigned char) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
1340                         *out++ = (unsigned char) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
1341                         *out++ = (unsigned char) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
1342                 }
1343                 else // last pixel of the line has no pixel to lerp to
1344                 {
1345                         *out++ = in[0];
1346                         *out++ = in[1];
1347                         *out++ = in[2];
1348                         *out++ = in[3];
1349                 }
1350         }
1351 }
1352
1353 #define LERPBYTE(i) r = resamplerow1[i];out[i] = (unsigned char) ((((resamplerow2[i] - r) * lerp) >> 16) + r)
1354 static void Image_Resample32Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1355 {
1356         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
1357         unsigned char *out;
1358         const unsigned char *inrow;
1359         unsigned char *resamplerow1;
1360         unsigned char *resamplerow2;
1361         out = (unsigned char *)outdata;
1362         fstep = (int) (inheight*65536.0f/outheight);
1363
1364         resamplerow1 = (unsigned char *)Mem_Alloc(tempmempool, outwidth*4*2);
1365         resamplerow2 = resamplerow1 + outwidth*4;
1366
1367         inrow = (const unsigned char *)indata;
1368         oldy = 0;
1369         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1370         Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1371         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1372         {
1373                 yi = f >> 16;
1374                 if (yi < endy)
1375                 {
1376                         lerp = f & 0xFFFF;
1377                         if (yi != oldy)
1378                         {
1379                                 inrow = (unsigned char *)indata + inwidth4*yi;
1380                                 if (yi == oldy+1)
1381                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1382                                 else
1383                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1384                                 Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1385                                 oldy = yi;
1386                         }
1387                         j = outwidth - 4;
1388                         while(j >= 0)
1389                         {
1390                                 LERPBYTE( 0);
1391                                 LERPBYTE( 1);
1392                                 LERPBYTE( 2);
1393                                 LERPBYTE( 3);
1394                                 LERPBYTE( 4);
1395                                 LERPBYTE( 5);
1396                                 LERPBYTE( 6);
1397                                 LERPBYTE( 7);
1398                                 LERPBYTE( 8);
1399                                 LERPBYTE( 9);
1400                                 LERPBYTE(10);
1401                                 LERPBYTE(11);
1402                                 LERPBYTE(12);
1403                                 LERPBYTE(13);
1404                                 LERPBYTE(14);
1405                                 LERPBYTE(15);
1406                                 out += 16;
1407                                 resamplerow1 += 16;
1408                                 resamplerow2 += 16;
1409                                 j -= 4;
1410                         }
1411                         if (j & 2)
1412                         {
1413                                 LERPBYTE( 0);
1414                                 LERPBYTE( 1);
1415                                 LERPBYTE( 2);
1416                                 LERPBYTE( 3);
1417                                 LERPBYTE( 4);
1418                                 LERPBYTE( 5);
1419                                 LERPBYTE( 6);
1420                                 LERPBYTE( 7);
1421                                 out += 8;
1422                                 resamplerow1 += 8;
1423                                 resamplerow2 += 8;
1424                         }
1425                         if (j & 1)
1426                         {
1427                                 LERPBYTE( 0);
1428                                 LERPBYTE( 1);
1429                                 LERPBYTE( 2);
1430                                 LERPBYTE( 3);
1431                                 out += 4;
1432                                 resamplerow1 += 4;
1433                                 resamplerow2 += 4;
1434                         }
1435                         resamplerow1 -= outwidth4;
1436                         resamplerow2 -= outwidth4;
1437                 }
1438                 else
1439                 {
1440                         if (yi != oldy)
1441                         {
1442                                 inrow = (unsigned char *)indata + inwidth4*yi;
1443                                 if (yi == oldy+1)
1444                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1445                                 else
1446                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1447                                 oldy = yi;
1448                         }
1449                         memcpy(out, resamplerow1, outwidth4);
1450                 }
1451         }
1452
1453         Mem_Free(resamplerow1);
1454         resamplerow1 = NULL;
1455         resamplerow2 = NULL;
1456 }
1457
1458 static void Image_Resample32Nolerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1459 {
1460         int i, j;
1461         unsigned frac, fracstep;
1462         // relies on int being 4 bytes
1463         int *inrow, *out;
1464         out = (int *)outdata;
1465
1466         fracstep = inwidth*0x10000/outwidth;
1467         for (i = 0;i < outheight;i++)
1468         {
1469                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
1470                 frac = fracstep >> 1;
1471                 j = outwidth - 4;
1472                 while (j >= 0)
1473                 {
1474                         out[0] = inrow[frac >> 16];frac += fracstep;
1475                         out[1] = inrow[frac >> 16];frac += fracstep;
1476                         out[2] = inrow[frac >> 16];frac += fracstep;
1477                         out[3] = inrow[frac >> 16];frac += fracstep;
1478                         out += 4;
1479                         j -= 4;
1480                 }
1481                 if (j & 2)
1482                 {
1483                         out[0] = inrow[frac >> 16];frac += fracstep;
1484                         out[1] = inrow[frac >> 16];frac += fracstep;
1485                         out += 2;
1486                 }
1487                 if (j & 1)
1488                 {
1489                         out[0] = inrow[frac >> 16];frac += fracstep;
1490                         out += 1;
1491                 }
1492         }
1493 }
1494
1495 /*
1496 ================
1497 Image_Resample
1498 ================
1499 */
1500 void Image_Resample32(const void *indata, int inwidth, int inheight, int indepth, void *outdata, int outwidth, int outheight, int outdepth, int quality)
1501 {
1502         if (indepth != 1 || outdepth != 1)
1503         {
1504                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1505                 return;
1506         }
1507         if (quality)
1508                 Image_Resample32Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1509         else
1510                 Image_Resample32Nolerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1511 }
1512
1513 // in can be the same as out
1514 void Image_MipReduce32(const unsigned char *in, unsigned char *out, int *width, int *height, int *depth, int destwidth, int destheight, int destdepth)
1515 {
1516         const unsigned char *inrow;
1517         int x, y, nextrow;
1518         if (*depth != 1 || destdepth != 1)
1519         {
1520                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1521                 if (*width > destwidth)
1522                         *width >>= 1;
1523                 if (*height > destheight)
1524                         *height >>= 1;
1525                 if (*depth > destdepth)
1526                         *depth >>= 1;
1527                 return;
1528         }
1529         // note: if given odd width/height this discards the last row/column of
1530         // pixels, rather than doing a proper box-filter scale down
1531         inrow = in;
1532         nextrow = *width * 4;
1533         if (*width > destwidth)
1534         {
1535                 *width >>= 1;
1536                 if (*height > destheight)
1537                 {
1538                         // reduce both
1539                         *height >>= 1;
1540                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1541                         {
1542                                 for (in = inrow, x = 0;x < *width;x++)
1543                                 {
1544                                         out[0] = (unsigned char) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
1545                                         out[1] = (unsigned char) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
1546                                         out[2] = (unsigned char) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
1547                                         out[3] = (unsigned char) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
1548                                         out += 4;
1549                                         in += 8;
1550                                 }
1551                         }
1552                 }
1553                 else
1554                 {
1555                         // reduce width
1556                         for (y = 0;y < *height;y++, inrow += nextrow)
1557                         {
1558                                 for (in = inrow, x = 0;x < *width;x++)
1559                                 {
1560                                         out[0] = (unsigned char) ((in[0] + in[4]) >> 1);
1561                                         out[1] = (unsigned char) ((in[1] + in[5]) >> 1);
1562                                         out[2] = (unsigned char) ((in[2] + in[6]) >> 1);
1563                                         out[3] = (unsigned char) ((in[3] + in[7]) >> 1);
1564                                         out += 4;
1565                                         in += 8;
1566                                 }
1567                         }
1568                 }
1569         }
1570         else
1571         {
1572                 if (*height > destheight)
1573                 {
1574                         // reduce height
1575                         *height >>= 1;
1576                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1577                         {
1578                                 for (in = inrow, x = 0;x < *width;x++)
1579                                 {
1580                                         out[0] = (unsigned char) ((in[0] + in[nextrow  ]) >> 1);
1581                                         out[1] = (unsigned char) ((in[1] + in[nextrow+1]) >> 1);
1582                                         out[2] = (unsigned char) ((in[2] + in[nextrow+2]) >> 1);
1583                                         out[3] = (unsigned char) ((in[3] + in[nextrow+3]) >> 1);
1584                                         out += 4;
1585                                         in += 4;
1586                                 }
1587                         }
1588                 }
1589                 else
1590                         Con_Printf ("Image_MipReduce: desired size already achieved\n");
1591         }
1592 }
1593
1594 void Image_HeightmapToNormalmap_BGRA(const unsigned char *inpixels, unsigned char *outpixels, int width, int height, int clamp, float bumpscale)
1595 {
1596         int x, y, x1, x2, y1, y2;
1597         const unsigned char *b, *row[3];
1598         int p[5];
1599         unsigned char *out;
1600         float ibumpscale, n[3];
1601         ibumpscale = (255.0f * 6.0f) / bumpscale;
1602         out = outpixels;
1603         for (y = 0, y1 = height-1;y < height;y1 = y, y++)
1604         {
1605                 y2 = y + 1;if (y2 >= height) y2 = 0;
1606                 row[0] = inpixels + (y1 * width) * 4;
1607                 row[1] = inpixels + (y  * width) * 4;
1608                 row[2] = inpixels + (y2 * width) * 4;
1609                 for (x = 0, x1 = width-1;x < width;x1 = x, x++)
1610                 {
1611                         x2 = x + 1;if (x2 >= width) x2 = 0;
1612                         // left, right
1613                         b = row[1] + x1 * 4;p[0] = (b[0] + b[1] + b[2]);
1614                         b = row[1] + x2 * 4;p[1] = (b[0] + b[1] + b[2]);
1615                         // above, below
1616                         b = row[0] + x  * 4;p[2] = (b[0] + b[1] + b[2]);
1617                         b = row[2] + x  * 4;p[3] = (b[0] + b[1] + b[2]);
1618                         // center
1619                         b = row[1] + x  * 4;p[4] = (b[0] + b[1] + b[2]);
1620                         // calculate a normal from the slopes
1621                         n[0] = p[0] - p[1];
1622                         n[1] = p[3] - p[2];
1623                         n[2] = ibumpscale;
1624                         VectorNormalize(n);
1625                         // turn it into a dot3 rgb vector texture
1626                         out[2] = (int)(128.0f + n[0] * 127.0f);
1627                         out[1] = (int)(128.0f + n[1] * 127.0f);
1628                         out[0] = (int)(128.0f + n[2] * 127.0f);
1629                         out[3] = (p[4]) / 3;
1630                         out += 4;
1631                 }
1632         }
1633 }