]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
lbximg: Make libpng a soft dependency.
[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 other formats.
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 <stdbool.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <assert.h>
26 #include <getopt.h>
27 #include <errno.h>
28
29 #include "tools.h"
30 #include "image.h"
31 #include "error.h"
32 #include "lbx.h"
33
34 #include "imgoutput.h"
35
36 /* Global flags */
37 static int verbose = 0;
38 static char *outname = "out";
39 static int usepalette = 1;
40
41 static void printusage(void)
42 {
43         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
44                           " [-f path]");
45         puts("              [-F format] [frameno ...]");
46 }
47
48 static void printhelp(void)
49 {
50         printusage();
51         puts("For now, see the man page for detailed help.");
52 }
53
54 enum {
55         MODE_NONE,
56         MODE_DECODE,
57         MODE_IDENT,
58 };
59
60 static const struct img_format {
61         img_output_func *output;
62         char name[4];
63         bool enabled;
64 } formats[] = {
65 #if HAVE_LIBPNG
66         { img_output_png, "png", 1 },
67 #endif
68         { img_output_pam, "pam", 1 },
69         { img_output_ppm, "ppm", 1 },
70         { img_output_pbm, "pbm", 1 },
71 };
72
73 static int lookup_format(const char *fmt)
74 {
75         for (size_t i = 0; i < sizeof formats / sizeof formats[0]; i++) {
76                 assert(!formats[i].name[sizeof formats[i].name - 1]);
77
78                 if (!fmt && formats[i].enabled)
79                         return i;
80
81                 if (strcmp(formats[i].name, fmt))
82                         continue;
83
84                 if (!formats[i].enabled) {
85                         tool_err(-1, "%s support disabled at build time", fmt);
86                         return -1;
87                 }
88
89                 return i;
90         }
91
92         tool_err(-1, "unknown format %s", fmt);
93         return -1;
94 }
95
96 bool img_is_masked(unsigned char **mask, unsigned width, unsigned height)
97 {
98         unsigned x, y;
99
100         for (x = y = 0; y < height; ++x < width || (x = 0, y++)) {
101                 if (mask[y][x] == 0)
102                         return true;
103         }
104
105         return false;
106 }
107
108 int parserange(unsigned frames, char *str, unsigned char *bits)
109 {
110         unsigned long start, end;
111         unsigned int i;
112         char *endptr;
113
114         start = strtoul(str, &endptr, 0);
115         if (start >= frames) {
116                 tool_err(-1, "frame %lu out of range.", start);
117                 return -1;
118         }
119
120         if (endptr == str) {
121                 tool_err(-1, "invalid frame range: %s.", str);
122                 return -1;
123         }
124
125         switch (*endptr) {
126         case '\0':
127                 end = start;
128                 break;
129         case '-':
130                 end = strtoul(endptr+1, &endptr, 0);
131                 if (end >= frames) {
132                         tool_err(-1, "frame %lu out of range.", end);
133                         return -1;
134                 }
135
136                 if (endptr == str)
137                         end = frames - 1;
138                 break;
139         default:
140                 tool_err(-1, "invalid frame range: %s.", str);
141                 return -1;
142         }
143
144         if (end < start) {
145                 tool_err(-1, "invalid frame range: %s.", str);
146                 return -1;
147         }
148
149         for (i = start; i <= end; i++) {
150                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
151         }
152
153         return 0;
154 }
155
156 int output(unsigned int frameno, const struct img_format *fmt,
157            unsigned char **framedata, unsigned char **mask,
158            unsigned int width, unsigned int height,
159            struct lbx_colour palette[static 256])
160 {
161         char name[strlen(outname) + sizeof ".65535.png"];
162         FILE *of;
163         int rc;
164
165         assert(fmt->output != NULL);
166         assert(frameno < 65536);
167         snprintf(name, sizeof name, "%s.%03d.%s", outname, frameno, fmt->name);
168
169         of = fopen(name, "wb");
170         if (!of) {
171                 tool_err(0, "failed to open %s", name);
172                 return -1;
173         }
174
175         rc = fmt->output(of, name, width, height, framedata, mask, palette);
176         if (rc < 0) {
177                 fclose(of);
178                 return -1;
179         }
180
181         if (fclose(of) == EOF) {
182                 tool_err(0, "error writing %s", name);
183                 return -1;
184         }
185                 
186         if (verbose)
187                 printf("wrote %s\n", name);
188
189         return 0;
190 }
191
192 static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
193 {
194         struct lbx_image *overimg = lbx_img_open(f, &lbx_default_fops, NULL);
195         struct lbx_imginfo info;
196
197         if (!overimg) {
198                 tool_err(-1, "failed to open override image: %s", lbx_errmsg());
199                 return -1;
200         }
201         lbx_img_getinfo(overimg, &info);
202
203         if (!info.palettesz) {
204                 tool_err(-1, "override image has no palette.");
205                 lbx_img_close(overimg);
206                 return -1;
207         }
208
209         if (lbx_img_getpalette(overimg, palette) == -1) {
210                 tool_err(-1, "error reading override palette: %s", lbx_errmsg());
211                 lbx_img_close(overimg);
212                 return -1;
213         }
214
215         lbx_img_close(overimg);
216         return 0;
217 }
218
219 static int loadpalette(struct lbx_image *img, struct lbx_imginfo *info,
220                        FILE *palf, FILE *override,
221                        struct lbx_colour palette[static 256])
222 {
223         int i;
224
225         /* For sanity. */
226         if (!palf && !info->palettesz && !override) {
227                 tool_err(-1, "no palette available.");
228                 return -1;
229         }
230
231         /* Default the palette to a wonderful pink. */
232         for (i = 0; i < 256; i++) {
233                 palette[i] = (struct lbx_colour){0x3f, 0x00, 0x3f};
234         }
235
236         /* Read the external palette, if any. */
237         if (palf && lbx_img_loadpalette(palf, &lbx_default_fops, palette) != 0) {
238                 tool_err(-1, "error reading external palette: %s", lbx_errmsg());
239                 return -1;
240         }
241
242         /* Read the embedded palette, if any. */
243         if (info->palettesz && lbx_img_getpalette(img, palette) == -1) {
244                 tool_err(-1, "error reading embedded palette: %s", lbx_errmsg());
245                 return -1;
246         }
247
248         /* Read the override palette, if any. */
249         if (override && loadoverride(override, palette) == -1) {
250                 return -1;
251         }
252
253         return 0;
254 }
255
256 static int
257 decode(struct lbx_image *img, FILE *palf, FILE *override, int fmt, char **argv)
258 {
259         unsigned char *framebits;
260         struct lbx_colour palette[256];
261         struct lbx_imginfo info;
262         int extracted = 0;
263         unsigned int i;
264
265         assert(fmt >= 0 && fmt < sizeof formats / sizeof formats[0]);
266
267         lbx_img_getinfo(img, &info);
268
269         framebits = calloc(1, img->frames / CHAR_BIT + 1);
270         if (!framebits) {
271                 return EXIT_FAILURE;
272         }
273
274         /* Figure out what images we're extracting. */
275         if (!argv[0]) {
276                 /* extract all images by default. */
277                 memset(framebits, -1, img->frames / CHAR_BIT + 1);
278         } else {
279                 for (i = 0; argv[i]; i++) {
280                         parserange(img->frames, argv[i], framebits);
281                 }
282         }
283
284         if (usepalette) {
285                 if (loadpalette(img, &info, palf, override, palette) == -1) {
286                         goto err;
287                 }
288         }
289
290         /* Extract the images, in order. */
291         for (i = 0; i < img->frames; i++) {
292                 unsigned char **data;
293                 unsigned char **mask;
294
295                 if (!(framebits[i / CHAR_BIT] & (1 << (i % CHAR_BIT))))
296                         continue;
297
298                 data = lbx_img_getframe(img, i);
299                 if (!data) {
300                         tool_err(-1, "error in frame %u: %s", i, lbx_errmsg());
301                         continue;
302                 }
303
304                 mask = lbx_img_getmask(img);
305
306                 if (!output(i, &formats[fmt], data, mask,
307                             img->width, img->height,
308                             usepalette ? palette : NULL)) {
309                         extracted = 1;
310                 }
311         }
312
313         if (!extracted) {
314                 tool_err(-1, "no frames extracted.");
315                 goto err;
316         }
317
318         free(framebits);
319         return EXIT_SUCCESS;
320 err:
321         free(framebits);
322         return EXIT_FAILURE;
323 }
324
325 int main(int argc, char **argv)
326 {
327         int mode = MODE_NONE, fmt, opt, rc = EXIT_FAILURE;
328         struct lbx_pipe_state stdin_handle = { .f = stdin };
329         const char *file = NULL, *fmtstring = NULL;
330         FILE *palf = NULL, *overf = NULL;
331         struct lbx_image *img;
332
333         static const char sopts[] = "idnvF:f:p:O:VH";
334         static const struct option lopts[] = {
335                 { "ident",      0, NULL, 'i' },
336                 { "decode",     0, NULL, 'd' },
337                 { "verbose",    0, NULL, 'v' },
338                 { "file",       1, NULL, 'f' },
339                 { "format",     1, NULL, 'F' },
340                 { "palette",    1, NULL, 'p' },
341                 { "override",   1, NULL, 'p' },
342
343                 { "version",    0, NULL, 'V' },
344                 { "usage",      0, NULL, 'U' },
345                 { "help",       0, NULL, 'H' },
346
347                 { "no-palette", 0, NULL, 'n' },
348
349                 { 0 }
350         };
351
352         tool_init("lbximg", argc, argv);
353         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
354                 switch(opt) {
355                 case 'i':
356                         mode = MODE_IDENT;
357                         break;
358                 case 'd':
359                         mode = MODE_DECODE;
360                         break;
361                 case 'v':
362                         verbose = 1;
363                         break;
364                 case 'F':
365                         fmtstring = optarg;
366                         break;
367                 case 'f':
368                         file = optarg;
369                         break;
370                 case 'n':
371                         usepalette = 0;
372                         break;
373                 case 'p':
374                         palf = fopen(optarg, "rb");
375                         if (!palf) {
376                                 tool_err(0, "failed to open %s", optarg);
377                                 return EXIT_FAILURE;
378                         }
379
380                         break;
381                 case 'O':
382                         overf = fopen(optarg, "rb");
383                         if (!overf) {
384                                 tool_err(0, "failed to open %s", optarg);
385                                 return EXIT_FAILURE;
386                         }
387                         break;
388                 case 'V':
389                         tool_version();
390                         return EXIT_SUCCESS;
391                 case 'U':
392                         printusage();
393                         return EXIT_SUCCESS;
394                 case 'H':
395                         printhelp();
396                         return EXIT_SUCCESS;
397                 default:
398                         return EXIT_FAILURE;
399                 }
400         }
401
402         if (mode == MODE_NONE) {
403                 tool_err(-1, "you must specify a mode.");
404                 return EXIT_FAILURE;
405         }
406
407         fmt = lookup_format(fmtstring);
408         if (fmt < 0)
409                 return EXIT_FAILURE;
410
411         if (file)
412                 img = lbx_img_fopen(file);
413         else
414                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
415
416         if (!img) {
417                 tool_err(-1, "failed to open image: %s.", lbx_errmsg());
418                 return EXIT_FAILURE;
419         }
420
421         if (verbose || mode == MODE_IDENT) {
422                 struct lbx_imginfo info;
423
424                 if (!file)
425                         file = "stdin";
426
427                 lbx_img_getinfo(img, &info);
428                 printf("%s is %hux%hu LBX image, %hhu frame(s)%s%s%s\n",
429                        file, img->width, img->height, img->frames,
430                        info.palettesz ? ", embedded palette" : "",
431                        img->chunk     ? ", chunked" : "",
432                        info.looping   ? ", loops" : "");
433         }
434
435         switch (mode) {
436         case MODE_DECODE:
437                 rc = decode(img, palf, overf, fmt, &argv[optind]);
438                 break;
439         }
440
441         lbx_img_close(img);
442         return rc;
443 }