]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
tools: Move progname handling into a common source file.
[liblbx.git] / src / lbximg.c
1 /*
2  *  2ooM: The Master of Orion II Reverse Engineering Project
3  *  Simple command-line tool to convert an LBX image to a set of PNGs.
4  *  Copyright © 2006-2011, 2013 Nick Bowler
5  *
6  *  This program 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  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 #include <config.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <assert.h>
25 #include <getopt.h>
26 #include <errno.h>
27
28 #include <png.h>
29
30 #include "tools.h"
31 #include "image.h"
32 #include "error.h"
33 #include "lbx.h"
34
35 /* Global flags */
36 static int verbose = 0;
37 static char *outname = "out";
38 static int usepalette = 1;
39
40 static void printusage(void)
41 {
42         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
43                           " [-f path]");
44         puts("              [frameno ...]");
45 }
46
47 static void printhelp(void)
48 {
49         printusage();
50         puts("For now, see the man page for detailed help.");
51 }
52
53 enum {
54         MODE_NONE,
55         MODE_DECODE,
56         MODE_IDENT,
57 };
58
59 int parserange(unsigned frames, char *str, unsigned char *bits)
60 {
61         unsigned long start, end;
62         unsigned int i;
63         char *endptr;
64
65         start = strtoul(str, &endptr, 0);
66         if (start >= frames) {
67                 errmsg("frame %lu out of range.\n", start);
68                 return -1;
69         }
70
71         if (endptr == str) {
72                 errmsg("invalid frame range: %s.\n", str);
73                 return -1;
74         }
75
76         switch (*endptr) {
77         case '\0':
78                 end = start;
79                 break;
80         case '-':
81                 end = strtoul(endptr+1, &endptr, 0);
82                 if (end >= frames) {
83                         errmsg("frame %lu out of range.\n", end);
84                         return -1;
85                 }
86
87                 if (endptr == str)
88                         end = frames - 1;
89                 break;
90         default:
91                 errmsg("invalid frame range: %s.\n", str);
92                 return -1;
93         }
94
95         if (end < start) {
96                 errmsg("invalid frame range: %s.\n", str);
97                 return -1;
98         }
99
100         for (i = start; i <= end; i++) {
101                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
102         }
103
104         return 0;
105 }
106
107 static int ismasked(unsigned char **mask, unsigned width, unsigned height)
108 {
109         unsigned y, x;
110         for (y = 0; y < height; y++) {
111                 for (x = 0; x < width; x++) {
112                         if (mask[y][x] == 0) return 1;
113                 }
114         }
115
116         return 0;
117 }
118
119 int outpng(unsigned int frameno,
120            unsigned char **framedata, unsigned char **mask,
121            unsigned int width, unsigned int height,
122            struct lbx_colour palette[static 256])
123 {
124         char name[strlen(outname) + sizeof ".65535.png"];
125         unsigned char *row;
126         unsigned int x, y;
127         FILE *of;
128
129         png_structp png;
130         png_infop   info;
131
132         assert(frameno < 65536);
133         snprintf(name, sizeof name, "%s.%03d.png", outname, frameno);
134
135         row = malloc(4 * width);
136         if (!row) {
137                 errmsg("failed to allocate row buffer: %s\n", strerror(errno));
138                 return -1;
139         }
140
141         of = fopen(name, "wb");
142         if (!of) {
143                 errmsg("failed to open %s: %s.\n", name, strerror(errno));
144                 free(row);
145                 return -1;
146         }
147
148         png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
149         if (!png) {
150                 errmsg("failed to init libpng.\n", 0);
151                 goto err;
152         }
153
154         info = png_create_info_struct(png);
155         if (!info) {
156                 errmsg("failed to init libpng.\n", 0);
157                 png_destroy_write_struct(&png, NULL);
158                 goto err;
159         }
160
161         if (setjmp(png_jmpbuf(png))) {
162                 png_destroy_write_struct(&png, &info);
163                 goto err;
164         }
165
166         png_init_io(png, of);
167
168         if (!ismasked(mask, width, height)) {
169                 /*
170                  * This case is easy; we can just feed the palette and pixel
171                  * data to libpng and let it do its magic.
172                  */
173
174                 png_color png_palette[256];
175                 for (unsigned i = 0; i < 256; i++) {
176                         png_palette[i].red   = palette[i].red;
177                         png_palette[i].green = palette[i].green;
178                         png_palette[i].blue  = palette[i].blue;
179                 }
180
181                 png_set_IHDR(png, info, width, height, 8,
182                              PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
183                              PNG_COMPRESSION_TYPE_DEFAULT,
184                              PNG_FILTER_TYPE_DEFAULT);
185                 
186                 png_set_PLTE(png, info, png_palette, 256);
187                 png_set_rows(png, info, framedata);
188                 png_write_png(png, info, PNG_TRANSFORM_IDENTITY, NULL);
189         } else {
190                 /*
191                  * Unfortunately, LBX doesn't translate nicely to PNG here.
192                  * LBX has a 256 colour palette _plus_ transparency.
193                  * We'll form an RGBA PNG to deal with this.
194                  */
195
196                 png_set_IHDR(png, info, width, height, 8,
197                              PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
198                              PNG_COMPRESSION_TYPE_DEFAULT,
199                              PNG_FILTER_TYPE_DEFAULT);
200         
201                 png_write_info(png, info);
202         
203                 for (y = 0; y < height; y++) {
204                         for (x = 0; x < width; x++) {
205                                 row[4*x+0] = palette[framedata[y][x]].red;
206                                 row[4*x+1] = palette[framedata[y][x]].green;
207                                 row[4*x+2] = palette[framedata[y][x]].blue;
208                                 row[4*x+3] = (mask[y][x]) ? -1 : 0;
209                         }
210         
211                         png_write_row(png, row);
212                 }
213         
214                 png_write_end(png, NULL);
215         }
216
217         png_destroy_write_struct(&png, &info);
218         fclose(of);
219         free(row);
220
221         if (verbose)
222                 printf("wrote %s\n", name);
223         return 0;
224 err:
225         fclose(of);
226         remove(name);
227         free(row);
228         return -1;
229 }
230
231 static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
232 {
233         struct lbx_image *overimg = lbx_img_open(f, &lbx_default_fops, NULL);
234         struct lbx_imginfo info;
235
236         if (!overimg) {
237                 errmsg("failed to open override image: %s\n", lbx_errmsg());
238                 return -1;
239         }
240         lbx_img_getinfo(overimg, &info);
241
242         if (!info.palettesz) {
243                 errmsg("override image has no palette.\n", 0);
244                 lbx_img_close(overimg);
245                 return -1;
246         }
247
248         if (lbx_img_getpalette(overimg, palette) == -1) {
249                 errmsg("error reading override palette: %s\n", lbx_errmsg());
250                 lbx_img_close(overimg);
251                 return -1;
252         }
253
254         lbx_img_close(overimg);
255         return 0;
256 }
257
258 static int loadpalette(struct lbx_image *img, struct lbx_imginfo *info,
259                        FILE *palf, FILE *override,
260                        struct lbx_colour palette[static 256])
261 {
262         int i;
263
264         /* In no-palette mode, use palette indices for colour. */
265         if (!usepalette) {
266                 for (i = 0; i < 256; i++) {
267                         palette[i] = (struct lbx_colour){i,i,i};
268                 }
269
270                 return 0;
271         }
272
273         /* For sanity. */
274         if (!palf && !info->palettesz && !override) {
275                 errmsg("no palette available.\n", 0);
276                 return -1;
277         }
278
279         /* Default the palette to a wonderful pink. */
280         for (i = 0; i < 256; i++) {
281                 palette[i] = (struct lbx_colour){0xff, 0x00, 0xff};
282         }
283
284         /* Read the external palette, if any. */
285         if (palf && lbx_img_loadpalette(palf, &lbx_default_fops, palette) != 0) {
286                 errmsg("error reading external palette: %s\n", lbx_errmsg());
287                 return -1;
288         }
289
290         /* Read the embedded palette, if any. */
291         if (info->palettesz && lbx_img_getpalette(img, palette) == -1) {
292                 errmsg("error reading embedded palette: %s\n", lbx_errmsg());
293                 return -1;
294         }
295
296         /* Read the override palette, if any. */
297         if (override && loadoverride(override, palette) == -1) {
298                 return -1;
299         }
300
301         return 0;
302 }
303
304 int decode(struct lbx_image *img, FILE *palf, FILE *override, char **argv)
305 {
306         unsigned char *framebits;
307         struct lbx_colour palette[256];
308         struct lbx_imginfo info;
309         int extracted = 0;
310         unsigned int i;
311
312         lbx_img_getinfo(img, &info);
313
314         framebits = calloc(1, img->frames / CHAR_BIT + 1);
315         if (!framebits) {
316                 return EXIT_FAILURE;
317         }
318
319         /* Figure out what images we're extracting. */
320         if (!argv[0]) {
321                 /* extract all images by default. */
322                 memset(framebits, -1, img->frames / CHAR_BIT + 1);
323         } else {
324                 for (i = 0; argv[i]; i++) {
325                         parserange(img->frames, argv[i], framebits);
326                 }
327         }
328
329         if (loadpalette(img, &info, palf, override, palette) == -1) {
330                 goto err;
331         }
332
333         /* Extract the images, in order. */
334         for (i = 0; i < img->frames; i++) {
335                 unsigned char **data;
336                 unsigned char **mask;
337
338                 if (!(framebits[i / CHAR_BIT] & (1 << (i % CHAR_BIT))))
339                         continue;
340
341                 data = lbx_img_getframe(img, i);
342                 if (!data) {
343                         errmsg("error in frame %u: %s\n", i, lbx_errmsg());
344                         continue;
345                 }
346
347                 mask = lbx_img_getmask(img);
348
349                 if (!outpng(i, data, mask, img->width, img->height, palette)) {
350                         extracted = 1;
351                 }
352         }
353
354         if (!extracted) {
355                 errmsg("no frames extracted.\n", 0);
356                 goto err;
357         }
358
359         free(framebits);
360         return EXIT_SUCCESS;
361 err:
362         free(framebits);
363         return EXIT_FAILURE;
364 }
365
366 int main(int argc, char **argv)
367 {
368         int mode = MODE_NONE, opt, rc = EXIT_FAILURE;
369         struct lbx_pipe_state stdin_handle = { .f = stdin };
370         FILE *palf = NULL, *overf = NULL;
371         const char *file = NULL;
372         struct lbx_image *img;
373
374         static const char *sopts = "idnvf:p:O:V";
375         static const struct option lopts[] = {
376                 { "ident",      0, NULL, 'i' },
377                 { "decode",     0, NULL, 'd' },
378                 { "verbose",    0, NULL, 'v' },
379                 { "file",       1, NULL, 'f' },
380                 { "palette",    1, NULL, 'p' },
381                 { "override",   1, NULL, 'p' },
382
383                 { "version",    0, NULL, 'V' },
384                 { "usage",      0, NULL, 'U' },
385                 { "help",       0, NULL, 'H' },
386
387                 { "no-palette", 0, NULL, 'n' },
388
389                 { 0 }
390         };
391
392         tool_init("lbximg", argc, argv);
393         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
394                 switch(opt) {
395                 case 'i':
396                         mode = MODE_IDENT;
397                         break;
398                 case 'd':
399                         mode = MODE_DECODE;
400                         break;
401                 case 'v':
402                         verbose = 1;
403                         break;
404                 case 'f':
405                         file = optarg;
406                         break;
407                 case 'n':
408                         usepalette = 0;
409                         break;
410                 case 'p':
411                         palf = fopen(optarg, "rb");
412                         if (!palf) {
413                                 errmsg("failed to open %s: %m\n", optarg);
414                                 return EXIT_FAILURE;
415                         }
416
417                         break;
418                 case 'O':
419                         overf = fopen(optarg, "rb");
420                         if (!overf) {
421                                 errmsg("failed to open %s: %m\n", optarg);
422                                 return EXIT_FAILURE;
423                         }
424                         break;
425                 case 'V':
426                         tool_version();
427                         return EXIT_SUCCESS;
428                 case 'U':
429                         printusage();
430                         return EXIT_SUCCESS;
431                 case 'H':
432                         printhelp();
433                         return EXIT_SUCCESS;
434                 case '?':
435                 case ':':
436                         return EXIT_FAILURE;
437                 }
438         }
439
440         if (mode == MODE_NONE) {
441                 errmsg("you must specify a mode.\n", 0);
442                 return EXIT_FAILURE;
443         }
444
445         if (file)
446                 img = lbx_img_fopen(file);
447         else
448                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
449
450         if (!img) {
451                 errmsg("failed to open image: %s.\n", lbx_errmsg());
452                 return EXIT_FAILURE;
453         }
454
455         if (verbose || mode == MODE_IDENT) {
456                 struct lbx_imginfo info;
457
458                 if (!file)
459                         file = "stdin";
460
461                 lbx_img_getinfo(img, &info);
462                 printf("%s is %ux%u LBX image, %u frame(s)%s%s\n",
463                        file, img->width, img->height, img->frames,
464                        info.palettesz ? ", embedded palette" : "",
465                        img->chunk     ? ", chunked" : "",
466                        info.looping   ? ", loops" : "");
467         }
468
469         switch (mode) {
470         case MODE_DECODE:
471                 rc = decode(img, palf, overf, &argv[optind]);
472                 break;
473         }
474
475         lbx_img_close(img);
476         return rc;
477 }