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