Image_files.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /*
  2. ===========================================================================
  3. Doom 3 GPL Source Code
  4. Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
  6. Doom 3 Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
  17. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
  18. ===========================================================================
  19. */
  20. #include "../idlib/precompiled.h"
  21. #pragma hdrstop
  22. #include "tr_local.h"
  23. /*
  24. This file only has a single entry point:
  25. void R_LoadImage( const char *name, byte **pic, int *width, int *height, bool makePowerOf2 );
  26. */
  27. /*
  28. * Include file for users of JPEG library.
  29. * You will need to have included system headers that define at least
  30. * the typedefs FILE and size_t before you can include jpeglib.h.
  31. * (stdio.h is sufficient on ANSI-conforming systems.)
  32. * You may also wish to include "jerror.h".
  33. */
  34. extern "C" {
  35. #include "jpeg-6/jpeglib.h"
  36. // hooks from jpeg lib to our system
  37. void jpg_Error( const char *fmt, ... ) {
  38. va_list argptr;
  39. char msg[2048];
  40. va_start (argptr,fmt);
  41. vsprintf (msg,fmt,argptr);
  42. va_end (argptr);
  43. common->FatalError( "%s", msg );
  44. }
  45. void jpg_Printf( const char *fmt, ... ) {
  46. va_list argptr;
  47. char msg[2048];
  48. va_start (argptr,fmt);
  49. vsprintf (msg,fmt,argptr);
  50. va_end (argptr);
  51. common->Printf( "%s", msg );
  52. }
  53. }
  54. /*
  55. ================
  56. R_WriteTGA
  57. ================
  58. */
  59. void R_WriteTGA( const char *filename, const byte *data, int width, int height, bool flipVertical ) {
  60. byte *buffer;
  61. int i;
  62. int bufferSize = width*height*4 + 18;
  63. int imgStart = 18;
  64. buffer = (byte *)Mem_Alloc( bufferSize );
  65. memset( buffer, 0, 18 );
  66. buffer[2] = 2; // uncompressed type
  67. buffer[12] = width&255;
  68. buffer[13] = width>>8;
  69. buffer[14] = height&255;
  70. buffer[15] = height>>8;
  71. buffer[16] = 32; // pixel size
  72. if ( !flipVertical ) {
  73. buffer[17] = (1<<5); // flip bit, for normal top to bottom raster order
  74. }
  75. // swap rgb to bgr
  76. for ( i=imgStart ; i<bufferSize ; i+=4 ) {
  77. buffer[i] = data[i-imgStart+2]; // blue
  78. buffer[i+1] = data[i-imgStart+1]; // green
  79. buffer[i+2] = data[i-imgStart+0]; // red
  80. buffer[i+3] = data[i-imgStart+3]; // alpha
  81. }
  82. fileSystem->WriteFile( filename, buffer, bufferSize );
  83. Mem_Free (buffer);
  84. }
  85. /*
  86. ================
  87. R_WritePalTGA
  88. ================
  89. */
  90. void R_WritePalTGA( const char *filename, const byte *data, const byte *palette, int width, int height, bool flipVertical ) {
  91. byte *buffer;
  92. int i;
  93. int bufferSize = (width * height) + (256 * 3) + 18;
  94. int palStart = 18;
  95. int imgStart = 18 + (256 * 3);
  96. buffer = (byte *)Mem_Alloc( bufferSize );
  97. memset( buffer, 0, 18 );
  98. buffer[1] = 1; // color map type
  99. buffer[2] = 1; // uncompressed color mapped image
  100. buffer[5] = 0; // number of palette entries (lo)
  101. buffer[6] = 1; // number of palette entries (hi)
  102. buffer[7] = 24; // color map bpp
  103. buffer[12] = width&255;
  104. buffer[13] = width>>8;
  105. buffer[14] = height&255;
  106. buffer[15] = height>>8;
  107. buffer[16] = 8; // pixel size
  108. if ( !flipVertical ) {
  109. buffer[17] = (1<<5); // flip bit, for normal top to bottom raster order
  110. }
  111. // store palette, swapping rgb to bgr
  112. for ( i=palStart ; i<imgStart ; i+=3 ) {
  113. buffer[i] = palette[i-palStart+2]; // blue
  114. buffer[i+1] = palette[i-palStart+1]; // green
  115. buffer[i+2] = palette[i-palStart+0]; // red
  116. }
  117. // store the image data
  118. for ( i=imgStart ; i<bufferSize ; i++ ) {
  119. buffer[i] = data[i-imgStart];
  120. }
  121. fileSystem->WriteFile( filename, buffer, bufferSize );
  122. Mem_Free (buffer);
  123. }
  124. static void LoadBMP( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp );
  125. static void LoadTGA( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp );
  126. static void LoadJPG( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp );
  127. /*
  128. ========================================================================
  129. PCX files are used for 8 bit images
  130. ========================================================================
  131. */
  132. typedef struct {
  133. char manufacturer;
  134. char version;
  135. char encoding;
  136. char bits_per_pixel;
  137. unsigned short xmin,ymin,xmax,ymax;
  138. unsigned short hres,vres;
  139. unsigned char palette[48];
  140. char reserved;
  141. char color_planes;
  142. unsigned short bytes_per_line;
  143. unsigned short palette_type;
  144. char filler[58];
  145. unsigned char data; // unbounded
  146. } pcx_t;
  147. /*
  148. ========================================================================
  149. TGA files are used for 24/32 bit images
  150. ========================================================================
  151. */
  152. typedef struct _TargaHeader {
  153. unsigned char id_length, colormap_type, image_type;
  154. unsigned short colormap_index, colormap_length;
  155. unsigned char colormap_size;
  156. unsigned short x_origin, y_origin, width, height;
  157. unsigned char pixel_size, attributes;
  158. } TargaHeader;
  159. /*
  160. =========================================================
  161. BMP LOADING
  162. =========================================================
  163. */
  164. typedef struct
  165. {
  166. char id[2];
  167. unsigned long fileSize;
  168. unsigned long reserved0;
  169. unsigned long bitmapDataOffset;
  170. unsigned long bitmapHeaderSize;
  171. unsigned long width;
  172. unsigned long height;
  173. unsigned short planes;
  174. unsigned short bitsPerPixel;
  175. unsigned long compression;
  176. unsigned long bitmapDataSize;
  177. unsigned long hRes;
  178. unsigned long vRes;
  179. unsigned long colors;
  180. unsigned long importantColors;
  181. unsigned char palette[256][4];
  182. } BMPHeader_t;
  183. /*
  184. ==============
  185. LoadBMP
  186. ==============
  187. */
  188. static void LoadBMP( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp )
  189. {
  190. int columns, rows, numPixels;
  191. byte *pixbuf;
  192. int row, column;
  193. byte *buf_p;
  194. byte *buffer;
  195. int length;
  196. BMPHeader_t bmpHeader;
  197. byte *bmpRGBA;
  198. if ( !pic ) {
  199. fileSystem->ReadFile ( name, NULL, timestamp );
  200. return; // just getting timestamp
  201. }
  202. *pic = NULL;
  203. //
  204. // load the file
  205. //
  206. length = fileSystem->ReadFile( name, (void **)&buffer, timestamp );
  207. if ( !buffer ) {
  208. return;
  209. }
  210. buf_p = buffer;
  211. bmpHeader.id[0] = *buf_p++;
  212. bmpHeader.id[1] = *buf_p++;
  213. bmpHeader.fileSize = LittleLong( * ( long * ) buf_p );
  214. buf_p += 4;
  215. bmpHeader.reserved0 = LittleLong( * ( long * ) buf_p );
  216. buf_p += 4;
  217. bmpHeader.bitmapDataOffset = LittleLong( * ( long * ) buf_p );
  218. buf_p += 4;
  219. bmpHeader.bitmapHeaderSize = LittleLong( * ( long * ) buf_p );
  220. buf_p += 4;
  221. bmpHeader.width = LittleLong( * ( long * ) buf_p );
  222. buf_p += 4;
  223. bmpHeader.height = LittleLong( * ( long * ) buf_p );
  224. buf_p += 4;
  225. bmpHeader.planes = LittleShort( * ( short * ) buf_p );
  226. buf_p += 2;
  227. bmpHeader.bitsPerPixel = LittleShort( * ( short * ) buf_p );
  228. buf_p += 2;
  229. bmpHeader.compression = LittleLong( * ( long * ) buf_p );
  230. buf_p += 4;
  231. bmpHeader.bitmapDataSize = LittleLong( * ( long * ) buf_p );
  232. buf_p += 4;
  233. bmpHeader.hRes = LittleLong( * ( long * ) buf_p );
  234. buf_p += 4;
  235. bmpHeader.vRes = LittleLong( * ( long * ) buf_p );
  236. buf_p += 4;
  237. bmpHeader.colors = LittleLong( * ( long * ) buf_p );
  238. buf_p += 4;
  239. bmpHeader.importantColors = LittleLong( * ( long * ) buf_p );
  240. buf_p += 4;
  241. memcpy( bmpHeader.palette, buf_p, sizeof( bmpHeader.palette ) );
  242. if ( bmpHeader.bitsPerPixel == 8 )
  243. buf_p += 1024;
  244. if ( bmpHeader.id[0] != 'B' && bmpHeader.id[1] != 'M' )
  245. {
  246. common->Error( "LoadBMP: only Windows-style BMP files supported (%s)\n", name );
  247. }
  248. if ( bmpHeader.fileSize != length )
  249. {
  250. common->Error( "LoadBMP: header size does not match file size (%lu vs. %d) (%s)\n", bmpHeader.fileSize, length, name );
  251. }
  252. if ( bmpHeader.compression != 0 )
  253. {
  254. common->Error( "LoadBMP: only uncompressed BMP files supported (%s)\n", name );
  255. }
  256. if ( bmpHeader.bitsPerPixel < 8 )
  257. {
  258. common->Error( "LoadBMP: monochrome and 4-bit BMP files not supported (%s)\n", name );
  259. }
  260. columns = bmpHeader.width;
  261. rows = bmpHeader.height;
  262. if ( rows < 0 )
  263. rows = -rows;
  264. numPixels = columns * rows;
  265. if ( width )
  266. *width = columns;
  267. if ( height )
  268. *height = rows;
  269. bmpRGBA = (byte *)R_StaticAlloc( numPixels * 4 );
  270. *pic = bmpRGBA;
  271. for ( row = rows-1; row >= 0; row-- )
  272. {
  273. pixbuf = bmpRGBA + row*columns*4;
  274. for ( column = 0; column < columns; column++ )
  275. {
  276. unsigned char red, green, blue, alpha;
  277. int palIndex;
  278. unsigned short shortPixel;
  279. switch ( bmpHeader.bitsPerPixel )
  280. {
  281. case 8:
  282. palIndex = *buf_p++;
  283. *pixbuf++ = bmpHeader.palette[palIndex][2];
  284. *pixbuf++ = bmpHeader.palette[palIndex][1];
  285. *pixbuf++ = bmpHeader.palette[palIndex][0];
  286. *pixbuf++ = 0xff;
  287. break;
  288. case 16:
  289. shortPixel = * ( unsigned short * ) pixbuf;
  290. pixbuf += 2;
  291. *pixbuf++ = ( shortPixel & ( 31 << 10 ) ) >> 7;
  292. *pixbuf++ = ( shortPixel & ( 31 << 5 ) ) >> 2;
  293. *pixbuf++ = ( shortPixel & ( 31 ) ) << 3;
  294. *pixbuf++ = 0xff;
  295. break;
  296. case 24:
  297. blue = *buf_p++;
  298. green = *buf_p++;
  299. red = *buf_p++;
  300. *pixbuf++ = red;
  301. *pixbuf++ = green;
  302. *pixbuf++ = blue;
  303. *pixbuf++ = 255;
  304. break;
  305. case 32:
  306. blue = *buf_p++;
  307. green = *buf_p++;
  308. red = *buf_p++;
  309. alpha = *buf_p++;
  310. *pixbuf++ = red;
  311. *pixbuf++ = green;
  312. *pixbuf++ = blue;
  313. *pixbuf++ = alpha;
  314. break;
  315. default:
  316. common->Error( "LoadBMP: illegal pixel_size '%d' in file '%s'\n", bmpHeader.bitsPerPixel, name );
  317. break;
  318. }
  319. }
  320. }
  321. fileSystem->FreeFile( buffer );
  322. }
  323. /*
  324. =================================================================
  325. PCX LOADING
  326. =================================================================
  327. */
  328. /*
  329. ==============
  330. LoadPCX
  331. ==============
  332. */
  333. static void LoadPCX ( const char *filename, byte **pic, byte **palette, int *width, int *height,
  334. ID_TIME_T *timestamp ) {
  335. byte *raw;
  336. pcx_t *pcx;
  337. int x, y;
  338. int len;
  339. int dataByte, runLength;
  340. byte *out, *pix;
  341. int xmax, ymax;
  342. if ( !pic ) {
  343. fileSystem->ReadFile( filename, NULL, timestamp );
  344. return; // just getting timestamp
  345. }
  346. *pic = NULL;
  347. *palette = NULL;
  348. //
  349. // load the file
  350. //
  351. len = fileSystem->ReadFile( filename, (void **)&raw, timestamp );
  352. if (!raw) {
  353. return;
  354. }
  355. //
  356. // parse the PCX file
  357. //
  358. pcx = (pcx_t *)raw;
  359. raw = &pcx->data;
  360. xmax = LittleShort(pcx->xmax);
  361. ymax = LittleShort(pcx->ymax);
  362. if (pcx->manufacturer != 0x0a
  363. || pcx->version != 5
  364. || pcx->encoding != 1
  365. || pcx->bits_per_pixel != 8
  366. || xmax >= 1024
  367. || ymax >= 1024)
  368. {
  369. common->Printf( "Bad pcx file %s (%i x %i) (%i x %i)\n", filename, xmax+1, ymax+1, pcx->xmax, pcx->ymax);
  370. return;
  371. }
  372. out = (byte *)R_StaticAlloc( (ymax+1) * (xmax+1) );
  373. *pic = out;
  374. pix = out;
  375. if (palette)
  376. {
  377. *palette = (byte *)R_StaticAlloc(768);
  378. memcpy (*palette, (byte *)pcx + len - 768, 768);
  379. }
  380. if (width)
  381. *width = xmax+1;
  382. if (height)
  383. *height = ymax+1;
  384. // FIXME: use bytes_per_line here?
  385. for (y=0 ; y<=ymax ; y++, pix += xmax+1)
  386. {
  387. for (x=0 ; x<=xmax ; )
  388. {
  389. dataByte = *raw++;
  390. if((dataByte & 0xC0) == 0xC0)
  391. {
  392. runLength = dataByte & 0x3F;
  393. dataByte = *raw++;
  394. }
  395. else
  396. runLength = 1;
  397. while(runLength-- > 0)
  398. pix[x++] = dataByte;
  399. }
  400. }
  401. if ( raw - (byte *)pcx > len)
  402. {
  403. common->Printf( "PCX file %s was malformed", filename );
  404. R_StaticFree (*pic);
  405. *pic = NULL;
  406. }
  407. fileSystem->FreeFile( pcx );
  408. }
  409. /*
  410. ==============
  411. LoadPCX32
  412. ==============
  413. */
  414. static void LoadPCX32 ( const char *filename, byte **pic, int *width, int *height, ID_TIME_T *timestamp) {
  415. byte *palette;
  416. byte *pic8;
  417. int i, c, p;
  418. byte *pic32;
  419. if ( !pic ) {
  420. fileSystem->ReadFile( filename, NULL, timestamp );
  421. return; // just getting timestamp
  422. }
  423. LoadPCX (filename, &pic8, &palette, width, height, timestamp);
  424. if (!pic8) {
  425. *pic = NULL;
  426. return;
  427. }
  428. c = (*width) * (*height);
  429. pic32 = *pic = (byte *)R_StaticAlloc(4 * c );
  430. for (i = 0 ; i < c ; i++) {
  431. p = pic8[i];
  432. pic32[0] = palette[p*3];
  433. pic32[1] = palette[p*3 + 1];
  434. pic32[2] = palette[p*3 + 2];
  435. pic32[3] = 255;
  436. pic32 += 4;
  437. }
  438. R_StaticFree( pic8 );
  439. R_StaticFree( palette );
  440. }
  441. /*
  442. =========================================================
  443. TARGA LOADING
  444. =========================================================
  445. */
  446. /*
  447. =============
  448. LoadTGA
  449. =============
  450. */
  451. static void LoadTGA( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp ) {
  452. int columns, rows, numPixels, fileSize, numBytes;
  453. byte *pixbuf;
  454. int row, column;
  455. byte *buf_p;
  456. byte *buffer;
  457. TargaHeader targa_header;
  458. byte *targa_rgba;
  459. if ( !pic ) {
  460. fileSystem->ReadFile( name, NULL, timestamp );
  461. return; // just getting timestamp
  462. }
  463. *pic = NULL;
  464. //
  465. // load the file
  466. //
  467. fileSize = fileSystem->ReadFile( name, (void **)&buffer, timestamp );
  468. if ( !buffer ) {
  469. return;
  470. }
  471. buf_p = buffer;
  472. targa_header.id_length = *buf_p++;
  473. targa_header.colormap_type = *buf_p++;
  474. targa_header.image_type = *buf_p++;
  475. targa_header.colormap_index = LittleShort ( *(short *)buf_p );
  476. buf_p += 2;
  477. targa_header.colormap_length = LittleShort ( *(short *)buf_p );
  478. buf_p += 2;
  479. targa_header.colormap_size = *buf_p++;
  480. targa_header.x_origin = LittleShort ( *(short *)buf_p );
  481. buf_p += 2;
  482. targa_header.y_origin = LittleShort ( *(short *)buf_p );
  483. buf_p += 2;
  484. targa_header.width = LittleShort ( *(short *)buf_p );
  485. buf_p += 2;
  486. targa_header.height = LittleShort ( *(short *)buf_p );
  487. buf_p += 2;
  488. targa_header.pixel_size = *buf_p++;
  489. targa_header.attributes = *buf_p++;
  490. if ( targa_header.image_type != 2 && targa_header.image_type != 10 && targa_header.image_type != 3 ) {
  491. common->Error( "LoadTGA( %s ): Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n", name );
  492. }
  493. if ( targa_header.colormap_type != 0 ) {
  494. common->Error( "LoadTGA( %s ): colormaps not supported\n", name );
  495. }
  496. if ( ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) && targa_header.image_type != 3 ) {
  497. common->Error( "LoadTGA( %s ): Only 32 or 24 bit images supported (no colormaps)\n", name );
  498. }
  499. if ( targa_header.image_type == 2 || targa_header.image_type == 3 ) {
  500. numBytes = targa_header.width * targa_header.height * ( targa_header.pixel_size >> 3 );
  501. if ( numBytes > fileSize - 18 - targa_header.id_length ) {
  502. common->Error( "LoadTGA( %s ): incomplete file\n", name );
  503. }
  504. }
  505. columns = targa_header.width;
  506. rows = targa_header.height;
  507. numPixels = columns * rows;
  508. if ( width ) {
  509. *width = columns;
  510. }
  511. if ( height ) {
  512. *height = rows;
  513. }
  514. targa_rgba = (byte *)R_StaticAlloc(numPixels*4);
  515. *pic = targa_rgba;
  516. if ( targa_header.id_length != 0 ) {
  517. buf_p += targa_header.id_length; // skip TARGA image comment
  518. }
  519. if ( targa_header.image_type == 2 || targa_header.image_type == 3 )
  520. {
  521. // Uncompressed RGB or gray scale image
  522. for( row = rows - 1; row >= 0; row-- )
  523. {
  524. pixbuf = targa_rgba + row*columns*4;
  525. for( column = 0; column < columns; column++)
  526. {
  527. unsigned char red,green,blue,alphabyte;
  528. switch( targa_header.pixel_size )
  529. {
  530. case 8:
  531. blue = *buf_p++;
  532. green = blue;
  533. red = blue;
  534. *pixbuf++ = red;
  535. *pixbuf++ = green;
  536. *pixbuf++ = blue;
  537. *pixbuf++ = 255;
  538. break;
  539. case 24:
  540. blue = *buf_p++;
  541. green = *buf_p++;
  542. red = *buf_p++;
  543. *pixbuf++ = red;
  544. *pixbuf++ = green;
  545. *pixbuf++ = blue;
  546. *pixbuf++ = 255;
  547. break;
  548. case 32:
  549. blue = *buf_p++;
  550. green = *buf_p++;
  551. red = *buf_p++;
  552. alphabyte = *buf_p++;
  553. *pixbuf++ = red;
  554. *pixbuf++ = green;
  555. *pixbuf++ = blue;
  556. *pixbuf++ = alphabyte;
  557. break;
  558. default:
  559. common->Error( "LoadTGA( %s ): illegal pixel_size '%d'\n", name, targa_header.pixel_size );
  560. break;
  561. }
  562. }
  563. }
  564. }
  565. else if ( targa_header.image_type == 10 ) { // Runlength encoded RGB images
  566. unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
  567. red = 0;
  568. green = 0;
  569. blue = 0;
  570. alphabyte = 0xff;
  571. for( row = rows - 1; row >= 0; row-- ) {
  572. pixbuf = targa_rgba + row*columns*4;
  573. for( column = 0; column < columns; ) {
  574. packetHeader= *buf_p++;
  575. packetSize = 1 + (packetHeader & 0x7f);
  576. if ( packetHeader & 0x80 ) { // run-length packet
  577. switch( targa_header.pixel_size ) {
  578. case 24:
  579. blue = *buf_p++;
  580. green = *buf_p++;
  581. red = *buf_p++;
  582. alphabyte = 255;
  583. break;
  584. case 32:
  585. blue = *buf_p++;
  586. green = *buf_p++;
  587. red = *buf_p++;
  588. alphabyte = *buf_p++;
  589. break;
  590. default:
  591. common->Error( "LoadTGA( %s ): illegal pixel_size '%d'\n", name, targa_header.pixel_size );
  592. break;
  593. }
  594. for( j = 0; j < packetSize; j++ ) {
  595. *pixbuf++=red;
  596. *pixbuf++=green;
  597. *pixbuf++=blue;
  598. *pixbuf++=alphabyte;
  599. column++;
  600. if ( column == columns ) { // run spans across rows
  601. column = 0;
  602. if ( row > 0) {
  603. row--;
  604. }
  605. else {
  606. goto breakOut;
  607. }
  608. pixbuf = targa_rgba + row*columns*4;
  609. }
  610. }
  611. }
  612. else { // non run-length packet
  613. for( j = 0; j < packetSize; j++ ) {
  614. switch( targa_header.pixel_size ) {
  615. case 24:
  616. blue = *buf_p++;
  617. green = *buf_p++;
  618. red = *buf_p++;
  619. *pixbuf++ = red;
  620. *pixbuf++ = green;
  621. *pixbuf++ = blue;
  622. *pixbuf++ = 255;
  623. break;
  624. case 32:
  625. blue = *buf_p++;
  626. green = *buf_p++;
  627. red = *buf_p++;
  628. alphabyte = *buf_p++;
  629. *pixbuf++ = red;
  630. *pixbuf++ = green;
  631. *pixbuf++ = blue;
  632. *pixbuf++ = alphabyte;
  633. break;
  634. default:
  635. common->Error( "LoadTGA( %s ): illegal pixel_size '%d'\n", name, targa_header.pixel_size );
  636. break;
  637. }
  638. column++;
  639. if ( column == columns ) { // pixel packet run spans across rows
  640. column = 0;
  641. if ( row > 0 ) {
  642. row--;
  643. }
  644. else {
  645. goto breakOut;
  646. }
  647. pixbuf = targa_rgba + row*columns*4;
  648. }
  649. }
  650. }
  651. }
  652. breakOut: ;
  653. }
  654. }
  655. if ( (targa_header.attributes & (1<<5)) ) { // image flp bit
  656. R_VerticalFlip( *pic, *width, *height );
  657. }
  658. fileSystem->FreeFile( buffer );
  659. }
  660. /*
  661. =========================================================
  662. JPG LOADING
  663. Interfaces with the huge libjpeg
  664. =========================================================
  665. */
  666. /*
  667. =============
  668. LoadJPG
  669. =============
  670. */
  671. static void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height, ID_TIME_T *timestamp ) {
  672. /* This struct contains the JPEG decompression parameters and pointers to
  673. * working space (which is allocated as needed by the JPEG library).
  674. */
  675. struct jpeg_decompress_struct cinfo;
  676. /* We use our private extension JPEG error handler.
  677. * Note that this struct must live as long as the main JPEG parameter
  678. * struct, to avoid dangling-pointer problems.
  679. */
  680. /* This struct represents a JPEG error handler. It is declared separately
  681. * because applications often want to supply a specialized error handler
  682. * (see the second half of this file for an example). But here we just
  683. * take the easy way out and use the standard error handler, which will
  684. * print a message on stderr and call exit() if compression fails.
  685. * Note that this struct must live as long as the main JPEG parameter
  686. * struct, to avoid dangling-pointer problems.
  687. */
  688. struct jpeg_error_mgr jerr;
  689. /* More stuff */
  690. JSAMPARRAY buffer; /* Output row buffer */
  691. int row_stride; /* physical row width in output buffer */
  692. unsigned char *out;
  693. byte *fbuffer;
  694. byte *bbuf;
  695. /* In this example we want to open the input file before doing anything else,
  696. * so that the setjmp() error recovery below can assume the file is open.
  697. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  698. * requires it in order to read binary files.
  699. */
  700. // JDC: because fill_input_buffer() blindly copies INPUT_BUF_SIZE bytes,
  701. // we need to make sure the file buffer is padded or it may crash
  702. if ( pic ) {
  703. *pic = NULL; // until proven otherwise
  704. }
  705. {
  706. int len;
  707. idFile *f;
  708. f = fileSystem->OpenFileRead( filename );
  709. if ( !f ) {
  710. return;
  711. }
  712. len = f->Length();
  713. if ( timestamp ) {
  714. *timestamp = f->Timestamp();
  715. }
  716. if ( !pic ) {
  717. fileSystem->CloseFile( f );
  718. return; // just getting timestamp
  719. }
  720. fbuffer = (byte *)Mem_ClearedAlloc( len + 4096 );
  721. f->Read( fbuffer, len );
  722. fileSystem->CloseFile( f );
  723. }
  724. /* Step 1: allocate and initialize JPEG decompression object */
  725. /* We have to set up the error handler first, in case the initialization
  726. * step fails. (Unlikely, but it could happen if you are out of memory.)
  727. * This routine fills in the contents of struct jerr, and returns jerr's
  728. * address which we place into the link field in cinfo.
  729. */
  730. cinfo.err = jpeg_std_error(&jerr);
  731. /* Now we can initialize the JPEG decompression object. */
  732. jpeg_create_decompress(&cinfo);
  733. /* Step 2: specify data source (eg, a file) */
  734. jpeg_stdio_src(&cinfo, fbuffer);
  735. /* Step 3: read file parameters with jpeg_read_header() */
  736. (void) jpeg_read_header(&cinfo, true );
  737. /* We can ignore the return value from jpeg_read_header since
  738. * (a) suspension is not possible with the stdio data source, and
  739. * (b) we passed TRUE to reject a tables-only JPEG file as an error.
  740. * See libjpeg.doc for more info.
  741. */
  742. /* Step 4: set parameters for decompression */
  743. /* In this example, we don't need to change any of the defaults set by
  744. * jpeg_read_header(), so we do nothing here.
  745. */
  746. /* Step 5: Start decompressor */
  747. (void) jpeg_start_decompress(&cinfo);
  748. /* We can ignore the return value since suspension is not possible
  749. * with the stdio data source.
  750. */
  751. /* We may need to do some setup of our own at this point before reading
  752. * the data. After jpeg_start_decompress() we have the correct scaled
  753. * output image dimensions available, as well as the output colormap
  754. * if we asked for color quantization.
  755. * In this example, we need to make an output work buffer of the right size.
  756. */
  757. /* JSAMPLEs per row in output buffer */
  758. row_stride = cinfo.output_width * cinfo.output_components;
  759. if (cinfo.output_components!=4) {
  760. common->DWarning( "JPG %s is unsupported color depth (%d)",
  761. filename, cinfo.output_components);
  762. }
  763. out = (byte *)R_StaticAlloc(cinfo.output_width*cinfo.output_height*4);
  764. *pic = out;
  765. *width = cinfo.output_width;
  766. *height = cinfo.output_height;
  767. /* Step 6: while (scan lines remain to be read) */
  768. /* jpeg_read_scanlines(...); */
  769. /* Here we use the library's state variable cinfo.output_scanline as the
  770. * loop counter, so that we don't have to keep track ourselves.
  771. */
  772. while (cinfo.output_scanline < cinfo.output_height) {
  773. /* jpeg_read_scanlines expects an array of pointers to scanlines.
  774. * Here the array is only one element long, but you could ask for
  775. * more than one scanline at a time if that's more convenient.
  776. */
  777. bbuf = ((out+(row_stride*cinfo.output_scanline)));
  778. buffer = &bbuf;
  779. (void) jpeg_read_scanlines(&cinfo, buffer, 1);
  780. }
  781. // clear all the alphas to 255
  782. {
  783. int i, j;
  784. byte *buf;
  785. buf = *pic;
  786. j = cinfo.output_width * cinfo.output_height * 4;
  787. for ( i = 3 ; i < j ; i+=4 ) {
  788. buf[i] = 255;
  789. }
  790. }
  791. /* Step 7: Finish decompression */
  792. (void) jpeg_finish_decompress(&cinfo);
  793. /* We can ignore the return value since suspension is not possible
  794. * with the stdio data source.
  795. */
  796. /* Step 8: Release JPEG decompression object */
  797. /* This is an important step since it will release a good deal of memory. */
  798. jpeg_destroy_decompress(&cinfo);
  799. /* After finish_decompress, we can close the input file.
  800. * Here we postpone it until after no more JPEG errors are possible,
  801. * so as to simplify the setjmp error logic above. (Actually, I don't
  802. * think that jpeg_destroy can do an error exit, but why assume anything...)
  803. */
  804. Mem_Free( fbuffer );
  805. /* At this point you may want to check to see whether any corrupt-data
  806. * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
  807. */
  808. /* And we're done! */
  809. }
  810. //===================================================================
  811. /*
  812. =================
  813. R_LoadImage
  814. Loads any of the supported image types into a cannonical
  815. 32 bit format.
  816. Automatically attempts to load .jpg files if .tga files fail to load.
  817. *pic will be NULL if the load failed.
  818. Anything that is going to make this into a texture would use
  819. makePowerOf2 = true, but something loading an image as a lookup
  820. table of some sort would leave it in identity form.
  821. It is important to do this at image load time instead of texture load
  822. time for bump maps.
  823. Timestamp may be NULL if the value is going to be ignored
  824. If pic is NULL, the image won't actually be loaded, it will just find the
  825. timestamp.
  826. =================
  827. */
  828. void R_LoadImage( const char *cname, byte **pic, int *width, int *height, ID_TIME_T *timestamp, bool makePowerOf2 ) {
  829. idStr name = cname;
  830. if ( pic ) {
  831. *pic = NULL;
  832. }
  833. if ( timestamp ) {
  834. *timestamp = 0xFFFFFFFF;
  835. }
  836. if ( width ) {
  837. *width = 0;
  838. }
  839. if ( height ) {
  840. *height = 0;
  841. }
  842. name.DefaultFileExtension( ".tga" );
  843. if (name.Length()<5) {
  844. return;
  845. }
  846. name.ToLower();
  847. idStr ext;
  848. name.ExtractFileExtension( ext );
  849. if ( ext == "tga" ) {
  850. LoadTGA( name.c_str(), pic, width, height, timestamp ); // try tga first
  851. if ( ( pic && *pic == 0 ) || ( timestamp && *timestamp == -1 ) ) {
  852. name.StripFileExtension();
  853. name.DefaultFileExtension( ".jpg" );
  854. LoadJPG( name.c_str(), pic, width, height, timestamp );
  855. }
  856. } else if ( ext == "pcx" ) {
  857. LoadPCX32( name.c_str(), pic, width, height, timestamp );
  858. } else if ( ext == "bmp" ) {
  859. LoadBMP( name.c_str(), pic, width, height, timestamp );
  860. } else if ( ext == "jpg" ) {
  861. LoadJPG( name.c_str(), pic, width, height, timestamp );
  862. }
  863. if ( ( width && *width < 1 ) || ( height && *height < 1 ) ) {
  864. if ( pic && *pic ) {
  865. R_StaticFree( *pic );
  866. *pic = 0;
  867. }
  868. }
  869. //
  870. // convert to exact power of 2 sizes
  871. //
  872. if ( pic && *pic && makePowerOf2 ) {
  873. int w, h;
  874. int scaled_width, scaled_height;
  875. byte *resampledBuffer;
  876. w = *width;
  877. h = *height;
  878. for (scaled_width = 1 ; scaled_width < w ; scaled_width<<=1)
  879. ;
  880. for (scaled_height = 1 ; scaled_height < h ; scaled_height<<=1)
  881. ;
  882. if ( scaled_width != w || scaled_height != h ) {
  883. if ( globalImages->image_roundDown.GetBool() && scaled_width > w ) {
  884. scaled_width >>= 1;
  885. }
  886. if ( globalImages->image_roundDown.GetBool() && scaled_height > h ) {
  887. scaled_height >>= 1;
  888. }
  889. resampledBuffer = R_ResampleTexture( *pic, w, h, scaled_width, scaled_height );
  890. R_StaticFree( *pic );
  891. *pic = resampledBuffer;
  892. *width = scaled_width;
  893. *height = scaled_height;
  894. }
  895. }
  896. }
  897. /*
  898. =======================
  899. R_LoadCubeImages
  900. Loads six files with proper extensions
  901. =======================
  902. */
  903. bool R_LoadCubeImages( const char *imgName, cubeFiles_t extensions, byte *pics[6], int *outSize, ID_TIME_T *timestamp ) {
  904. int i, j;
  905. char *cameraSides[6] = { "_forward.tga", "_back.tga", "_left.tga", "_right.tga",
  906. "_up.tga", "_down.tga" };
  907. char *axisSides[6] = { "_px.tga", "_nx.tga", "_py.tga", "_ny.tga",
  908. "_pz.tga", "_nz.tga" };
  909. char **sides;
  910. char fullName[MAX_IMAGE_NAME];
  911. int width, height, size = 0;
  912. if ( extensions == CF_CAMERA ) {
  913. sides = cameraSides;
  914. } else {
  915. sides = axisSides;
  916. }
  917. // FIXME: precompressed cube map files
  918. if ( pics ) {
  919. memset( pics, 0, 6*sizeof(pics[0]) );
  920. }
  921. if ( timestamp ) {
  922. *timestamp = 0;
  923. }
  924. for ( i = 0 ; i < 6 ; i++ ) {
  925. idStr::snPrintf( fullName, sizeof( fullName ), "%s%s", imgName, sides[i] );
  926. ID_TIME_T thisTime;
  927. if ( !pics ) {
  928. // just checking timestamps
  929. R_LoadImageProgram( fullName, NULL, &width, &height, &thisTime );
  930. } else {
  931. R_LoadImageProgram( fullName, &pics[i], &width, &height, &thisTime );
  932. }
  933. if ( thisTime == FILE_NOT_FOUND_TIMESTAMP ) {
  934. break;
  935. }
  936. if ( i == 0 ) {
  937. size = width;
  938. }
  939. if ( width != size || height != size ) {
  940. common->Warning( "Mismatched sizes on cube map '%s'", imgName );
  941. break;
  942. }
  943. if ( timestamp ) {
  944. if ( thisTime > *timestamp ) {
  945. *timestamp = thisTime;
  946. }
  947. }
  948. if ( pics && extensions == CF_CAMERA ) {
  949. // convert from "camera" images to native cube map images
  950. switch( i ) {
  951. case 0: // forward
  952. R_RotatePic( pics[i], width);
  953. break;
  954. case 1: // back
  955. R_RotatePic( pics[i], width);
  956. R_HorizontalFlip( pics[i], width, height );
  957. R_VerticalFlip( pics[i], width, height );
  958. break;
  959. case 2: // left
  960. R_VerticalFlip( pics[i], width, height );
  961. break;
  962. case 3: // right
  963. R_HorizontalFlip( pics[i], width, height );
  964. break;
  965. case 4: // up
  966. R_RotatePic( pics[i], width);
  967. break;
  968. case 5: // down
  969. R_RotatePic( pics[i], width);
  970. break;
  971. }
  972. }
  973. }
  974. if ( i != 6 ) {
  975. // we had an error, so free everything
  976. if ( pics ) {
  977. for ( j = 0 ; j < i ; j++ ) {
  978. R_StaticFree( pics[j] );
  979. }
  980. }
  981. if ( timestamp ) {
  982. *timestamp = 0;
  983. }
  984. return false;
  985. }
  986. if ( outSize ) {
  987. *outSize = size;
  988. }
  989. return true;
  990. }