Added a mempool parameter to FS_LoadFile
[divverent/darkplaces.git] / image.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "r_shadow.h"
6
7 int             image_width;
8 int             image_height;
9
10 void Image_CopyMux(qbyte *outpixels, const qbyte *inpixels, int width, int height, int flipx, int flipy, int flipdiagonal, int numincomponents, int numoutcomponents, int *inputcomponentindices)
11 {
12         int index, c, x, y;
13         const qbyte *in, *inrow, *incolumn;
14         if (flipdiagonal)
15         {
16                 for (y = 0;y < height;y++)
17                 {
18                         incolumn = inpixels + (flipx ? width - 1 - y : y) * numincomponents;
19                         for (x = 0;x < width;x++)
20                         {
21                                 in = incolumn + (flipy ? height - 1 - x : x) * width * numincomponents;
22                                 for (c = 0;c < numoutcomponents;c++)
23                                 {
24                                         index = inputcomponentindices[c];
25                                         *outpixels++ = (index & 0x80000000) ? (index - 0x8000000) : in[index];
26                                 }
27                         }
28                 }
29         }
30         else
31         {
32                 for (y = 0;y < height;y++)
33                 {
34                         inrow = inpixels + (flipy ? height - 1 - y : y) * width * numincomponents;
35                         for (x = 0;x < width;x++)
36                         {
37                                 in = inrow + (flipx ? width - 1 - x : x) * numincomponents;
38                                 for (c = 0;c < numoutcomponents;c++)
39                                 {
40                                         index = inputcomponentindices[c];
41                                         *outpixels++ = (index & 0x80000000) ? (index - 0x8000000) : in[index];
42                                 }
43                         }
44                 }
45         }
46 }
47
48 void Image_GammaRemapRGB(const qbyte *in, qbyte *out, int pixels, const qbyte *gammar, const qbyte *gammag, const qbyte *gammab)
49 {
50         while (pixels--)
51         {
52                 out[0] = gammar[in[0]];
53                 out[1] = gammag[in[1]];
54                 out[2] = gammab[in[2]];
55                 in += 3;
56                 out += 3;
57         }
58 }
59
60 // note: pal must be 32bit color
61 void Image_Copy8bitRGBA(const qbyte *in, qbyte *out, int pixels, const unsigned int *pal)
62 {
63         int *iout = (void *)out;
64         while (pixels >= 8)
65         {
66                 iout[0] = pal[in[0]];
67                 iout[1] = pal[in[1]];
68                 iout[2] = pal[in[2]];
69                 iout[3] = pal[in[3]];
70                 iout[4] = pal[in[4]];
71                 iout[5] = pal[in[5]];
72                 iout[6] = pal[in[6]];
73                 iout[7] = pal[in[7]];
74                 in += 8;
75                 iout += 8;
76                 pixels -= 8;
77         }
78         if (pixels & 4)
79         {
80                 iout[0] = pal[in[0]];
81                 iout[1] = pal[in[1]];
82                 iout[2] = pal[in[2]];
83                 iout[3] = pal[in[3]];
84                 in += 4;
85                 iout += 4;
86         }
87         if (pixels & 2)
88         {
89                 iout[0] = pal[in[0]];
90                 iout[1] = pal[in[1]];
91                 in += 2;
92                 iout += 2;
93         }
94         if (pixels & 1)
95                 iout[0] = pal[in[0]];
96 }
97
98 /*
99 =================================================================
100
101   PCX Loading
102
103 =================================================================
104 */
105
106 typedef struct
107 {
108     char        manufacturer;
109     char        version;
110     char        encoding;
111     char        bits_per_pixel;
112     unsigned short      xmin,ymin,xmax,ymax;
113     unsigned short      hres,vres;
114     unsigned char       palette[48];
115     char        reserved;
116     char        color_planes;
117     unsigned short      bytes_per_line;
118     unsigned short      palette_type;
119     char        filler[58];
120 } pcx_t;
121
122 /*
123 ============
124 LoadPCX
125 ============
126 */
127 qbyte* LoadPCX (qbyte *f, int matchwidth, int matchheight)
128 {
129         pcx_t pcx;
130         qbyte *a, *b, *image_rgba, *pbuf;
131         const qbyte *palette, *fin, *enddata;
132         int x, y, x2, dataByte;
133
134         if (fs_filesize < (int)sizeof(pcx) + 768)
135         {
136                 Con_Print("Bad pcx file\n");
137                 return NULL;
138         }
139
140         fin = f;
141
142         memcpy(&pcx, fin, sizeof(pcx));
143         fin += sizeof(pcx);
144
145         // LordHavoc: big-endian support ported from QF newtree
146         pcx.xmax = LittleShort (pcx.xmax);
147         pcx.xmin = LittleShort (pcx.xmin);
148         pcx.ymax = LittleShort (pcx.ymax);
149         pcx.ymin = LittleShort (pcx.ymin);
150         pcx.hres = LittleShort (pcx.hres);
151         pcx.vres = LittleShort (pcx.vres);
152         pcx.bytes_per_line = LittleShort (pcx.bytes_per_line);
153         pcx.palette_type = LittleShort (pcx.palette_type);
154
155         image_width = pcx.xmax + 1 - pcx.xmin;
156         image_height = pcx.ymax + 1 - pcx.ymin;
157         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)
158         {
159                 Con_Print("Bad pcx file\n");
160                 return NULL;
161         }
162         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
163                 return NULL;
164
165         palette = f + fs_filesize - 768;
166
167         image_rgba = Mem_Alloc(tempmempool, image_width*image_height*4);
168         if (!image_rgba)
169         {
170                 Con_Printf("LoadPCX: not enough memory for %i by %i image\n", image_width, image_height);
171                 return NULL;
172         }
173         pbuf = image_rgba + image_width*image_height*3;
174         enddata = palette;
175
176         for (y = 0;y < image_height && fin < enddata;y++)
177         {
178                 a = pbuf + y * image_width;
179                 for (x = 0;x < image_width && fin < enddata;)
180                 {
181                         dataByte = *fin++;
182                         if(dataByte >= 0xC0)
183                         {
184                                 if (fin >= enddata)
185                                         break;
186                                 x2 = x + (dataByte & 0x3F);
187                                 dataByte = *fin++;
188                                 if (x2 > image_width)
189                                         x2 = image_width; // technically an error
190                                 while(x < x2)
191                                         a[x++] = dataByte;
192                         }
193                         else
194                                 a[x++] = dataByte;
195                 }
196                 fin += pcx.bytes_per_line - image_width; // the number of bytes per line is always forced to an even number
197                 while(x < image_width)
198                         a[x++] = 0;
199         }
200
201         a = image_rgba;
202         b = pbuf;
203
204         for(x = 0;x < image_width*image_height;x++)
205         {
206                 y = *b++ * 3;
207                 *a++ = palette[y];
208                 *a++ = palette[y+1];
209                 *a++ = palette[y+2];
210                 *a++ = 255;
211         }
212
213         return image_rgba;
214 }
215
216 /*
217 =========================================================
218
219 TARGA LOADING
220
221 =========================================================
222 */
223
224 typedef struct _TargaHeader
225 {
226         unsigned char   id_length, colormap_type, image_type;
227         unsigned short  colormap_index, colormap_length;
228         unsigned char   colormap_size;
229         unsigned short  x_origin, y_origin, width, height;
230         unsigned char   pixel_size, attributes;
231 }
232 TargaHeader;
233
234 void PrintTargaHeader(TargaHeader *t)
235 {
236         Con_Print("TargaHeader:\n");
237         Con_Printf("uint8 id_length = %i;\n", t->id_length);
238         Con_Printf("uint8 colormap_type = %i;\n", t->colormap_type);
239         Con_Printf("uint8 image_type = %i;\n", t->image_type);
240         Con_Printf("uint16 colormap_index = %i;\n", t->colormap_index);
241         Con_Printf("uint16 colormap_length = %i;\n", t->colormap_length);
242         Con_Printf("uint8 colormap_size = %i;\n", t->colormap_size);
243         Con_Printf("uint16 x_origin = %i;\n", t->x_origin);
244         Con_Printf("uint16 y_origin = %i;\n", t->y_origin);
245         Con_Printf("uint16 width = %i;\n", t->width);
246         Con_Printf("uint16 height = %i;\n", t->height);
247         Con_Printf("uint8 pixel_size = %i;\n", t->pixel_size);
248         Con_Printf("uint8 attributes = %i;\n", t->attributes);
249 }
250
251 /*
252 =============
253 LoadTGA
254 =============
255 */
256 qbyte *LoadTGA (qbyte *f, int matchwidth, int matchheight)
257 {
258         int x, y, row_inc, compressed, readpixelcount, red, green, blue, alpha, runlen, pindex;
259         qbyte *pixbuf, *image_rgba;
260         qbyte *fin, *enddata;
261         TargaHeader targa_header;
262         unsigned char palette[256*4], *p;
263
264         if (fs_filesize < 19)
265                 return NULL;
266
267         enddata = f + fs_filesize;
268
269         targa_header.id_length = f[0];
270         targa_header.colormap_type = f[1];
271         targa_header.image_type = f[2];
272
273         targa_header.colormap_index = f[3] + f[4] * 256;
274         targa_header.colormap_length = f[5] + f[6] * 256;
275         targa_header.colormap_size = f[7];
276         targa_header.x_origin = f[8] + f[9] * 256;
277         targa_header.y_origin = f[10] + f[11] * 256;
278         targa_header.width = image_width = f[12] + f[13] * 256;
279         targa_header.height = image_height = f[14] + f[15] * 256;
280         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
281         {
282                 Con_Print("LoadTGA: invalid size\n");
283                 PrintTargaHeader(&targa_header);
284                 return NULL;
285         }
286         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
287                 return NULL;
288         targa_header.pixel_size = f[16];
289         targa_header.attributes = f[17];
290
291         fin = f + 18;
292         if (targa_header.id_length != 0)
293                 fin += targa_header.id_length;  // skip TARGA image comment
294         if (targa_header.image_type == 2 || targa_header.image_type == 10)
295         {
296                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
297                 {
298                         Con_Print("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
299                         PrintTargaHeader(&targa_header);
300                         return NULL;
301                 }
302         }
303         else if (targa_header.image_type == 1 || targa_header.image_type == 9)
304         {
305                 if (targa_header.pixel_size != 8)
306                 {
307                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
308                         PrintTargaHeader(&targa_header);
309                         return NULL;
310                 }
311                 if (targa_header.colormap_length > 256)
312                 {
313                         Con_Print("LoadTGA: only up to 256 colormap_length supported\n");
314                         PrintTargaHeader(&targa_header);
315                         return NULL;
316                 }
317                 if (targa_header.colormap_index)
318                 {
319                         Con_Print("LoadTGA: colormap_index not supported\n");
320                         PrintTargaHeader(&targa_header);
321                         return NULL;
322                 }
323                 if (targa_header.colormap_size == 24)
324                 {
325                         for (x = 0;x < targa_header.colormap_length;x++)
326                         {
327                                 palette[x*4+2] = *fin++;
328                                 palette[x*4+1] = *fin++;
329                                 palette[x*4+0] = *fin++;
330                                 palette[x*4+3] = 255;
331                         }
332                 }
333                 else if (targa_header.colormap_size == 32)
334                 {
335                         for (x = 0;x < targa_header.colormap_length;x++)
336                         {
337                                 palette[x*4+2] = *fin++;
338                                 palette[x*4+1] = *fin++;
339                                 palette[x*4+0] = *fin++;
340                                 palette[x*4+3] = *fin++;
341                         }
342                 }
343                 else
344                 {
345                         Con_Print("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
346                         PrintTargaHeader(&targa_header);
347                         return NULL;
348                 }
349         }
350         else if (targa_header.image_type == 3 || targa_header.image_type == 11)
351         {
352                 if (targa_header.pixel_size != 8)
353                 {
354                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
355                         PrintTargaHeader(&targa_header);
356                         return NULL;
357                 }
358         }
359         else
360         {
361                 Con_Printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
362                 PrintTargaHeader(&targa_header);
363                 return NULL;
364         }
365
366         if (targa_header.attributes & 0x10)
367         {
368                 Con_Print("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
369                 return NULL;
370         }
371
372         image_rgba = Mem_Alloc(tempmempool, image_width * image_height * 4);
373         if (!image_rgba)
374         {
375                 Con_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
376                 return NULL;
377         }
378
379         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
380         if ((targa_header.attributes & 0x20) == 0)
381         {
382                 pixbuf = image_rgba + (image_height - 1)*image_width*4;
383                 row_inc = -image_width*4*2;
384         }
385         else
386         {
387                 pixbuf = image_rgba;
388                 row_inc = 0;
389         }
390
391         compressed = targa_header.image_type == 9 || targa_header.image_type == 10 || targa_header.image_type == 11;
392         x = 0;
393         y = 0;
394         red = green = blue = alpha = 255;
395         while (y < image_height)
396         {
397                 // decoder is mostly the same whether it's compressed or not
398                 readpixelcount = 1000000;
399                 runlen = 1000000;
400                 if (compressed && fin < enddata)
401                 {
402                         runlen = *fin++;
403                         // high bit indicates this is an RLE compressed run
404                         if (runlen & 0x80)
405                                 readpixelcount = 1;
406                         runlen = 1 + (runlen & 0x7f);
407                 }
408
409                 while((runlen--) && y < image_height)
410                 {
411                         if (readpixelcount > 0)
412                         {
413                                 readpixelcount--;
414                                 red = green = blue = alpha = 255;
415                                 if (fin < enddata)
416                                 {
417                                         switch(targa_header.image_type)
418                                         {
419                                         case 1:
420                                         case 9:
421                                                 // colormapped
422                                                 pindex = *fin++;
423                                                 if (pindex >= targa_header.colormap_length)
424                                                         pindex = 0; // error
425                                                 p = palette + pindex * 4;
426                                                 red = p[0];
427                                                 green = p[1];
428                                                 blue = p[2];
429                                                 alpha = p[3];
430                                                 break;
431                                         case 2:
432                                         case 10:
433                                                 // BGR or BGRA
434                                                 blue = *fin++;
435                                                 if (fin < enddata)
436                                                         green = *fin++;
437                                                 if (fin < enddata)
438                                                         red = *fin++;
439                                                 if (targa_header.pixel_size == 32 && fin < enddata)
440                                                         alpha = *fin++;
441                                                 break;
442                                         case 3:
443                                         case 11:
444                                                 // greyscale
445                                                 red = green = blue = *fin++;
446                                                 break;
447                                         }
448                                 }
449                         }
450                         *pixbuf++ = red;
451                         *pixbuf++ = green;
452                         *pixbuf++ = blue;
453                         *pixbuf++ = alpha;
454                         x++;
455                         if (x == image_width)
456                         {
457                                 // end of line, advance to next
458                                 x = 0;
459                                 y++;
460                                 pixbuf += row_inc;
461                         }
462                 }
463         }
464
465         return image_rgba;
466 }
467
468 /*
469 ============
470 LoadLMP
471 ============
472 */
473 qbyte *LoadLMP (qbyte *f, int matchwidth, int matchheight)
474 {
475         qbyte *image_rgba;
476
477         if (fs_filesize < 9)
478         {
479                 Con_Print("LoadLMP: invalid LMP file\n");
480                 return NULL;
481         }
482
483         // parse the very complicated header *chuckle*
484         image_width = f[0] + f[1] * 256 + f[2] * 65536 + f[3] * 16777216;
485         image_height = f[4] + f[5] * 256 + f[6] * 65536 + f[7] * 16777216;
486         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
487         {
488                 Con_Printf("LoadLMP: invalid size %ix%i\n", image_width, image_height);
489                 return NULL;
490         }
491         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
492                 return NULL;
493
494         if (fs_filesize < 8 + image_width * image_height)
495         {
496                 Con_Print("LoadLMP: invalid LMP file\n");
497                 return NULL;
498         }
499
500         image_rgba = Mem_Alloc(tempmempool, image_width * image_height * 4);
501         if (!image_rgba)
502         {
503                 Con_Printf("LoadLMP: not enough memory for %i by %i image\n", image_width, image_height);
504                 return NULL;
505         }
506         Image_Copy8bitRGBA(f + 8, image_rgba, image_width * image_height, palette_complete);
507         return image_rgba;
508 }
509
510 typedef struct
511 {
512         char            name[32];
513         unsigned        width, height;
514         unsigned        offsets[MIPLEVELS];             // four mip maps stored
515         char            animname[32];                   // next frame in animation chain
516         int                     flags;
517         int                     contents;
518         int                     value;
519 } q2wal_t;
520
521 qbyte *LoadWAL (qbyte *f, int matchwidth, int matchheight)
522 {
523         qbyte *image_rgba;
524         const q2wal_t *inwal = (const void *)f;
525
526         if (fs_filesize < (int) sizeof(q2wal_t))
527         {
528                 Con_Print("LoadWAL: invalid WAL file\n");
529                 return NULL;
530         }
531
532         image_width = LittleLong(inwal->width);
533         image_height = LittleLong(inwal->height);
534         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
535         {
536                 Con_Printf("LoadWAL: invalid size %ix%i\n", image_width, image_height);
537                 return NULL;
538         }
539         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
540                 return NULL;
541
542         if ((int) fs_filesize < (int) sizeof(q2wal_t) + (int) LittleLong(inwal->offsets[0]) + image_width * image_height)
543         {
544                 Con_Print("LoadWAL: invalid WAL file\n");
545                 return NULL;
546         }
547
548         image_rgba = Mem_Alloc(tempmempool, image_width * image_height * 4);
549         if (!image_rgba)
550         {
551                 Con_Printf("LoadLMP: not enough memory for %i by %i image\n", image_width, image_height);
552                 return NULL;
553         }
554         Image_Copy8bitRGBA(f + LittleLong(inwal->offsets[0]), image_rgba, image_width * image_height, palette_complete);
555         return image_rgba;
556 }
557
558
559
560 /*
561 ============
562 LoadLMP
563 ============
564 */
565 qbyte *LoadLMPAs8Bit (qbyte *f, int matchwidth, int matchheight)
566 {
567         qbyte *image_8bit;
568
569         if (fs_filesize < 9)
570         {
571                 Con_Print("LoadLMPAs8Bit: invalid LMP file\n");
572                 return NULL;
573         }
574
575         // parse the very complicated header *chuckle*
576         image_width = f[0] + f[1] * 256 + f[2] * 65536 + f[3] * 16777216;
577         image_height = f[4] + f[5] * 256 + f[6] * 65536 + f[7] * 16777216;
578         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
579         {
580                 Con_Printf("LoadLMPAs8Bit: invalid size %ix%i\n", image_width, image_height);
581                 return NULL;
582         }
583         if ((matchwidth && image_width != matchwidth) || (matchheight && image_height != matchheight))
584                 return NULL;
585
586         if (fs_filesize < 8 + image_width * image_height)
587         {
588                 Con_Print("LoadLMPAs8Bit: invalid LMP file\n");
589                 return NULL;
590         }
591
592         image_8bit = Mem_Alloc(tempmempool, image_width * image_height);
593         if (!image_8bit)
594         {
595                 Con_Printf("LoadLMPAs8Bit: not enough memory for %i by %i image\n", image_width, image_height);
596                 return NULL;
597         }
598         memcpy(image_8bit, f + 8, image_width * image_height);
599         return image_8bit;
600 }
601
602 void Image_StripImageExtension (const char *in, char *out)
603 {
604         const char *end, *temp;
605         end = in + strlen(in);
606         if ((end - in) >= 4)
607         {
608                 temp = end - 4;
609                 if (strcmp(temp, ".tga") == 0
610                  || strcmp(temp, ".pcx") == 0
611                  || strcmp(temp, ".lmp") == 0
612                  || strcmp(temp, ".png") == 0
613                  || strcmp(temp, ".jpg") == 0)
614                         end = temp;
615                 while (in < end)
616                         *out++ = *in++;
617                 *out++ = 0;
618         }
619         else
620                 strcpy(out, in);
621 }
622
623 struct
624 {
625         const char *formatstring;
626         qbyte *(*loadfunc)(qbyte *f, int matchwidth, int matchheight);
627 }
628 imageformats[] =
629 {
630         {"override/%s.tga", LoadTGA},
631         {"override/%s.jpg", JPEG_LoadImage},
632         {"textures/%s.tga", LoadTGA},
633         {"textures/%s.jpg", JPEG_LoadImage},
634         {"textures/%s.pcx", LoadPCX},
635         {"textures/%s.wal", LoadWAL},
636         {"%s.tga", LoadTGA},
637         {"%s.jpg", JPEG_LoadImage},
638         {"%s.pcx", LoadPCX},
639         {"%s.lmp", LoadLMP},
640         {NULL, NULL}
641 };
642
643 qbyte *loadimagepixels (const char *filename, qboolean complain, int matchwidth, int matchheight)
644 {
645         int i;
646         qbyte *f, *data = NULL;
647         char basename[MAX_QPATH], name[MAX_QPATH], *c;
648         if (developer_memorydebug.integer)
649                 Mem_CheckSentinelsGlobal();
650         Image_StripImageExtension(filename, basename); // strip filename extensions to allow replacement by other types
651         // replace *'s with #, so commandline utils don't get confused when dealing with the external files
652         for (c = basename;*c;c++)
653                 if (*c == '*')
654                         *c = '#';
655         for (i = 0;imageformats[i].formatstring;i++)
656         {
657                 sprintf (name, imageformats[i].formatstring, basename);
658                 f = FS_LoadFile(name, tempmempool, true);
659                 if (f)
660                 {
661                         data = imageformats[i].loadfunc(f, matchwidth, matchheight);
662                         Mem_Free(f);
663                         if (data)
664                         {
665                                 Con_DPrintf("loaded image %s (%dx%d)\n", name, image_width, image_height);
666                                 if (developer_memorydebug.integer)
667                                         Mem_CheckSentinelsGlobal();
668                                 return data;
669                         }
670                 }
671         }
672         if (complain)
673         {
674                 Con_Printf("Couldn't load %s using ", filename);
675                 for (i = 0;imageformats[i].formatstring;i++)
676                 {
677                         sprintf (name, imageformats[i].formatstring, basename);
678                         Con_Printf(i == 0 ? "\"%s\"" : (imageformats[i+1].formatstring ? ", \"%s\"" : " or \"%s\".\n"), imageformats[i].formatstring);
679                 }
680         }
681         if (developer_memorydebug.integer)
682                 Mem_CheckSentinelsGlobal();
683         return NULL;
684 }
685
686 int image_makemask (const qbyte *in, qbyte *out, int size)
687 {
688         int i, count;
689         count = 0;
690         for (i = 0;i < size;i++)
691         {
692                 out[0] = out[1] = out[2] = 255;
693                 out[3] = in[3];
694                 if (in[3] != 255)
695                         count++;
696                 in += 4;
697                 out += 4;
698         }
699         return count;
700 }
701
702 qbyte* loadimagepixelsmask (const char *filename, qboolean complain, int matchwidth, int matchheight)
703 {
704         qbyte *in, *data;
705         in = data = loadimagepixels(filename, complain, matchwidth, matchheight);
706         if (!data)
707                 return NULL;
708         if (image_makemask(data, data, image_width * image_height))
709                 return data; // some transparency
710         else
711         {
712                 Mem_Free(data);
713                 return NULL; // all opaque
714         }
715 }
716
717 rtexture_t *loadtextureimage (rtexturepool_t *pool, const char *filename, int matchwidth, int matchheight, qboolean complain, int flags)
718 {
719         qbyte *data;
720         rtexture_t *rt;
721         if (!(data = loadimagepixels (filename, complain, matchwidth, matchheight)))
722                 return 0;
723         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, TEXTYPE_RGBA, flags, NULL);
724         Mem_Free(data);
725         return rt;
726 }
727
728 rtexture_t *loadtextureimagemask (rtexturepool_t *pool, const char *filename, int matchwidth, int matchheight, qboolean complain, int flags)
729 {
730         qbyte *data;
731         rtexture_t *rt;
732         if (!(data = loadimagepixelsmask (filename, complain, matchwidth, matchheight)))
733                 return 0;
734         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, TEXTYPE_RGBA, flags, NULL);
735         Mem_Free(data);
736         return rt;
737 }
738
739 rtexture_t *image_masktex;
740 rtexture_t *image_nmaptex;
741 rtexture_t *loadtextureimagewithmask (rtexturepool_t *pool, const char *filename, int matchwidth, int matchheight, qboolean complain, int flags)
742 {
743         qbyte *data;
744         rtexture_t *rt;
745         image_masktex = NULL;
746         image_nmaptex = NULL;
747         if (!(data = loadimagepixels (filename, complain, matchwidth, matchheight)))
748                 return 0;
749
750         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, TEXTYPE_RGBA, flags, NULL);
751
752         if (flags & TEXF_ALPHA && image_makemask(data, data, image_width * image_height))
753                 image_masktex = R_LoadTexture2D(pool, va("%s_mask", filename), image_width, image_height, data, TEXTYPE_RGBA, flags, NULL);
754
755         Mem_Free(data);
756         return rt;
757 }
758
759 rtexture_t *loadtextureimagewithmaskandnmap (rtexturepool_t *pool, const char *filename, int matchwidth, int matchheight, qboolean complain, int flags, float bumpscale)
760 {
761         qbyte *data, *data2;
762         rtexture_t *rt;
763         image_masktex = NULL;
764         image_nmaptex = NULL;
765         if (!(data = loadimagepixels (filename, complain, matchwidth, matchheight)))
766                 return 0;
767
768         data2 = Mem_Alloc(tempmempool, image_width * image_height * 4);
769
770         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, TEXTYPE_RGBA, flags, NULL);
771
772         Image_HeightmapToNormalmap(data, data2, image_width, image_height, (flags & TEXF_CLAMP) != 0, bumpscale);
773         image_nmaptex = R_LoadTexture2D(pool, va("%s_nmap", filename), image_width, image_height, data2, TEXTYPE_RGBA, flags, NULL);
774
775         if (flags & TEXF_ALPHA && image_makemask(data, data2, image_width * image_height))
776                 image_masktex = R_LoadTexture2D(pool, va("%s_mask", filename), image_width, image_height, data2, TEXTYPE_RGBA, flags, NULL);
777
778         Mem_Free(data2);
779
780         Mem_Free(data);
781         return rt;
782 }
783
784 rtexture_t *loadtextureimagebumpasnmap (rtexturepool_t *pool, const char *filename, int matchwidth, int matchheight, qboolean complain, int flags, float bumpscale)
785 {
786         qbyte *data, *data2;
787         rtexture_t *rt;
788         if (!(data = loadimagepixels (filename, complain, matchwidth, matchheight)))
789                 return 0;
790         data2 = Mem_Alloc(tempmempool, image_width * image_height * 4);
791
792         Image_HeightmapToNormalmap(data, data2, image_width, image_height, (flags & TEXF_CLAMP) != 0, bumpscale);
793         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data2, TEXTYPE_RGBA, flags, NULL);
794
795         Mem_Free(data2);
796         Mem_Free(data);
797         return rt;
798 }
799
800 qboolean Image_WriteTGARGB_preflipped (const char *filename, int width, int height, const qbyte *data)
801 {
802         qboolean ret;
803         qbyte *buffer, *out;
804         const qbyte *in, *end;
805
806         buffer = Mem_Alloc(tempmempool, width*height*3 + 18);
807
808         memset (buffer, 0, 18);
809         buffer[2] = 2;          // uncompressed type
810         buffer[12] = (width >> 0) & 0xFF;
811         buffer[13] = (width >> 8) & 0xFF;
812         buffer[14] = (height >> 0) & 0xFF;
813         buffer[15] = (height >> 8) & 0xFF;
814         buffer[16] = 24;        // pixel size
815
816         // swap rgb to bgr
817         in = data;
818         out = buffer + 18;
819         end = in + width*height*3;
820         for (;in < end;in += 3)
821         {
822                 *out++ = in[2];
823                 *out++ = in[1];
824                 *out++ = in[0];
825         }
826         ret = FS_WriteFile (filename, buffer, width*height*3 + 18 );
827
828         Mem_Free(buffer);
829         return ret;
830 }
831
832 void Image_WriteTGARGB (const char *filename, int width, int height, const qbyte *data)
833 {
834         int y;
835         qbyte *buffer, *out;
836         const qbyte *in, *end;
837
838         buffer = Mem_Alloc(tempmempool, width*height*3 + 18);
839
840         memset (buffer, 0, 18);
841         buffer[2] = 2;          // uncompressed type
842         buffer[12] = (width >> 0) & 0xFF;
843         buffer[13] = (width >> 8) & 0xFF;
844         buffer[14] = (height >> 0) & 0xFF;
845         buffer[15] = (height >> 8) & 0xFF;
846         buffer[16] = 24;        // pixel size
847
848         // swap rgb to bgr and flip upside down
849         out = buffer + 18;
850         for (y = height - 1;y >= 0;y--)
851         {
852                 in = data + y * width * 3;
853                 end = in + width * 3;
854                 for (;in < end;in += 3)
855                 {
856                         *out++ = in[2];
857                         *out++ = in[1];
858                         *out++ = in[0];
859                 }
860         }
861         FS_WriteFile (filename, buffer, width*height*3 + 18 );
862
863         Mem_Free(buffer);
864 }
865
866 void Image_WriteTGARGBA (const char *filename, int width, int height, const qbyte *data)
867 {
868         int y;
869         qbyte *buffer, *out;
870         const qbyte *in, *end;
871
872         buffer = Mem_Alloc(tempmempool, width*height*4 + 18);
873
874         memset (buffer, 0, 18);
875         buffer[2] = 2;          // uncompressed type
876         buffer[12] = (width >> 0) & 0xFF;
877         buffer[13] = (width >> 8) & 0xFF;
878         buffer[14] = (height >> 0) & 0xFF;
879         buffer[15] = (height >> 8) & 0xFF;
880         buffer[16] = 32;        // pixel size
881
882         // swap rgba to bgra and flip upside down
883         out = buffer + 18;
884         for (y = height - 1;y >= 0;y--)
885         {
886                 in = data + y * width * 4;
887                 end = in + width * 4;
888                 for (;in < end;in += 4)
889                 {
890                         *out++ = in[2];
891                         *out++ = in[1];
892                         *out++ = in[0];
893                         *out++ = in[3];
894                 }
895         }
896         FS_WriteFile (filename, buffer, width*height*4 + 18 );
897
898         Mem_Free(buffer);
899 }
900
901 qboolean Image_CheckAlpha(const qbyte *data, int size, qboolean rgba)
902 {
903         const qbyte *end;
904         if (rgba)
905         {
906                 // check alpha bytes
907                 for (end = data + size * 4, data += 3;data < end;data += 4)
908                         if (*data < 255)
909                                 return 1;
910         }
911         else
912         {
913                 // color 255 is transparent
914                 for (end = data + size;data < end;data++)
915                         if (*data == 255)
916                                 return 1;
917         }
918         return 0;
919 }
920
921 static void Image_Resample32LerpLine (const qbyte *in, qbyte *out, int inwidth, int outwidth)
922 {
923         int             j, xi, oldx = 0, f, fstep, endx, lerp;
924         fstep = (int) (inwidth*65536.0f/outwidth);
925         endx = (inwidth-1);
926         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
927         {
928                 xi = f >> 16;
929                 if (xi != oldx)
930                 {
931                         in += (xi - oldx) * 4;
932                         oldx = xi;
933                 }
934                 if (xi < endx)
935                 {
936                         lerp = f & 0xFFFF;
937                         *out++ = (qbyte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
938                         *out++ = (qbyte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
939                         *out++ = (qbyte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
940                         *out++ = (qbyte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
941                 }
942                 else // last pixel of the line has no pixel to lerp to
943                 {
944                         *out++ = in[0];
945                         *out++ = in[1];
946                         *out++ = in[2];
947                         *out++ = in[3];
948                 }
949         }
950 }
951
952 static void Image_Resample24LerpLine (const qbyte *in, qbyte *out, int inwidth, int outwidth)
953 {
954         int             j, xi, oldx = 0, f, fstep, endx, lerp;
955         fstep = (int) (inwidth*65536.0f/outwidth);
956         endx = (inwidth-1);
957         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
958         {
959                 xi = f >> 16;
960                 if (xi != oldx)
961                 {
962                         in += (xi - oldx) * 3;
963                         oldx = xi;
964                 }
965                 if (xi < endx)
966                 {
967                         lerp = f & 0xFFFF;
968                         *out++ = (qbyte) ((((in[3] - in[0]) * lerp) >> 16) + in[0]);
969                         *out++ = (qbyte) ((((in[4] - in[1]) * lerp) >> 16) + in[1]);
970                         *out++ = (qbyte) ((((in[5] - in[2]) * lerp) >> 16) + in[2]);
971                 }
972                 else // last pixel of the line has no pixel to lerp to
973                 {
974                         *out++ = in[0];
975                         *out++ = in[1];
976                         *out++ = in[2];
977                 }
978         }
979 }
980
981 int resamplerowsize = 0;
982 qbyte *resamplerow1 = NULL;
983 qbyte *resamplerow2 = NULL;
984 mempool_t *resamplemempool = NULL;
985
986 #define LERPBYTE(i) r = resamplerow1[i];out[i] = (qbyte) ((((resamplerow2[i] - r) * lerp) >> 16) + r)
987 void Image_Resample32Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
988 {
989         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
990         qbyte *out;
991         const qbyte *inrow;
992         out = outdata;
993         fstep = (int) (inheight*65536.0f/outheight);
994
995         inrow = indata;
996         oldy = 0;
997         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
998         Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
999         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1000         {
1001                 yi = f >> 16;
1002                 if (yi < endy)
1003                 {
1004                         lerp = f & 0xFFFF;
1005                         if (yi != oldy)
1006                         {
1007                                 inrow = (qbyte *)indata + inwidth4*yi;
1008                                 if (yi == oldy+1)
1009                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1010                                 else
1011                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1012                                 Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1013                                 oldy = yi;
1014                         }
1015                         j = outwidth - 4;
1016                         while(j >= 0)
1017                         {
1018                                 LERPBYTE( 0);
1019                                 LERPBYTE( 1);
1020                                 LERPBYTE( 2);
1021                                 LERPBYTE( 3);
1022                                 LERPBYTE( 4);
1023                                 LERPBYTE( 5);
1024                                 LERPBYTE( 6);
1025                                 LERPBYTE( 7);
1026                                 LERPBYTE( 8);
1027                                 LERPBYTE( 9);
1028                                 LERPBYTE(10);
1029                                 LERPBYTE(11);
1030                                 LERPBYTE(12);
1031                                 LERPBYTE(13);
1032                                 LERPBYTE(14);
1033                                 LERPBYTE(15);
1034                                 out += 16;
1035                                 resamplerow1 += 16;
1036                                 resamplerow2 += 16;
1037                                 j -= 4;
1038                         }
1039                         if (j & 2)
1040                         {
1041                                 LERPBYTE( 0);
1042                                 LERPBYTE( 1);
1043                                 LERPBYTE( 2);
1044                                 LERPBYTE( 3);
1045                                 LERPBYTE( 4);
1046                                 LERPBYTE( 5);
1047                                 LERPBYTE( 6);
1048                                 LERPBYTE( 7);
1049                                 out += 8;
1050                                 resamplerow1 += 8;
1051                                 resamplerow2 += 8;
1052                         }
1053                         if (j & 1)
1054                         {
1055                                 LERPBYTE( 0);
1056                                 LERPBYTE( 1);
1057                                 LERPBYTE( 2);
1058                                 LERPBYTE( 3);
1059                                 out += 4;
1060                                 resamplerow1 += 4;
1061                                 resamplerow2 += 4;
1062                         }
1063                         resamplerow1 -= outwidth4;
1064                         resamplerow2 -= outwidth4;
1065                 }
1066                 else
1067                 {
1068                         if (yi != oldy)
1069                         {
1070                                 inrow = (qbyte *)indata + inwidth4*yi;
1071                                 if (yi == oldy+1)
1072                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1073                                 else
1074                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1075                                 oldy = yi;
1076                         }
1077                         memcpy(out, resamplerow1, outwidth4);
1078                 }
1079         }
1080 }
1081
1082 void Image_Resample32Nearest(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1083 {
1084         int i, j;
1085         unsigned frac, fracstep;
1086         // relies on int being 4 bytes
1087         int *inrow, *out;
1088         out = outdata;
1089
1090         fracstep = inwidth*0x10000/outwidth;
1091         for (i = 0;i < outheight;i++)
1092         {
1093                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
1094                 frac = fracstep >> 1;
1095                 j = outwidth - 4;
1096                 while (j >= 0)
1097                 {
1098                         out[0] = inrow[frac >> 16];frac += fracstep;
1099                         out[1] = inrow[frac >> 16];frac += fracstep;
1100                         out[2] = inrow[frac >> 16];frac += fracstep;
1101                         out[3] = inrow[frac >> 16];frac += fracstep;
1102                         out += 4;
1103                         j -= 4;
1104                 }
1105                 if (j & 2)
1106                 {
1107                         out[0] = inrow[frac >> 16];frac += fracstep;
1108                         out[1] = inrow[frac >> 16];frac += fracstep;
1109                         out += 2;
1110                 }
1111                 if (j & 1)
1112                 {
1113                         out[0] = inrow[frac >> 16];frac += fracstep;
1114                         out += 1;
1115                 }
1116         }
1117 }
1118
1119 void Image_Resample24Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1120 {
1121         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth3 = inwidth * 3, outwidth3 = outwidth * 3;
1122         qbyte *out;
1123         const qbyte *inrow;
1124         out = outdata;
1125         fstep = (int) (inheight*65536.0f/outheight);
1126
1127         inrow = indata;
1128         oldy = 0;
1129         Image_Resample24LerpLine (inrow, resamplerow1, inwidth, outwidth);
1130         Image_Resample24LerpLine (inrow + inwidth3, resamplerow2, inwidth, outwidth);
1131         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1132         {
1133                 yi = f >> 16;
1134                 if (yi < endy)
1135                 {
1136                         lerp = f & 0xFFFF;
1137                         if (yi != oldy)
1138                         {
1139                                 inrow = (qbyte *)indata + inwidth3*yi;
1140                                 if (yi == oldy+1)
1141                                         memcpy(resamplerow1, resamplerow2, outwidth3);
1142                                 else
1143                                         Image_Resample24LerpLine (inrow, resamplerow1, inwidth, outwidth);
1144                                 Image_Resample24LerpLine (inrow + inwidth3, resamplerow2, inwidth, outwidth);
1145                                 oldy = yi;
1146                         }
1147                         j = outwidth - 4;
1148                         while(j >= 0)
1149                         {
1150                                 LERPBYTE( 0);
1151                                 LERPBYTE( 1);
1152                                 LERPBYTE( 2);
1153                                 LERPBYTE( 3);
1154                                 LERPBYTE( 4);
1155                                 LERPBYTE( 5);
1156                                 LERPBYTE( 6);
1157                                 LERPBYTE( 7);
1158                                 LERPBYTE( 8);
1159                                 LERPBYTE( 9);
1160                                 LERPBYTE(10);
1161                                 LERPBYTE(11);
1162                                 out += 12;
1163                                 resamplerow1 += 12;
1164                                 resamplerow2 += 12;
1165                                 j -= 4;
1166                         }
1167                         if (j & 2)
1168                         {
1169                                 LERPBYTE( 0);
1170                                 LERPBYTE( 1);
1171                                 LERPBYTE( 2);
1172                                 LERPBYTE( 3);
1173                                 LERPBYTE( 4);
1174                                 LERPBYTE( 5);
1175                                 out += 6;
1176                                 resamplerow1 += 6;
1177                                 resamplerow2 += 6;
1178                         }
1179                         if (j & 1)
1180                         {
1181                                 LERPBYTE( 0);
1182                                 LERPBYTE( 1);
1183                                 LERPBYTE( 2);
1184                                 out += 3;
1185                                 resamplerow1 += 3;
1186                                 resamplerow2 += 3;
1187                         }
1188                         resamplerow1 -= outwidth3;
1189                         resamplerow2 -= outwidth3;
1190                 }
1191                 else
1192                 {
1193                         if (yi != oldy)
1194                         {
1195                                 inrow = (qbyte *)indata + inwidth3*yi;
1196                                 if (yi == oldy+1)
1197                                         memcpy(resamplerow1, resamplerow2, outwidth3);
1198                                 else
1199                                         Image_Resample24LerpLine (inrow, resamplerow1, inwidth, outwidth);
1200                                 oldy = yi;
1201                         }
1202                         memcpy(out, resamplerow1, outwidth3);
1203                 }
1204         }
1205 }
1206
1207 void Image_Resample24Nolerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1208 {
1209         int i, j, f, inwidth3 = inwidth * 3;
1210         unsigned frac, fracstep;
1211         qbyte *inrow, *out;
1212         out = outdata;
1213
1214         fracstep = inwidth*0x10000/outwidth;
1215         for (i = 0;i < outheight;i++)
1216         {
1217                 inrow = (qbyte *)indata + inwidth3*(i*inheight/outheight);
1218                 frac = fracstep >> 1;
1219                 j = outwidth - 4;
1220                 while (j >= 0)
1221                 {
1222                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1223                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1224                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1225                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1226                         j -= 4;
1227                 }
1228                 if (j & 2)
1229                 {
1230                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1231                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1232                         out += 2;
1233                 }
1234                 if (j & 1)
1235                 {
1236                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
1237                         out += 1;
1238                 }
1239         }
1240 }
1241
1242 /*
1243 ================
1244 Image_Resample
1245 ================
1246 */
1247 void Image_Resample (const void *indata, int inwidth, int inheight, int indepth, void *outdata, int outwidth, int outheight, int outdepth, int bytesperpixel, int quality)
1248 {
1249         if (indepth != 1 || outdepth != 1)
1250                 Sys_Error("Image_Resample: 3D resampling not supported\n");
1251         if (resamplerowsize < outwidth*4)
1252         {
1253                 if (resamplerow1)
1254                         Mem_Free(resamplerow1);
1255                 resamplerowsize = outwidth*4;
1256                 if (!resamplemempool)
1257                         resamplemempool = Mem_AllocPool("Image Scaling Buffer");
1258                 resamplerow1 = Mem_Alloc(resamplemempool, resamplerowsize*2);
1259                 resamplerow2 = resamplerow1 + resamplerowsize;
1260         }
1261         if (bytesperpixel == 4)
1262         {
1263                 if (quality)
1264                         Image_Resample32Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1265                 else
1266                         Image_Resample32Nearest(indata, inwidth, inheight, outdata, outwidth, outheight);
1267         }
1268         else if (bytesperpixel == 3)
1269         {
1270                 if (quality)
1271                         Image_Resample24Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1272                 else
1273                         Image_Resample24Nolerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1274         }
1275         else
1276                 Sys_Error("Image_Resample: unsupported bytesperpixel %i\n", bytesperpixel);
1277 }
1278
1279 // in can be the same as out
1280 void Image_MipReduce(const qbyte *in, qbyte *out, int *width, int *height, int *depth, int destwidth, int destheight, int destdepth, int bytesperpixel)
1281 {
1282         int x, y, nextrow;
1283         if (*depth != 1 || destdepth != 1)
1284                 Sys_Error("Image_Resample: 3D resampling not supported\n");
1285         nextrow = *width * bytesperpixel;
1286         if (*width > destwidth)
1287         {
1288                 *width >>= 1;
1289                 if (*height > destheight)
1290                 {
1291                         // reduce both
1292                         *height >>= 1;
1293                         if (bytesperpixel == 4)
1294                         {
1295                                 for (y = 0;y < *height;y++)
1296                                 {
1297                                         for (x = 0;x < *width;x++)
1298                                         {
1299                                                 out[0] = (qbyte) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
1300                                                 out[1] = (qbyte) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
1301                                                 out[2] = (qbyte) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
1302                                                 out[3] = (qbyte) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
1303                                                 out += 4;
1304                                                 in += 8;
1305                                         }
1306                                         in += nextrow; // skip a line
1307                                 }
1308                         }
1309                         else if (bytesperpixel == 3)
1310                         {
1311                                 for (y = 0;y < *height;y++)
1312                                 {
1313                                         for (x = 0;x < *width;x++)
1314                                         {
1315                                                 out[0] = (qbyte) ((in[0] + in[3] + in[nextrow  ] + in[nextrow+3]) >> 2);
1316                                                 out[1] = (qbyte) ((in[1] + in[4] + in[nextrow+1] + in[nextrow+4]) >> 2);
1317                                                 out[2] = (qbyte) ((in[2] + in[5] + in[nextrow+2] + in[nextrow+5]) >> 2);
1318                                                 out += 3;
1319                                                 in += 6;
1320                                         }
1321                                         in += nextrow; // skip a line
1322                                 }
1323                         }
1324                         else
1325                                 Sys_Error("Image_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
1326                 }
1327                 else
1328                 {
1329                         // reduce width
1330                         if (bytesperpixel == 4)
1331                         {
1332                                 for (y = 0;y < *height;y++)
1333                                 {
1334                                         for (x = 0;x < *width;x++)
1335                                         {
1336                                                 out[0] = (qbyte) ((in[0] + in[4]) >> 1);
1337                                                 out[1] = (qbyte) ((in[1] + in[5]) >> 1);
1338                                                 out[2] = (qbyte) ((in[2] + in[6]) >> 1);
1339                                                 out[3] = (qbyte) ((in[3] + in[7]) >> 1);
1340                                                 out += 4;
1341                                                 in += 8;
1342                                         }
1343                                 }
1344                         }
1345                         else if (bytesperpixel == 3)
1346                         {
1347                                 for (y = 0;y < *height;y++)
1348                                 {
1349                                         for (x = 0;x < *width;x++)
1350                                         {
1351                                                 out[0] = (qbyte) ((in[0] + in[3]) >> 1);
1352                                                 out[1] = (qbyte) ((in[1] + in[4]) >> 1);
1353                                                 out[2] = (qbyte) ((in[2] + in[5]) >> 1);
1354                                                 out += 3;
1355                                                 in += 6;
1356                                         }
1357                                 }
1358                         }
1359                         else
1360                                 Sys_Error("Image_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
1361                 }
1362         }
1363         else
1364         {
1365                 if (*height > destheight)
1366                 {
1367                         // reduce height
1368                         *height >>= 1;
1369                         if (bytesperpixel == 4)
1370                         {
1371                                 for (y = 0;y < *height;y++)
1372                                 {
1373                                         for (x = 0;x < *width;x++)
1374                                         {
1375                                                 out[0] = (qbyte) ((in[0] + in[nextrow  ]) >> 1);
1376                                                 out[1] = (qbyte) ((in[1] + in[nextrow+1]) >> 1);
1377                                                 out[2] = (qbyte) ((in[2] + in[nextrow+2]) >> 1);
1378                                                 out[3] = (qbyte) ((in[3] + in[nextrow+3]) >> 1);
1379                                                 out += 4;
1380                                                 in += 4;
1381                                         }
1382                                         in += nextrow; // skip a line
1383                                 }
1384                         }
1385                         else if (bytesperpixel == 3)
1386                         {
1387                                 for (y = 0;y < *height;y++)
1388                                 {
1389                                         for (x = 0;x < *width;x++)
1390                                         {
1391                                                 out[0] = (qbyte) ((in[0] + in[nextrow  ]) >> 1);
1392                                                 out[1] = (qbyte) ((in[1] + in[nextrow+1]) >> 1);
1393                                                 out[2] = (qbyte) ((in[2] + in[nextrow+2]) >> 1);
1394                                                 out += 3;
1395                                                 in += 3;
1396                                         }
1397                                         in += nextrow; // skip a line
1398                                 }
1399                         }
1400                         else
1401                                 Sys_Error("Image_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
1402                 }
1403                 else
1404                         Sys_Error("Image_MipReduce: desired size already achieved\n");
1405         }
1406 }
1407
1408 void Image_HeightmapToNormalmap(const unsigned char *inpixels, unsigned char *outpixels, int width, int height, int clamp, float bumpscale)
1409 {
1410         int x, y;
1411         const unsigned char *p0, *p1, *p2;
1412         unsigned char *out;
1413         float iwidth, iheight, ibumpscale, n[3];
1414         iwidth = 1.0f / width;
1415         iheight = 1.0f / height;
1416         ibumpscale = (255.0f * 3.0f) / bumpscale;
1417         out = outpixels;
1418         for (y = 0;y < height;y++)
1419         {
1420                 for (x = 0;x < width;x++)
1421                 {
1422                         p0 = inpixels + (y * width + x) * 4;
1423                         if (x == width - 1)
1424                         {
1425                                 if (clamp)
1426                                         p1 = inpixels + (y * width + x) * 4;
1427                                 else
1428                                         p1 = inpixels + (y * width) * 4;
1429                         }
1430                         else
1431                                 p1 = inpixels + (y * width + x + 1) * 4;
1432                         if (y == height - 1)
1433                         {
1434                                 if (clamp)
1435                                         p2 = inpixels + (y * width + x) * 4;
1436                                 else
1437                                         p2 = inpixels + x * 4;
1438                         }
1439                         else
1440                                 p2 = inpixels + ((y + 1) * width + x) * 4;
1441                         /*
1442                         dv[0][0] = iwidth;
1443                         dv[0][1] = 0;
1444                         dv[0][2] = ((p0[0] + p0[1] + p0[2]) * ibumpscale) - ((p1[0] + p1[1] + p1[2]) * ibumpscale);
1445                         dv[1][0] = 0;
1446                         dv[1][1] = iheight;
1447                         dv[1][2] = ((p2[0] + p2[1] + p2[2]) * ibumpscale) - ((p0[0] + p0[1] + p0[2]) * ibumpscale);
1448                         n[0] = dv[0][1]*dv[1][2]-dv[0][2]*dv[1][1];
1449                         n[1] = dv[0][2]*dv[1][0]-dv[0][0]*dv[1][2];
1450                         n[2] = dv[0][0]*dv[1][1]-dv[0][1]*dv[1][0];
1451                         */
1452                         n[0] = ((p1[0] + p1[1] + p1[2]) - (p0[0] + p0[1] + p0[2]));
1453                         n[1] = ((p0[0] + p0[1] + p0[2]) - (p2[0] + p2[1] + p2[2]));
1454                         n[2] = ibumpscale;
1455                         VectorNormalize(n);
1456                         /*
1457                         // this should work for the bottom right triangle if anyone wants
1458                         // code for that for some reason
1459                         n[0] = ((p3[0] + p3[1] + p3[2]) - (p1[0] + p1[1] + p1[2]));
1460                         n[1] = ((p2[0] + p2[1] + p2[2]) - (p3[0] + p3[1] + p3[2]));
1461                         n[2] = ibumpscale;
1462                         VectorNormalize(n);
1463                         */
1464                         out[0] = 128.0f + n[0] * 127.0f;
1465                         out[1] = 128.0f + n[1] * 127.0f;
1466                         out[2] = 128.0f + n[2] * 127.0f;
1467                         out[3] = 255;
1468                         out += 4;
1469                 }
1470         }
1471 }
1472
1473 int image_loadskin(imageskin_t *s, char *shadername)
1474 {
1475         int j;
1476         qbyte *bumppixels;
1477         int bumppixels_width, bumppixels_height;
1478         char name[MAX_QPATH];
1479         Image_StripImageExtension(shadername, name);
1480         memset(s, 0, sizeof(*s));
1481         s->basepixels = loadimagepixels(name, false, 0, 0);
1482         if (s->basepixels == NULL)
1483                 return false;
1484         s->basepixels_width = image_width;
1485         s->basepixels_height = image_height;
1486
1487         bumppixels = NULL;bumppixels_width = 0;bumppixels_height = 0;
1488         if (Image_CheckAlpha(s->basepixels, s->basepixels_width * s->basepixels_height, true))
1489         {
1490                 s->maskpixels = Mem_Alloc(loadmodel->mempool, s->basepixels_width * s->basepixels_height * 4);
1491                 s->maskpixels_width = s->basepixels_width;
1492                 s->maskpixels_height = s->basepixels_height;
1493                 memcpy(s->maskpixels, s->basepixels, s->maskpixels_width * s->maskpixels_height * 4);
1494                 for (j = 0;j < s->basepixels_width * s->basepixels_height * 4;j += 4)
1495                 {
1496                         s->maskpixels[j+0] = 255;
1497                         s->maskpixels[j+1] = 255;
1498                         s->maskpixels[j+2] = 255;
1499                 }
1500         }
1501
1502         // _luma is supported for tenebrae compatibility
1503         // (I think it's a very stupid name, but oh well)
1504         if ((s->glowpixels = loadimagepixels(va("%s_glow", name), false, 0, 0)) != NULL
1505          || (s->glowpixels = loadimagepixels(va("%s_luma", name), false, 0, 0)) != NULL)
1506         {
1507                 s->glowpixels_width = image_width;
1508                 s->glowpixels_height = image_height;
1509         }
1510         // _norm is the name used by tenebrae
1511         // (I don't like the name much)
1512         if ((s->nmappixels = loadimagepixels(va("%s_norm", name), false, 0, 0)) != NULL)
1513         {
1514                 s->nmappixels_width = image_width;
1515                 s->nmappixels_height = image_height;
1516         }
1517         else if ((bumppixels = loadimagepixels(va("%s_bump", name), false, 0, 0)) != NULL)
1518         {
1519                 bumppixels_width = image_width;
1520                 bumppixels_height = image_height;
1521         }
1522         if ((s->glosspixels = loadimagepixels(va("%s_gloss", name), false, 0, 0)) != NULL)
1523         {
1524                 s->glosspixels_width = image_width;
1525                 s->glosspixels_height = image_height;
1526         }
1527         if ((s->pantspixels = loadimagepixels(va("%s_pants", name), false, 0, 0)) != NULL)
1528         {
1529                 s->pantspixels_width = image_width;
1530                 s->pantspixels_height = image_height;
1531         }
1532         if ((s->shirtpixels = loadimagepixels(va("%s_shirt", name), false, 0, 0)) != NULL)
1533         {
1534                 s->shirtpixels_width = image_width;
1535                 s->shirtpixels_height = image_height;
1536         }
1537
1538         if (s->nmappixels == NULL)
1539         {
1540                 if (bumppixels != NULL)
1541                 {
1542                         if (r_shadow_bumpscale_bumpmap.value > 0)
1543                         {
1544                                 s->nmappixels = Mem_Alloc(loadmodel->mempool, bumppixels_width * bumppixels_height * 4);
1545                                 s->nmappixels_width = bumppixels_width;
1546                                 s->nmappixels_height = bumppixels_height;
1547                                 Image_HeightmapToNormalmap(bumppixels, s->nmappixels, s->nmappixels_width, s->nmappixels_height, false, r_shadow_bumpscale_bumpmap.value);
1548                         }
1549                 }
1550                 else
1551                 {
1552                         if (r_shadow_bumpscale_basetexture.value > 0)
1553                         {
1554                                 s->nmappixels = Mem_Alloc(loadmodel->mempool, s->basepixels_width * s->basepixels_height * 4);
1555                                 s->nmappixels_width = s->basepixels_width;
1556                                 s->nmappixels_height = s->basepixels_height;
1557                                 Image_HeightmapToNormalmap(s->basepixels, s->nmappixels, s->nmappixels_width, s->nmappixels_height, false, r_shadow_bumpscale_basetexture.value);
1558                         }
1559                 }
1560         }
1561         if (bumppixels != NULL)
1562                 Mem_Free(bumppixels);
1563         return true;
1564 }
1565
1566 void image_freeskin(imageskin_t *s)
1567 {
1568         if (s->basepixels)
1569                 Mem_Free(s->basepixels);
1570         if (s->maskpixels)
1571                 Mem_Free(s->maskpixels);
1572         if (s->nmappixels)
1573                 Mem_Free(s->nmappixels);
1574         if (s->glowpixels)
1575                 Mem_Free(s->glowpixels);
1576         if (s->glosspixels)
1577                 Mem_Free(s->glosspixels);
1578         if (s->pantspixels)
1579                 Mem_Free(s->pantspixels);
1580         if (s->shirtpixels)
1581                 Mem_Free(s->shirtpixels);
1582         memset(s, 0, sizeof(*s));
1583 }
1584