summaryrefslogtreecommitdiff
path: root/testbc1.c
blob: 8475bb2a344b6f2ecc612c5afd5630a3598ca21f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <stdlib.h>

#include "render.h"

typedef struct {
	float r, g, b;
} vec3;

void lerp(vec3* d, const vec3* a, const vec3* b, float t) {
	d->r = a->r + t * (b->r - a->r);
	d->g = a->g + t * (b->g - a->g);
	d->b = a->b + t * (b->b - a->b);
}

#define use_float_sample 0
#if use_float_sample
Colour get_pixel(unsigned* data, int x, int y, int w) {
	vec3 start, end, col;
	float t;
	int i;
	Colour r = { 0 };
	unsigned palette = data[(x / 4 + y / 4 * (w / 4)) * 2];
	unsigned indices = data[(x / 4 + y / 4 * (w / 4)) * 2 + 1];
	start.r = (float)((palette & (31 << 27)) >> 27) / 32.0f;
	start.g = (float)((palette & (63 << 21)) >> 21) / 64.0f;
	start.b = (float)((palette & (31 << 16)) >> 16) / 32.0f;
	end.r   = (float)((palette & (31 << 11)) >> 11) / 32.0f;
	end.g   = (float)((palette & (63 << 5))  >> 5)  / 64.0f;
	end.b   = (float)((palette & (31     ))      )  / 32.0f;
	i = x % 4 + (y % 4) * 4;
	i = (indices & (3 << i * 2)) >> i * 2;
	t = (float)i / 3.0f;
	lerp(&col, &start, &end, t);
	r.r = (int)(col.r * 255.0f);
	r.g = (int)(col.g * 255.0f);
	r.b = (int)(col.b * 255.0f);
	return r;
}
#else
Colour get_pixel(unsigned* data, int x, int y, int w) {
	Colour r;
	int s[3];
	int i;
	int coord = ((x >> 2) + (y >> 2) * (w >> 2)) << 1;
	unsigned pal = data[coord];
	unsigned ind = data[coord + 1];
	s[0] = (pal & (31 << 27)) >> 24;
	s[1] = (pal & (63 << 21)) >> 19;
	s[2] = (pal & (31 << 16)) >> 13;
	i = ((x & 3) + ((y & 3) << 2)) << 1;
	i = (ind & (3 << i)) >> i;
	r.r = s[0] + (i * ((int)((pal & (31 << 11)) >> 8) - s[0]) / 3);
	r.g = s[1] + (i * ((int)((pal & (63 << 5))  >> 3) - s[1]) / 3);
	r.b = s[2] + (i * ((int)((pal & (31     ))  << 3) - s[2]) / 3);
	r.a = 0xff;
	return r;
}
#endif

int main(int argc, const char** argv) {
	FILE* infile, * outfile;
	unsigned* data;
	int w, h, x, y, cw, ch;
	unsigned palette, indices;
	vec3 colour;
	if (argc < 3) {
		fprintf(stderr, "Usage: %s infile outfile.\n", argv[0]);
		return 1;
	}
	infile = fopen(argv[1], "rb");
	if (!infile) {
		fprintf(stderr, "Failed to open %s.\n", argv[1]);
		return 2;
	}
	outfile = fopen(argv[2], "w");
	if (!infile) {
		fprintf(stderr, "Failed to open %s.\n", argv[2]);
		return 3;
	}
	fread(&w, 1, 4, infile);
	fread(&h, 1, 4, infile);
	cw = w / 4;
	ch = h / 4;
	data = malloc(cw * ch * 8);
	fread(data, 1, cw * ch * 8, infile);
	fprintf(outfile, "P3\n");
	fprintf(outfile, "%d %d\n", w, h);
	fprintf(outfile, "255\n");
	for (y = 0; y < h; y++) {
		for (x = 0; x < w; x++) {
			Colour c = get_pixel(data, x, y, w);
			fprintf(outfile, "%d %d %d\n", c.r, c.g, c.b);
		}
	}
}