tga.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. ////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // WARNING
  4. //
  5. // THIS DOES NOT DEAL WITH VERTICALLY FLIPPED DATA CORRECTLY
  6. //
  7. ////////////////////////////////////////////////////////////////////////////////
  8. /* This file is derived from (actually an earlier version of)... */
  9. /* The GIMP -- an image manipulation program
  10. * Copyright (C) 1995 Spencer Kimball and Peter Mattis
  11. *
  12. * $Id: tga.cpp,v 1.1.2.5 2007-05-10 02:10:07 elif Exp $
  13. * TrueVision Targa loading and saving file filter for the Gimp.
  14. * Targa code Copyright (C) 1997 Raphael FRANCOIS and Gordon Matzigkeit
  15. *
  16. * The Targa reading and writing code was written from scratch by
  17. * Raphael FRANCOIS <fraph@ibm.net> and Gordon Matzigkeit
  18. * <gord@gnu.ai.mit.edu> based on the TrueVision TGA File Format
  19. * Specification, Version 2.0:
  20. *
  21. * <URL:ftp://ftp.truevision.com/pub/TGA.File.Format.Spec/>
  22. *
  23. * It does not contain any code written for other TGA file loaders.
  24. * Not even the RLE handling. ;)
  25. *
  26. * This program is free software; you can redistribute it and/or modify
  27. * it under the terms of the GNU General Public License as published by
  28. * the Free Software Foundation; either version 2 of the License, or
  29. * (at your option) any later version.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU General Public License
  37. * along with this program; if not, write to the Free Software
  38. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  39. */
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <string.h>
  43. #include <assert.h>
  44. #include "tga.h"
  45. static char error[256];
  46. static unsigned int _verbose = 0;
  47. static int totbytes = 0;
  48. typedef struct {
  49. unsigned char *statebuf;
  50. int statelen;
  51. int laststate;
  52. } RLEstate;
  53. IGL_INLINE static int
  54. std_fread(RLEstate * /*rleInfo*/, unsigned char *buf, size_t datasize, size_t nelems, FILE *fp)
  55. {
  56. if (_verbose > 1) {
  57. totbytes += nelems * datasize;
  58. printf("TGA: std_fread %d (total %d)\n",
  59. (int)(nelems * datasize), totbytes);
  60. }
  61. return fread(buf, datasize, nelems, fp);
  62. }
  63. #define MIN(a,b) (((a) < (b)) ? (a) : (b))
  64. #define RLE_PACKETSIZE 0x80
  65. /* Decode a bufferful of file. */
  66. IGL_INLINE static int
  67. rle_fread(RLEstate *rleInfo, unsigned char *vbuf, size_t datasize, size_t nelems, FILE *fp)
  68. {
  69. unsigned char *buf = vbuf;
  70. int j, k;
  71. int buflen, count, bytes, curbytes;
  72. unsigned char *p;
  73. /* Scale the buffer length. */
  74. buflen = nelems * datasize;
  75. j = 0;
  76. curbytes = totbytes;
  77. while (j < buflen) {
  78. if (rleInfo->laststate < rleInfo->statelen) {
  79. /* Copy bytes from our previously decoded buffer. */
  80. bytes = MIN(buflen - j, rleInfo->statelen - rleInfo->laststate);
  81. memcpy(buf + j, rleInfo->statebuf + rleInfo->laststate, bytes);
  82. j += bytes;
  83. rleInfo->laststate += bytes;
  84. /* If we used up all of our state bytes, then reset them. */
  85. if (rleInfo->laststate >= rleInfo->statelen) {
  86. rleInfo->laststate = 0;
  87. rleInfo->statelen = 0;
  88. }
  89. /* If we filled the buffer, then exit the loop. */
  90. if (j >= buflen) break;
  91. }
  92. /* Decode the next packet. */
  93. count = fgetc(fp);
  94. if (count == EOF) {
  95. if (_verbose) printf("TGA: hit EOF while looking for count\n");
  96. return j / datasize;
  97. }
  98. /* Scale the byte length to the size of the data. */
  99. bytes = ((count & ~RLE_PACKETSIZE) + 1) * datasize;
  100. if (j + bytes <= buflen) {
  101. /* We can copy directly into the image buffer. */
  102. p = buf + j;
  103. } else {
  104. #ifdef PROFILE
  105. printf("TGA: needed to use statebuf for %d bytes\n", buflen - j);
  106. #endif
  107. /* Allocate the state buffer if we haven't already. */
  108. if (!rleInfo->statebuf) {
  109. rleInfo->statebuf = (unsigned char *) malloc(RLE_PACKETSIZE * datasize);
  110. }
  111. p = rleInfo->statebuf;
  112. }
  113. if (count & RLE_PACKETSIZE) {
  114. /* Fill the buffer with the next value. */
  115. if (fread(p, datasize, 1, fp) != 1) {
  116. if (_verbose) {
  117. printf("TGA: EOF while reading %d/%d element RLE packet\n",
  118. bytes, (int)datasize);
  119. }
  120. return j / datasize;
  121. }
  122. /* Optimized case for single-byte encoded data. */
  123. if (datasize == 1) {
  124. memset(p + 1, *p, bytes - 1);
  125. } else {
  126. for (k = datasize; k < bytes; k += datasize) {
  127. memcpy(p + k, p, datasize);
  128. }
  129. }
  130. } else {
  131. /* Read in the buffer. */
  132. if (fread(p, bytes, 1, fp) != 1) {
  133. if (_verbose) {
  134. printf("TGA: EOF while reading %d/%d element raw packet\n",
  135. bytes, (int)datasize);
  136. }
  137. return j / datasize;
  138. }
  139. }
  140. if (_verbose > 1) {
  141. totbytes += bytes;
  142. if (_verbose > 2) {
  143. printf("TGA: %s packet %d/%d\n",
  144. (count & RLE_PACKETSIZE) ? "RLE" : "raw",
  145. bytes, totbytes);
  146. }
  147. }
  148. /* We may need to copy bytes from the state buffer. */
  149. if (p == rleInfo->statebuf) {
  150. rleInfo->statelen = bytes;
  151. } else {
  152. j += bytes;
  153. }
  154. }
  155. if (_verbose > 1) {
  156. printf("TGA: rle_fread %d/%d (total %d)\n",
  157. (int) ( nelems * datasize), totbytes - curbytes, totbytes);
  158. }
  159. return nelems;
  160. }
  161. IGL_INLINE igl::opengl::gliGenericImage *
  162. igl::opengl::gliReadTGA(FILE *fp, char *name, int /*hflip*/, int vflip)
  163. {
  164. igl::opengl::TgaHeader tgaHeader;
  165. igl::opengl::TgaFooter tgaFooter;
  166. char horzrev, vertrev;
  167. int width, height, bpp;
  168. int start, end, dir;
  169. int i, j, k;
  170. int pelbytes, wbytes;
  171. GLenum format;
  172. int components;
  173. RLEstate rleRec;
  174. RLEstate *rleInfo;
  175. int rle;
  176. int index, colors, length;
  177. GLubyte *cmap, *pixels, *data;
  178. int (*myfread)(RLEstate *rleInfo, unsigned char*, size_t, size_t, FILE*);
  179. igl::opengl::gliGenericImage *genericImage;
  180. /* Check the footer. */
  181. if (fseek(fp, 0L - sizeof(tgaFooter), SEEK_END)
  182. || fread(&tgaFooter, sizeof(tgaFooter), 1, fp) != 1) {
  183. sprintf(error, "TGA: Cannot read footer from \"%s\"", name);
  184. if (_verbose) printf("%s\n", error);
  185. return NULL;
  186. }
  187. /* Check the signature. */
  188. if (memcmp(tgaFooter.signature, TGA_SIGNATURE,
  189. sizeof(tgaFooter.signature)) == 0) {
  190. if (_verbose) printf("TGA: found New TGA\n");
  191. } else {
  192. if (_verbose) printf("TGA: found Original TGA\n");
  193. }
  194. if (fseek(fp, 0, SEEK_SET) ||
  195. fread(&tgaHeader, sizeof(tgaHeader), 1, fp) != 1) {
  196. sprintf(error, "TGA: Cannot read header from \"%s\"", name);
  197. if (_verbose) printf("%s\n", error);
  198. return NULL;
  199. }
  200. if (_verbose && tgaHeader.idLength) {
  201. char *idString = (char*) malloc(tgaHeader.idLength);
  202. if (fread(idString, tgaHeader.idLength, 1, fp) != 1) {
  203. sprintf(error, "TGA: Cannot read ID field in \"%s\"", name);
  204. printf("%s\n", error);
  205. } else {
  206. printf("TGA: ID field: \"%*s\"\n", tgaHeader.idLength, idString);
  207. }
  208. free(idString);
  209. } else {
  210. /* Skip the image ID field. */
  211. if (tgaHeader.idLength && fseek(fp, tgaHeader.idLength, SEEK_CUR)) {
  212. sprintf(error, "TGA: Cannot skip ID field in \"%s\"", name);
  213. if (_verbose) printf("%s\n", error);
  214. return NULL;
  215. }
  216. }
  217. /* Reassemble the multi-byte values correctly, regardless of
  218. host endianness. */
  219. width = (tgaHeader.widthHi << 8) | tgaHeader.widthLo;
  220. height = (tgaHeader.heightHi << 8) | tgaHeader.heightLo;
  221. bpp = tgaHeader.bpp;
  222. if (_verbose) {
  223. printf("TGA: width=%d, height=%d, bpp=%d\n", width, height, bpp);
  224. }
  225. horzrev = tgaHeader.descriptor & TGA_DESC_HORIZONTAL;
  226. vertrev = tgaHeader.descriptor & TGA_DESC_VERTICAL;
  227. //vertrev=0;
  228. // // JASON - we can force this stuff if we want
  229. // if( hflip )
  230. // horzrev = 1;
  231. if( vflip )
  232. vertrev = 1;
  233. if (_verbose && horzrev) printf("TGA: horizontal reversed\n");
  234. if (_verbose && vertrev) printf("TGA: vertical reversed\n");
  235. rle = 0;
  236. switch (tgaHeader.imageType) {
  237. case TGA_TYPE_MAPPED_RLE:
  238. rle = 1;
  239. if (_verbose) printf("TGA: run-length encoded\n");
  240. case TGA_TYPE_MAPPED:
  241. /* Test for alpha channel. */
  242. format = GL_COLOR_INDEX;
  243. components = 1;
  244. if (_verbose) {
  245. printf("TGA: %d bit indexed image (%d bit palette)\n",
  246. tgaHeader.colorMapSize, bpp);
  247. }
  248. break;
  249. case TGA_TYPE_GRAY_RLE:
  250. rle = 1;
  251. if (_verbose) printf("TGA: run-length encoded\n");
  252. case TGA_TYPE_GRAY:
  253. format = GL_LUMINANCE;
  254. components = 1;
  255. if (_verbose) printf("TGA: %d bit grayscale image\n", bpp);
  256. break;
  257. case TGA_TYPE_COLOR_RLE:
  258. rle = 1;
  259. if (_verbose) printf("TGA: run-length encoded\n");
  260. case TGA_TYPE_COLOR:
  261. /* Test for alpha channel. */
  262. if (bpp == 32) {
  263. format = GL_BGRA_EXT;
  264. components = 4;
  265. if (_verbose) {
  266. printf("TGA: %d bit color image with alpha channel\n", bpp);
  267. }
  268. } else {
  269. format = GL_BGR_EXT;
  270. components = 3;
  271. if (_verbose) printf("TGA: %d bit color image\n", bpp);
  272. }
  273. break;
  274. default:
  275. sprintf(error,
  276. "TGA: unrecognized image type %d\n", tgaHeader.imageType);
  277. if (_verbose) printf("%s\n", error);
  278. return NULL;
  279. }
  280. if ((format == GL_BGRA_EXT && bpp != 32) ||
  281. (format == GL_BGR_EXT && bpp != 24) ||
  282. ((format == GL_LUMINANCE || format == GL_COLOR_INDEX) && bpp != 8)) {
  283. /* FIXME: We haven't implemented bit-packed fields yet. */
  284. fprintf(stderr, "bpp %d, format %x\n", bpp, (unsigned int)format);
  285. sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
  286. if (_verbose) printf("%s\n", error);
  287. return NULL;
  288. }
  289. /* Check that we have a color map only when we need it. */
  290. if (format == GL_COLOR_INDEX) {
  291. if (tgaHeader.colorMapType != 1) {
  292. sprintf(error, "TGA: indexed image has invalid color map type %d\n",
  293. tgaHeader.colorMapType);
  294. if (_verbose) printf("%s\n", error);
  295. return NULL;
  296. }
  297. } else if (tgaHeader.colorMapType != 0) {
  298. sprintf(error, "TGA: non-indexed image has invalid color map type %d\n",
  299. tgaHeader.colorMapType);
  300. if (_verbose) printf("%s\n", error);
  301. return NULL;
  302. }
  303. if (tgaHeader.colorMapType == 1) {
  304. /* We need to read in the colormap. */
  305. index = (tgaHeader.colorMapIndexHi << 8) | tgaHeader.colorMapIndexLo;
  306. length = (tgaHeader.colorMapLengthHi << 8) | tgaHeader.colorMapLengthLo;
  307. if (_verbose) {
  308. printf("TGA: reading color map (%d + %d) * (%d / 8)\n",
  309. index, length, tgaHeader.colorMapSize);
  310. }
  311. if (length == 0) {
  312. sprintf(error, "TGA: invalid color map length %d", length);
  313. if (_verbose) printf("%s\n", error);
  314. return NULL;
  315. }
  316. if (tgaHeader.colorMapSize != 24) {
  317. /* We haven't implemented bit-packed fields yet. */
  318. sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
  319. if (_verbose) printf("%s\n", error);
  320. return NULL;
  321. }
  322. pelbytes = tgaHeader.colorMapSize / 8;
  323. colors = length + index;
  324. cmap = (GLubyte*)malloc (colors * pelbytes);
  325. /* Zero the entries up to the beginning of the map. */
  326. memset(cmap, 0, index * pelbytes);
  327. /* Read in the rest of the colormap. */
  328. if (fread(cmap, pelbytes, length, fp) != (size_t) length) {
  329. sprintf(error, "TGA: error reading colormap (ftell == %ld)\n",
  330. ftell (fp));
  331. if (_verbose) printf("%s\n", error);
  332. return NULL;
  333. }
  334. if (pelbytes >= 3) {
  335. /* Rearrange the colors from BGR to RGB. */
  336. int tmp;
  337. for (j = index; j < length * pelbytes; j += pelbytes) {
  338. tmp = cmap[j];
  339. cmap[j] = cmap[j + 2];
  340. cmap[j + 2] = tmp;
  341. }
  342. }
  343. } else {
  344. colors = 0;
  345. cmap = NULL;
  346. }
  347. /* Allocate the data. */
  348. pelbytes = bpp / 8;
  349. pixels = (unsigned char *) malloc (width * height * pelbytes);
  350. if (rle) {
  351. rleRec.statebuf = 0;
  352. rleRec.statelen = 0;
  353. rleRec.laststate = 0;
  354. rleInfo = &rleRec;
  355. myfread = rle_fread;
  356. } else {
  357. rleInfo = NULL;
  358. myfread = std_fread;
  359. }
  360. wbytes = width * pelbytes;
  361. if (vertrev) {
  362. start = 0;
  363. end = height;
  364. dir = 1;
  365. } else {
  366. /* We need to reverse loading order of rows. */
  367. start = height-1;
  368. end = -1;
  369. dir = -1;
  370. }
  371. for (i = start; i != end; i += dir) {
  372. data = pixels + i*wbytes;
  373. /* Suck in the data one row at a time. */
  374. if (myfread(rleInfo, data, pelbytes, width, fp) != width) {
  375. /* Probably premature end of file. */
  376. if (_verbose) {
  377. printf ("TGA: error reading (ftell == %ld, width=%d)\n",
  378. ftell(fp), width);
  379. }
  380. return NULL;
  381. }
  382. if (horzrev) {
  383. /* We need to mirror row horizontally. */
  384. for (j = 0; j < width/2; j++) {
  385. GLubyte tmp;
  386. for (k = 0; k < pelbytes; k++) {
  387. tmp = data[j*pelbytes+k];
  388. data[j*pelbytes+k] = data[(width-j-1)*pelbytes+k];
  389. data[(width-j-1)*pelbytes+k] = tmp;
  390. }
  391. }
  392. }
  393. }
  394. if (rle) {
  395. free(rleInfo->statebuf);
  396. }
  397. if (fgetc (fp) != EOF) {
  398. if (_verbose) printf ("TGA: too much input data, ignoring extra...\n");
  399. }
  400. genericImage = (igl::opengl::gliGenericImage*) malloc(sizeof(igl::opengl::gliGenericImage));
  401. genericImage->width = width;
  402. genericImage->height = height;
  403. genericImage->format = format;
  404. genericImage->components = components;
  405. genericImage->cmapEntries = colors;
  406. genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me
  407. genericImage->cmap = cmap;
  408. genericImage->pixels = pixels;
  409. return genericImage;
  410. }
  411. IGL_INLINE int igl::opengl::gli_verbose(int new_verbose)
  412. {
  413. _verbose = new_verbose;
  414. return _verbose;
  415. }
  416. // added 10/2005, Denis Zorin
  417. // a very simple TGA output, supporting
  418. // uncompressed luminance RGB and RGBA
  419. // G22.2270 students: this is C (no C++)
  420. // so this is not the style I would encourage
  421. // you to use; I used it for consistency
  422. // with the rest of the code in this file
  423. // fixed header values for the subset of TGA we use for writing
  424. unsigned char TGAHeaderColor[12] =
  425. { 0,// 0 ID length = no id
  426. 0,// 1 color map type = no color map
  427. 2,// 2 image type = uncompressed true color
  428. 0, 0, 0, 0, 0,// color map spec = empty
  429. 0, 0, // x origin of image
  430. 0, 0 // y origin of image
  431. };
  432. unsigned char TGAHeaderBW[12] =
  433. { 0,// 0 ID length = no id
  434. 0,// 1 color map type = no color map
  435. 3,// 3 image type = uncompressed black and white
  436. 0, 0, 0, 0, 0,// color map spec = empty
  437. 0, 0, // x origin of image
  438. 0, 0 // y origin of image
  439. };
  440. // this makes sure that
  441. // image size is written in correct format
  442. // and byte order (least first)
  443. IGL_INLINE void write16bit(int n, FILE* fp) {
  444. unsigned char bytes[] = { static_cast<unsigned char>(n % 256), static_cast<unsigned char>(n / 256) };
  445. fwrite(bytes, 2, sizeof(unsigned char),fp);
  446. }
  447. IGL_INLINE void igl::opengl::writeTGA( igl::opengl::gliGenericImage* image, FILE *fp) {
  448. assert(!image->cmap); // we do not deal with color map images
  449. if(image->components == 3 || image->components == 4)
  450. fwrite(TGAHeaderColor, 12, sizeof(unsigned char),fp);
  451. else {
  452. if(image->components == 1 )
  453. fwrite(TGAHeaderBW, 12, sizeof(unsigned char),fp);
  454. else { fprintf(stderr,"Supported component number: 1,3 or 4\n"); exit(1); }
  455. }
  456. write16bit(image->width,fp);
  457. write16bit(image->height,fp);
  458. switch (image->components ) {
  459. case 1:
  460. putc(8,fp);
  461. break;
  462. case 3:
  463. putc(24,fp);
  464. break;
  465. case 4:
  466. putc(32,fp);
  467. break;
  468. default: fprintf(stderr,"Supported component number: 1,3 or 4\n"); exit(1);
  469. };
  470. if(image-> components == 4)
  471. putc(0x04,fp); // bottom left image (0x00) + 8 bit alpha (0x4)
  472. else
  473. putc(0x00,fp);
  474. fwrite(image->pixels, image->height*image->width*image->components, sizeof(char),fp);
  475. }