1 #include <cstring>
2 #include <cstdlib>
3 #include <cstdio>
4 
5 #include "Common/Data/Format/PNGLoad.h"
6 #include "Common/Data/Format/ZIMLoad.h"
7 #include "Common/Data/Format/ZIMSave.h"
8 
9 #include "Common/Common.h"
10 
11 char magic[5] = "ZIMG";
12 
13 const char *format_strings[4] = { "8888", "4444", "565", "ETC1" };
14 int formats[3] = { ZIM_RGBA8888, ZIM_RGBA4444, ZIM_RGB565 };
15 
printusage()16 void printusage() {
17 	fprintf(stderr, "Usage: zimtool infile.png outfile.zim [-f=FORMAT] [-m] [-g] [-z[LEVEL]]\n");
18 	fprintf(stderr, "Formats: 8888 4444 565 ETC1\n");
19 }
20 
filesize(const char * filename)21 int filesize(const char *filename) {
22 	FILE *f = fopen(filename, "rb");
23 	fseek(f, 0, SEEK_END);
24 	int sz = ftell(f);
25 	fclose(f);
26 	return sz;
27 }
28 
main(int argc,char ** argv)29 int main(int argc, char **argv) {
30 	// Parse command line arguments.
31 	const char *FLAGS_infile;
32 	const char *FLAGS_outfile;
33 	if (argc >= 3) {
34 		FLAGS_infile = argv[1];
35 		FLAGS_outfile = argv[2];
36 	} else {
37 		fprintf(stderr, "ERROR: Not enough parameters.\n");
38 		printusage();
39 		return 1;
40 	}
41 
42 	int flags = 0;
43 	int level = 0;
44 	bool format_set = false;
45 	for (int i = 3; i < argc; i++) {
46 		if (argv[i][0] != '-') {
47 			fprintf(stderr, "Additional arguments must start with '-'\n");
48 			return 1;
49 		}
50 		switch (argv[i][1]) {
51 		case 'm':
52 			flags |= ZIM_HAS_MIPS;
53 			// Generates mips directly here. We can generate gamma
54 			// corrected mips, and mips for ETC1.
55 			break;
56 		case 'g':
57 			flags |= ZIM_GEN_MIPS;
58 			break;
59 		case 'c':
60 			flags |= ZIM_CLAMP;
61 			break;
62 		case 'f':
63 		{
64 			for (int j = 0; j < 4; j++) {
65 				if (!strcmp(format_strings[j], argv[i] + 3)) {
66 					flags |= j;
67 					format_set = true;
68 				}
69 			}
70 		}
71 		break;
72 		case 'z':
73 			flags |= ZIM_ZSTD_COMPRESSED;
74 			if (argv[i][2] != '\0') {
75 				int pos = 2;
76 				while (argv[i][pos] >= '0' && argv[i][pos] <= '9') {
77 					level = level * 10 + argv[i][pos] - '0';
78 					pos++;
79 				}
80 			}
81 			break;
82 		}
83 	}
84 	// TODO: make setting?
85 	flags |= ZIM_ETC1_MEDIUM;
86 	if (!format_set) {
87 		fprintf(stderr, "Must set format\n");
88 		printusage();
89 		return 1;
90 	}
91 
92 	uint8_t *image_data;
93 	int width, height;
94 	if (1 != pngLoad(FLAGS_infile, &width, &height, &image_data)) {
95 		fprintf(stderr, "Input not a PNG file\n");
96 		printusage();
97 		return 1;
98 	}
99 
100 	FILE *f = fopen(FLAGS_outfile, "wb");
101 	SaveZIM(f, width, height, width * 4, flags, image_data, level);
102 	fclose(f);
103 	int in_file_size = filesize(FLAGS_infile);
104 	int out_file_size = filesize(FLAGS_outfile);
105 	fprintf(stdout, "Converted %s to %s. %i b to %i b. %ix%i, %s.\n", FLAGS_infile, FLAGS_outfile, in_file_size, out_file_size, width, height, format_strings[flags & ZIM_FORMAT_MASK]);
106 	return 0;
107 }
108