]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/common/imagelib.c
fix unzip code
[xonotic/netradiant.git] / tools / quake3 / common / imagelib.c
1 /*
2    Copyright (C) 1999-2007 id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 // imagelib.c
23
24 #include "inout.h"
25 #include "cmdlib.h"
26 #include "imagelib.h"
27 #include "vfs.h"
28
29 int fgetLittleShort( FILE *f ){
30         byte b1, b2;
31
32         b1 = fgetc( f );
33         b2 = fgetc( f );
34
35         return (short)( b1 + b2 * 256 );
36 }
37
38 int fgetLittleLong( FILE *f ){
39         byte b1, b2, b3, b4;
40
41         b1 = fgetc( f );
42         b2 = fgetc( f );
43         b3 = fgetc( f );
44         b4 = fgetc( f );
45
46         return b1 + ( b2 << 8 ) + ( b3 << 16 ) + ( b4 << 24 );
47 }
48
49 int bufLittleShort( byte *buf, int len, int *pos ){
50         byte b1, b2;
51
52         if ( ( len - *pos ) < 2 ) {
53                 Error( "Unexpected buffer end" );
54         }
55
56         b1 = buf[*pos]; *pos += 1;
57         b2 = buf[*pos]; *pos += 1;
58
59         return (short)( b1 + b2 * 256 );
60 }
61
62 int bufLittleLong( byte *buf, int len, int *pos ){
63         byte b1, b2, b3, b4;
64
65         if ( ( len - *pos ) < 4 ) {
66                 Error( "Unexpected buffer end" );
67         }
68
69         b1 = buf[*pos]; *pos += 1;
70         b2 = buf[*pos]; *pos += 1;
71         b3 = buf[*pos]; *pos += 1;
72         b4 = buf[*pos]; *pos += 1;
73
74         return b1 + ( b2 << 8 ) + ( b3 << 16 ) + ( b4 << 24 );
75 }
76
77
78 /*
79    ============================================================================
80
81                         LBM STUFF
82
83    ============================================================================
84  */
85
86
87 typedef unsigned char UBYTE;
88 //conflicts with windows typedef short                  WORD;
89 typedef unsigned short UWORD;
90 typedef long LONG;
91
92 typedef enum
93 {
94         ms_none,
95         ms_mask,
96         ms_transcolor,
97         ms_lasso
98 } mask_t;
99
100 typedef enum
101 {
102         cm_none,
103         cm_rle1
104 } compress_t;
105
106 typedef struct
107 {
108         UWORD w,h;
109         short x,y;
110         UBYTE nPlanes;
111         UBYTE masking;
112         UBYTE compression;
113         UBYTE pad1;
114         UWORD transparentColor;
115         UBYTE xAspect,yAspect;
116         short pageWidth,pageHeight;
117 } bmhd_t;
118
119 extern bmhd_t bmhd;                         // will be in native byte order
120
121
122
123 #define FORMID ( 'F' + ( 'O' << 8 ) + ( (int)'R' << 16 ) + ( (int)'M' << 24 ) )
124 #define ILBMID ( 'I' + ( 'L' << 8 ) + ( (int)'B' << 16 ) + ( (int)'M' << 24 ) )
125 #define PBMID  ( 'P' + ( 'B' << 8 ) + ( (int)'M' << 16 ) + ( (int)' ' << 24 ) )
126 #define BMHDID ( 'B' + ( 'M' << 8 ) + ( (int)'H' << 16 ) + ( (int)'D' << 24 ) )
127 #define BODYID ( 'B' + ( 'O' << 8 ) + ( (int)'D' << 16 ) + ( (int)'Y' << 24 ) )
128 #define CMAPID ( 'C' + ( 'M' << 8 ) + ( (int)'A' << 16 ) + ( (int)'P' << 24 ) )
129
130
131 bmhd_t bmhd;
132
133 int    Align( int l ){
134         if ( l & 1 ) {
135                 return l + 1;
136         }
137         return l;
138 }
139
140
141
142 /*
143    ================
144    LBMRLEdecompress
145
146    Source must be evenly aligned!
147    ================
148  */
149 byte  *LBMRLEDecompress( byte *source,byte *unpacked, int bpwidth ){
150         int count;
151         byte b,rept;
152
153         count = 0;
154
155         do
156         {
157                 rept = *source++;
158
159                 if ( rept > 0x80 ) {
160                         rept = ( rept ^ 0xff ) + 2;
161                         b = *source++;
162                         memset( unpacked,b,rept );
163                         unpacked += rept;
164                 }
165                 else if ( rept < 0x80 ) {
166                         rept++;
167                         memcpy( unpacked,source,rept );
168                         unpacked += rept;
169                         source += rept;
170                 }
171                 else{
172                         rept = 0;               // rept of 0x80 is NOP
173
174                 }
175                 count += rept;
176
177         } while ( count < bpwidth );
178
179         if ( count > bpwidth ) {
180                 Error( "Decompression exceeded width!\n" );
181         }
182
183
184         return source;
185 }
186
187
188 /*
189    =================
190    LoadLBM
191    =================
192  */
193 void LoadLBM( const char *filename, byte **picture, byte **palette ){
194         byte    *LBMbuffer, *picbuffer, *cmapbuffer;
195         int y;
196         byte    *LBM_P, *LBMEND_P;
197         byte    *pic_p;
198         byte    *body_p;
199
200         int formtype,formlength;
201         int chunktype,chunklength;
202
203 // qiet compiler warnings
204         picbuffer = NULL;
205         cmapbuffer = NULL;
206
207 //
208 // load the LBM
209 //
210         LoadFile( filename, (void **)&LBMbuffer );
211
212 //
213 // parse the LBM header
214 //
215         LBM_P = LBMbuffer;
216         if ( *(int *)LBMbuffer != LittleLong( FORMID ) ) {
217                 Error( "No FORM ID at start of file!\n" );
218         }
219
220         LBM_P += 4;
221         formlength = BigLong( *(int *)LBM_P );
222         LBM_P += 4;
223         LBMEND_P = LBM_P + Align( formlength );
224
225         formtype = LittleLong( *(int *)LBM_P );
226
227         if ( formtype != ILBMID && formtype != PBMID ) {
228                 Error( "Unrecognized form type: %c%c%c%c\n", formtype & 0xff
229                            ,( formtype >> 8 ) & 0xff,( formtype >> 16 ) & 0xff,( formtype >> 24 ) & 0xff );
230         }
231
232         LBM_P += 4;
233
234 //
235 // parse chunks
236 //
237
238         while ( LBM_P < LBMEND_P )
239         {
240                 chunktype = LBM_P[0] + ( LBM_P[1] << 8 ) + ( LBM_P[2] << 16 ) + ( LBM_P[3] << 24 );
241                 LBM_P += 4;
242                 chunklength = LBM_P[3] + ( LBM_P[2] << 8 ) + ( LBM_P[1] << 16 ) + ( LBM_P[0] << 24 );
243                 LBM_P += 4;
244
245                 switch ( chunktype )
246                 {
247                 case BMHDID:
248                         memcpy( &bmhd,LBM_P,sizeof( bmhd ) );
249                         bmhd.w = BigShort( bmhd.w );
250                         bmhd.h = BigShort( bmhd.h );
251                         bmhd.x = BigShort( bmhd.x );
252                         bmhd.y = BigShort( bmhd.y );
253                         bmhd.pageWidth = BigShort( bmhd.pageWidth );
254                         bmhd.pageHeight = BigShort( bmhd.pageHeight );
255                         break;
256
257                 case CMAPID:
258                         cmapbuffer = safe_malloc( 768 );
259                         memset( cmapbuffer, 0, 768 );
260                         memcpy( cmapbuffer, LBM_P, chunklength );
261                         break;
262
263                 case BODYID:
264                         body_p = LBM_P;
265
266                         pic_p = picbuffer = safe_malloc( bmhd.w * bmhd.h );
267                         if ( formtype == PBMID ) {
268                                 //
269                                 // unpack PBM
270                                 //
271                                 for ( y = 0 ; y < bmhd.h ; y++, pic_p += bmhd.w )
272                                 {
273                                         if ( bmhd.compression == cm_rle1 ) {
274                                                 body_p = LBMRLEDecompress( (byte *)body_p
275                                                                                                    , pic_p, bmhd.w );
276                                         }
277                                         else if ( bmhd.compression == cm_none ) {
278                                                 memcpy( pic_p,body_p,bmhd.w );
279                                                 body_p += Align( bmhd.w );
280                                         }
281                                 }
282
283                         }
284                         else
285                         {
286                                 //
287                                 // unpack ILBM
288                                 //
289                                 Error( "%s is an interlaced LBM, not packed", filename );
290                         }
291                         break;
292                 }
293
294                 LBM_P += Align( chunklength );
295         }
296
297         free( LBMbuffer );
298
299         *picture = picbuffer;
300
301         if ( palette ) {
302                 *palette = cmapbuffer;
303         }
304 }
305
306
307 /*
308    ============================================================================
309
310                             WRITE LBM
311
312    ============================================================================
313  */
314
315 /*
316    ==============
317    WriteLBMfile
318    ==============
319  */
320 void WriteLBMfile( const char *filename, byte *data,
321                                    int width, int height, byte *palette ){
322         byte    *lbm, *lbmptr;
323         int    *formlength, *bmhdlength, *cmaplength, *bodylength;
324         int length;
325         bmhd_t basebmhd;
326
327         lbm = lbmptr = safe_malloc( width * height + 1000 );
328
329 //
330 // start FORM
331 //
332         *lbmptr++ = 'F';
333         *lbmptr++ = 'O';
334         *lbmptr++ = 'R';
335         *lbmptr++ = 'M';
336
337         formlength = (int*)lbmptr;
338         lbmptr += 4;                      // leave space for length
339
340         *lbmptr++ = 'P';
341         *lbmptr++ = 'B';
342         *lbmptr++ = 'M';
343         *lbmptr++ = ' ';
344
345 //
346 // write BMHD
347 //
348         *lbmptr++ = 'B';
349         *lbmptr++ = 'M';
350         *lbmptr++ = 'H';
351         *lbmptr++ = 'D';
352
353         bmhdlength = (int *)lbmptr;
354         lbmptr += 4;                      // leave space for length
355
356         memset( &basebmhd,0,sizeof( basebmhd ) );
357         basebmhd.w = BigShort( (short)width );
358         basebmhd.h = BigShort( (short)height );
359         basebmhd.nPlanes = BigShort( 8 );
360         basebmhd.xAspect = BigShort( 5 );
361         basebmhd.yAspect = BigShort( 6 );
362         basebmhd.pageWidth = BigShort( (short)width );
363         basebmhd.pageHeight = BigShort( (short)height );
364
365         memcpy( lbmptr,&basebmhd,sizeof( basebmhd ) );
366         lbmptr += sizeof( basebmhd );
367
368         length = lbmptr - (byte *)bmhdlength - 4;
369         *bmhdlength = BigLong( length );
370         if ( length & 1 ) {
371                 *lbmptr++ = 0;          // pad chunk to even offset
372
373         }
374 //
375 // write CMAP
376 //
377         *lbmptr++ = 'C';
378         *lbmptr++ = 'M';
379         *lbmptr++ = 'A';
380         *lbmptr++ = 'P';
381
382         cmaplength = (int *)lbmptr;
383         lbmptr += 4;                      // leave space for length
384
385         memcpy( lbmptr,palette,768 );
386         lbmptr += 768;
387
388         length = lbmptr - (byte *)cmaplength - 4;
389         *cmaplength = BigLong( length );
390         if ( length & 1 ) {
391                 *lbmptr++ = 0;          // pad chunk to even offset
392
393         }
394 //
395 // write BODY
396 //
397         *lbmptr++ = 'B';
398         *lbmptr++ = 'O';
399         *lbmptr++ = 'D';
400         *lbmptr++ = 'Y';
401
402         bodylength = (int *)lbmptr;
403         lbmptr += 4;                      // leave space for length
404
405         memcpy( lbmptr,data,width * height );
406         lbmptr += width * height;
407
408         length = lbmptr - (byte *)bodylength - 4;
409         *bodylength = BigLong( length );
410         if ( length & 1 ) {
411                 *lbmptr++ = 0;          // pad chunk to even offset
412
413         }
414 //
415 // done
416 //
417         length = lbmptr - (byte *)formlength - 4;
418         *formlength = BigLong( length );
419         if ( length & 1 ) {
420                 *lbmptr++ = 0;          // pad chunk to even offset
421
422         }
423 //
424 // write output file
425 //
426         SaveFile( filename, lbm, lbmptr - lbm );
427         free( lbm );
428 }
429
430
431 /*
432    ============================================================================
433
434    LOAD PCX
435
436    ============================================================================
437  */
438
439 typedef struct
440 {
441         char manufacturer;
442         char version;
443         char encoding;
444         char bits_per_pixel;
445         unsigned short xmin,ymin,xmax,ymax;
446         unsigned short hres,vres;
447         unsigned char palette[48];
448         char reserved;
449         char color_planes;
450         unsigned short bytes_per_line;
451         unsigned short palette_type;
452         char filler[58];
453         unsigned char data;             // unbounded
454 } pcx_t;
455
456
457 /*
458    ==============
459    LoadPCX
460    ==============
461  */
462
463 /* RR2DO2 */
464 #define DECODEPCX( b, d, r ) d = *b++; if ( ( d & 0xC0 ) == 0xC0 ) {r = d & 0x3F; d = *b++; }else{r = 1; }
465
466 void LoadPCX( const char *filename, byte **pic, byte **palette, int *width, int *height ){
467         byte    *raw;
468         pcx_t   *pcx;
469         int x, y, lsize;
470         int len;
471         int dataByte, runLength;
472         byte    *out, *pix;
473
474
475         /* load the file */
476         len = vfsLoadFile( filename, (void **)&raw, 0 );
477         if ( len == -1 ) {
478                 Error( "LoadPCX: Couldn't read %s", filename );
479         }
480
481
482         /* parse the PCX file */
483         pcx = (pcx_t *)raw;
484         raw = &pcx->data;
485
486         pcx->xmin = LittleShort( pcx->xmin );
487         pcx->ymin = LittleShort( pcx->ymin );
488         pcx->xmax = LittleShort( pcx->xmax );
489         pcx->ymax = LittleShort( pcx->ymax );
490         pcx->hres = LittleShort( pcx->hres );
491         pcx->vres = LittleShort( pcx->vres );
492         pcx->bytes_per_line = LittleShort( pcx->bytes_per_line );
493         pcx->palette_type = LittleShort( pcx->palette_type );
494
495         if ( pcx->manufacturer != 0x0a
496                  || pcx->version != 5
497                  || pcx->encoding != 1
498                  || pcx->bits_per_pixel != 8
499                  || pcx->xmax >= 640
500                  || pcx->ymax >= 480 ) {
501                 Error( "Bad pcx file %s", filename );
502         }
503
504         if ( palette ) {
505                 *palette = safe_malloc( 768 );
506                 memcpy( *palette, (byte *)pcx + len - 768, 768 );
507         }
508
509         if ( width ) {
510                 *width = pcx->xmax + 1;
511         }
512         if ( height ) {
513                 *height = pcx->ymax + 1;
514         }
515
516         if ( !pic ) {
517                 return;
518         }
519
520         out = safe_malloc( ( pcx->ymax + 1 ) * ( pcx->xmax + 1 ) );
521         if ( !out ) {
522                 Error( "LoadPCX: couldn't allocate" );
523         }
524
525         *pic = out;
526         pix = out;
527
528         /* RR2DO2: pcx fix  */
529         lsize = pcx->color_planes * pcx->bytes_per_line;
530
531         /* go scanline by scanline */
532         for ( y = 0; y <= pcx->ymax; y++, pix += pcx->xmax + 1 )
533         {
534                 /* do a scanline */
535                 for ( x = 0; x <= pcx->xmax; )
536                 {
537                         /* RR2DO2 */
538                         DECODEPCX( raw, dataByte, runLength );
539                         while ( runLength-- > 0 )
540                                 pix[ x++ ] = dataByte;
541                 }
542
543                 /* RR2DO2: discard any other data */
544                 while ( x < lsize )
545                 {
546                         DECODEPCX( raw, dataByte, runLength );
547                         x++;
548                 }
549                 while ( runLength-- > 0 )
550                         x++;
551         }
552
553         /* validity check */
554         if ( raw - (byte *) pcx > len ) {
555                 Error( "PCX file %s was malformed", filename );
556         }
557         free( pcx );
558 }
559
560
561
562 /*
563    ==============
564    WritePCXfile
565    ==============
566  */
567 void WritePCXfile( const char *filename, byte *data,
568                                    int width, int height, byte *palette ){
569         int i, j, length;
570         pcx_t   *pcx;
571         byte        *pack;
572
573         pcx = safe_malloc( width * height * 2 + 1000 );
574         memset( pcx, 0, sizeof( *pcx ) );
575
576         pcx->manufacturer = 0x0a;   // PCX id
577         pcx->version = 5;           // 256 color
578         pcx->encoding = 1;      // uncompressed
579         pcx->bits_per_pixel = 8;        // 256 color
580         pcx->xmin = 0;
581         pcx->ymin = 0;
582         pcx->xmax = LittleShort( (short)( width - 1 ) );
583         pcx->ymax = LittleShort( (short)( height - 1 ) );
584         pcx->hres = LittleShort( (short)width );
585         pcx->vres = LittleShort( (short)height );
586         pcx->color_planes = 1;      // chunky image
587         pcx->bytes_per_line = LittleShort( (short)width );
588         pcx->palette_type = LittleShort( 1 );     // not a grey scale
589
590         // pack the image
591         pack = &pcx->data;
592
593         for ( i = 0 ; i < height ; i++ )
594         {
595                 for ( j = 0 ; j < width ; j++ )
596                 {
597                         if ( ( *data & 0xc0 ) != 0xc0 ) {
598                                 *pack++ = *data++;
599                         }
600                         else
601                         {
602                                 *pack++ = 0xc1;
603                                 *pack++ = *data++;
604                         }
605                 }
606         }
607
608         // write the palette
609         *pack++ = 0x0c; // palette ID byte
610         for ( i = 0 ; i < 768 ; i++ )
611                 *pack++ = *palette++;
612
613 // write output file
614         length = pack - (byte *)pcx;
615         SaveFile( filename, pcx, length );
616
617         free( pcx );
618 }
619
620 /*
621    ============================================================================
622
623    LOAD BMP
624
625    ============================================================================
626  */
627
628
629 /*
630
631    // we can't just use these structures, because
632    // compiler structure alignment will not be portable
633    // on this unaligned stuff
634
635    typedef struct tagBITMAPFILEHEADER { // bmfh
636         WORD    bfType;                         // BM
637         DWORD   bfSize;
638         WORD    bfReserved1;
639         WORD    bfReserved2;
640         DWORD   bfOffBits;
641    } BITMAPFILEHEADER;
642
643    typedef struct tagBITMAPINFOHEADER{ // bmih
644    DWORD  biSize;
645    LONG   biWidth;
646    LONG   biHeight;
647    WORD   biPlanes;
648    WORD   biBitCount
649    DWORD  biCompression;
650    DWORD  biSizeImage;
651    LONG   biXPelsPerMeter;
652    LONG   biYPelsPerMeter;
653    DWORD  biClrUsed;
654    DWORD  biClrImportant;
655    } BITMAPINFOHEADER;
656
657    typedef struct tagBITMAPINFO { // bmi
658    BITMAPINFOHEADER bmiHeader;
659    RGBQUAD          bmiColors[1];
660    } BITMAPINFO;
661
662    typedef struct tagBITMAPCOREHEADER { // bmch
663         DWORD   bcSize;
664         WORD    bcWidth;
665         WORD    bcHeight;
666         WORD    bcPlanes;
667         WORD    bcBitCount;
668    } BITMAPCOREHEADER;
669
670    typedef struct _BITMAPCOREINFO {    // bmci
671         BITMAPCOREHEADER  bmciHeader;
672         RGBTRIPLE         bmciColors[1];
673    } BITMAPCOREINFO;
674
675  */
676
677 /*
678    ==============
679    LoadBMP
680    ==============
681  */
682 void LoadBMP( const char *filename, byte **pic, byte **palette, int *width, int *height ){
683         byte  *out;
684         int i;
685         int bfSize;
686         int bfOffBits;
687         int structSize;
688         int bcWidth;
689         int bcHeight;
690         int bcPlanes;
691         int bcBitCount;
692         byte bcPalette[1024];
693         qboolean flipped;
694         byte *in;
695         int len, pos = 0;
696
697         len = vfsLoadFile( filename, (void **)&in, 0 );
698         if ( len == -1 ) {
699                 Error( "Couldn't read %s", filename );
700         }
701
702         i = bufLittleShort( in, len, &pos );
703         if ( i != 'B' + ( 'M' << 8 ) ) {
704                 Error( "%s is not a bmp file", filename );
705         }
706
707         bfSize = bufLittleLong( in, len, &pos );
708         bufLittleShort( in, len, &pos );
709         bufLittleShort( in, len, &pos );
710         bfOffBits = bufLittleLong( in, len, &pos );
711
712         // the size will tell us if it is a
713         // bitmapinfo or a bitmapcore
714         structSize = bufLittleLong( in, len, &pos );
715         if ( structSize == 40 ) {
716                 // bitmapinfo
717                 bcWidth = bufLittleLong( in, len, &pos );
718                 bcHeight = bufLittleLong( in, len, &pos );
719                 bcPlanes = bufLittleShort( in, len, &pos );
720                 bcBitCount = bufLittleShort( in, len, &pos );
721
722                 pos += 24;
723
724                 if ( palette ) {
725                         memcpy( bcPalette, in + pos, 1024 );
726                         pos += 1024;
727                         *palette = safe_malloc( 768 );
728
729                         for ( i = 0 ; i < 256 ; i++ )
730                         {
731                                 ( *palette )[i * 3 + 0] = bcPalette[i * 4 + 2];
732                                 ( *palette )[i * 3 + 1] = bcPalette[i * 4 + 1];
733                                 ( *palette )[i * 3 + 2] = bcPalette[i * 4 + 0];
734                         }
735                 }
736         }
737         else if ( structSize == 12 ) {
738                 // bitmapcore
739                 bcWidth = bufLittleShort( in, len, &pos );
740                 bcHeight = bufLittleShort( in, len, &pos );
741                 bcPlanes = bufLittleShort( in, len, &pos );
742                 bcBitCount = bufLittleShort( in, len, &pos );
743
744                 if ( palette ) {
745                         memcpy( bcPalette, in + pos, 768 );
746                         pos += 768;
747                         *palette = safe_malloc( 768 );
748
749                         for ( i = 0 ; i < 256 ; i++ ) {
750                                 ( *palette )[i * 3 + 0] = bcPalette[i * 3 + 2];
751                                 ( *palette )[i * 3 + 1] = bcPalette[i * 3 + 1];
752                                 ( *palette )[i * 3 + 2] = bcPalette[i * 3 + 0];
753                         }
754                 }
755         }
756         else {
757                 Error( "%s had strange struct size", filename );
758         }
759
760         if ( bcPlanes != 1 ) {
761                 Error( "%s was not a single plane image", filename );
762         }
763
764         if ( bcBitCount != 8 ) {
765                 Error( "%s was not an 8 bit image", filename );
766         }
767
768         if ( bcHeight < 0 ) {
769                 bcHeight = -bcHeight;
770                 flipped = qtrue;
771         }
772         else {
773                 flipped = qfalse;
774         }
775
776         if ( width ) {
777                 *width = bcWidth;
778         }
779         if ( height ) {
780                 *height = bcHeight;
781         }
782
783         if ( !pic ) {
784                 free( in );
785                 return;
786         }
787
788         out = safe_malloc( bcWidth * bcHeight );
789         *pic = out;
790         pos = bfOffBits;
791
792         if ( flipped ) {
793                 for ( i = 0 ; i < bcHeight ; i++ ) {
794                         memcpy( out + bcWidth * ( bcHeight - 1 - i ), in + pos, bcWidth );
795                         pos += bcWidth;
796                 }
797         }
798         else {
799                 memcpy( out, in + pos, bcWidth * bcHeight );
800                 pos += bcWidth * bcHeight;
801         }
802
803         free( in );
804 }
805
806
807 /*
808    ============================================================================
809
810    LOAD IMAGE
811
812    ============================================================================
813  */
814
815 /*
816    ==============
817    Load256Image
818
819    Will load either an lbm or pcx, depending on extension.
820    Any of the return pointers can be NULL if you don't want them.
821    ==============
822  */
823 void Load256Image( const char *name, byte **pixels, byte **palette, int *width, int *height ){
824         char ext[128];
825
826         ExtractFileExtension( name, ext );
827         if ( !Q_stricmp( ext, "lbm" ) ) {
828                 LoadLBM( name, pixels, palette );
829                 if ( width ) {
830                         *width = bmhd.w;
831                 }
832                 if ( height ) {
833                         *height = bmhd.h;
834                 }
835         }
836         else if ( !Q_stricmp( ext, "pcx" ) ) {
837                 LoadPCX( name, pixels, palette, width, height );
838         }
839         else if ( !Q_stricmp( ext, "bmp" ) ) {
840                 LoadBMP( name, pixels, palette, width, height );
841         }
842         else{
843                 Error( "%s doesn't have a known image extension", name );
844         }
845 }
846
847
848 /*
849    ==============
850    Save256Image
851
852    Will save either an lbm or pcx, depending on extension.
853    ==============
854  */
855 void Save256Image( const char *name, byte *pixels, byte *palette,
856                                    int width, int height ){
857         char ext[128];
858
859         ExtractFileExtension( name, ext );
860         if ( !Q_stricmp( ext, "lbm" ) ) {
861                 WriteLBMfile( name, pixels, width, height, palette );
862         }
863         else if ( !Q_stricmp( ext, "pcx" ) ) {
864                 WritePCXfile( name, pixels, width, height, palette );
865         }
866         else{
867                 Error( "%s doesn't have a known image extension", name );
868         }
869 }
870
871
872
873
874 /*
875    ============================================================================
876
877    TARGA IMAGE
878
879    ============================================================================
880  */
881
882 typedef struct _TargaHeader {
883         unsigned char id_length, colormap_type, image_type;
884         unsigned short colormap_index, colormap_length;
885         unsigned char colormap_size;
886         unsigned short x_origin, y_origin, width, height;
887         unsigned char pixel_size, attributes;
888 } TargaHeader;
889
890 void TargaError( TargaHeader *t, const char *message ){
891         Sys_Printf( "%s\n: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", message, 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 );
892 }
893
894 /*
895    =============
896    LoadTGABuffer
897    =============
898  */
899 void LoadTGABuffer( const byte *f, const byte *enddata, byte **pic, int *width, int *height ){
900         int x, y, row_inc, compressed, readpixelcount, red, green, blue, alpha, runlen, pindex, alphabits, image_width, image_height;
901         byte *pixbuf, *image_rgba;
902         const byte *fin;
903         unsigned char *p;
904         TargaHeader targa_header;
905         unsigned char palette[256 * 4];
906
907         *pic = NULL;
908
909         // abort if it is too small to parse
910         if ( enddata - f < 19 ) {
911                 return;
912         }
913
914         targa_header.id_length = f[0];
915         targa_header.colormap_type = f[1];
916         targa_header.image_type = f[2];
917
918         targa_header.colormap_index = f[3] + f[4] * 256;
919         targa_header.colormap_length = f[5] + f[6] * 256;
920         targa_header.colormap_size = f[7];
921         targa_header.x_origin = f[8] + f[9] * 256;
922         targa_header.y_origin = f[10] + f[11] * 256;
923         targa_header.width = image_width = f[12] + f[13] * 256;
924         targa_header.height = image_height = f[14] + f[15] * 256;
925
926         targa_header.pixel_size = f[16];
927         targa_header.attributes = f[17];
928
929         // advance to end of header
930         fin = f + 18;
931
932         // skip TARGA image comment (usually 0 bytes)
933         fin += targa_header.id_length;
934
935         // read/skip the colormap if present (note: according to the TARGA spec it
936         // can be present even on truecolor or greyscale images, just not used by
937         // the image data)
938         if ( targa_header.colormap_type ) {
939                 if ( targa_header.colormap_length > 256 ) {
940                         TargaError( &targa_header, "LoadTGA: only up to 256 colormap_length supported\n" );
941                         return;
942                 }
943                 if ( targa_header.colormap_index ) {
944                         TargaError( &targa_header, "LoadTGA: colormap_index not supported\n" );
945                         return;
946                 }
947                 if ( targa_header.colormap_size == 24 ) {
948                         for ( x = 0; x < targa_header.colormap_length; x++ )
949                         {
950                                 palette[x * 4 + 2] = *fin++;
951                                 palette[x * 4 + 1] = *fin++;
952                                 palette[x * 4 + 0] = *fin++;
953                                 palette[x * 4 + 3] = 255;
954                         }
955                 }
956                 else if ( targa_header.colormap_size == 32 ) {
957                         for ( x = 0; x < targa_header.colormap_length; x++ )
958                         {
959                                 palette[x * 4 + 2] = *fin++;
960                                 palette[x * 4 + 1] = *fin++;
961                                 palette[x * 4 + 0] = *fin++;
962                                 palette[x * 4 + 3] = *fin++;
963                         }
964                 }
965                 else
966                 {
967                         TargaError( &targa_header, "LoadTGA: Only 32 and 24 bit colormap_size supported\n" );
968                         return;
969                 }
970         }
971
972         // check our pixel_size restrictions according to image_type
973         if ( targa_header.image_type == 2 || targa_header.image_type == 10 ) {
974                 if ( targa_header.pixel_size != 24 && targa_header.pixel_size != 32 ) {
975                         TargaError( &targa_header, "LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n" );
976                         return;
977                 }
978         }
979         else if ( targa_header.image_type == 1 || targa_header.image_type == 9 ) {
980                 if ( targa_header.pixel_size != 8 ) {
981                         TargaError( &targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n" );
982                         return;
983                 }
984         }
985         else if ( targa_header.image_type == 3 || targa_header.image_type == 11 ) {
986                 if ( targa_header.pixel_size != 8 ) {
987                         TargaError( &targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n" );
988                         return;
989                 }
990         }
991         else
992         {
993                 TargaError( &targa_header, "LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported" );
994                 return;
995         }
996
997         if ( targa_header.attributes & 0x10 ) {
998                 TargaError( &targa_header, "LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n" );
999                 return;
1000         }
1001
1002         // number of attribute bits per pixel, we only support 0 or 8
1003         alphabits = targa_header.attributes & 0x0F;
1004         if ( alphabits != 8 && alphabits != 0 ) {
1005                 TargaError( &targa_header, "LoadTGA: only 0 or 8 attribute (alpha) bits supported\n" );
1006                 return;
1007         }
1008
1009         image_rgba = safe_malloc( image_width * image_height * 4 );
1010         if ( !image_rgba ) {
1011                 Sys_Printf( "LoadTGA: not enough memory for %i by %i image\n", image_width, image_height );
1012                 return;
1013         }
1014
1015         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
1016         if ( ( targa_header.attributes & 0x20 ) == 0 ) {
1017                 pixbuf = image_rgba + ( image_height - 1 ) * image_width * 4;
1018                 row_inc = -image_width * 4 * 2;
1019         }
1020         else
1021         {
1022                 pixbuf = image_rgba;
1023                 row_inc = 0;
1024         }
1025
1026         compressed = targa_header.image_type == 9 || targa_header.image_type == 10 || targa_header.image_type == 11;
1027         x = 0;
1028         y = 0;
1029         red = green = blue = alpha = 255;
1030         while ( y < image_height )
1031         {
1032                 // decoder is mostly the same whether it's compressed or not
1033                 readpixelcount = 1000000;
1034                 runlen = 1000000;
1035                 if ( compressed && fin < enddata ) {
1036                         runlen = *fin++;
1037                         // high bit indicates this is an RLE compressed run
1038                         if ( runlen & 0x80 ) {
1039                                 readpixelcount = 1;
1040                         }
1041                         runlen = 1 + ( runlen & 0x7f );
1042                 }
1043
1044                 while ( ( runlen-- ) && y < image_height )
1045                 {
1046                         if ( readpixelcount > 0 ) {
1047                                 readpixelcount--;
1048                                 red = green = blue = alpha = 255;
1049                                 if ( fin < enddata ) {
1050                                         switch ( targa_header.image_type )
1051                                         {
1052                                         case 1:
1053                                         case 9:
1054                                                 // colormapped
1055                                                 pindex = *fin++;
1056                                                 if ( pindex >= targa_header.colormap_length ) {
1057                                                         pindex = 0; // error
1058                                                 }
1059                                                 p = palette + pindex * 4;
1060                                                 red = p[0];
1061                                                 green = p[1];
1062                                                 blue = p[2];
1063                                                 alpha = p[3];
1064                                                 break;
1065                                         case 2:
1066                                         case 10:
1067                                                 // BGR or BGRA
1068                                                 blue = *fin++;
1069                                                 if ( fin < enddata ) {
1070                                                         green = *fin++;
1071                                                 }
1072                                                 if ( fin < enddata ) {
1073                                                         red = *fin++;
1074                                                 }
1075                                                 if ( targa_header.pixel_size == 32 && fin < enddata ) {
1076                                                         alpha = *fin++;
1077                                                 }
1078                                                 break;
1079                                         case 3:
1080                                         case 11:
1081                                                 // greyscale
1082                                                 red = green = blue = *fin++;
1083                                                 break;
1084                                         }
1085                                         if ( !alphabits ) {
1086                                                 alpha = 255;
1087                                         }
1088                                 }
1089                         }
1090                         *pixbuf++ = red;
1091                         *pixbuf++ = green;
1092                         *pixbuf++ = blue;
1093                         *pixbuf++ = alpha;
1094                         x++;
1095                         if ( x == image_width ) {
1096                                 // end of line, advance to next
1097                                 x = 0;
1098                                 y++;
1099                                 pixbuf += row_inc;
1100                         }
1101                 }
1102         }
1103
1104         *pic = image_rgba;
1105         if ( width ) {
1106                 *width = image_width;
1107         }
1108         if ( height ) {
1109                 *height = image_height;
1110         }
1111 }
1112
1113
1114 /*
1115    =============
1116    LoadTGA
1117    =============
1118  */
1119 void LoadTGA( const char *name, byte **pixels, int *width, int *height ){
1120         byte            *buffer;
1121         int nLen;
1122         //
1123         // load the file
1124         //
1125         nLen = vfsLoadFile( ( char * ) name, (void **)&buffer, 0 );
1126         if ( nLen == -1 ) {
1127                 Error( "Couldn't read %s", name );
1128         }
1129
1130         LoadTGABuffer( buffer, buffer + nLen, pixels, width, height );
1131
1132 }
1133
1134
1135 /*
1136    ================
1137    WriteTGA
1138    ================
1139  */
1140 void WriteTGA( const char *filename, byte *data, int width, int height ) {
1141         byte    *buffer;
1142         int i;
1143         int c;
1144         FILE    *f;
1145
1146         buffer = safe_malloc( width * height * 4 + 18 );
1147         memset( buffer, 0, 18 );
1148         buffer[2] = 2;      // uncompressed type
1149         buffer[12] = width & 255;
1150         buffer[13] = width >> 8;
1151         buffer[14] = height & 255;
1152         buffer[15] = height >> 8;
1153         buffer[16] = 32;    // pixel size
1154
1155         // swap rgb to bgr
1156         c = 18 + width * height * 4;
1157         for ( i = 18 ; i < c ; i += 4 )
1158         {
1159                 buffer[i] = data[i - 18 + 2];       // blue
1160                 buffer[i + 1] = data[i - 18 + 1];     // green
1161                 buffer[i + 2] = data[i - 18 + 0];     // red
1162                 buffer[i + 3] = data[i - 18 + 3];     // alpha
1163         }
1164
1165         f = fopen( filename, "wb" );
1166         fwrite( buffer, 1, c, f );
1167         fclose( f );
1168
1169         free( buffer );
1170 }
1171
1172 /*
1173    ============================================================================
1174
1175    LOAD32BITIMAGE
1176
1177    ============================================================================
1178  */
1179
1180 /*
1181    ==============
1182    Load32BitImage
1183
1184    Any of the return pointers can be NULL if you don't want them.
1185    ==============
1186  */
1187 void Load32BitImage( const char *name, unsigned **pixels,  int *width, int *height ){
1188         char ext[128];
1189         byte    *palette;
1190         byte    *pixels8;
1191         byte    *pixels32;
1192         int size;
1193         int i;
1194         int v;
1195
1196         ExtractFileExtension( name, ext );
1197         if ( !Q_stricmp( ext, "tga" ) ) {
1198                 LoadTGA( name, (byte **)pixels, width, height );
1199         }
1200         else {
1201                 Load256Image( name, &pixels8, &palette, width, height );
1202                 if ( !pixels ) {
1203                         return;
1204                 }
1205                 size = *width * *height;
1206                 pixels32 = safe_malloc( size * 4 );
1207                 *pixels = (unsigned *)pixels32;
1208                 for ( i = 0 ; i < size ; i++ ) {
1209                         v = pixels8[i];
1210                         pixels32[i * 4 + 0] = palette[ v * 3 + 0 ];
1211                         pixels32[i * 4 + 1] = palette[ v * 3 + 1 ];
1212                         pixels32[i * 4 + 2] = palette[ v * 3 + 2 ];
1213                         pixels32[i * 4 + 3] = 0xff;
1214                 }
1215         }
1216 }