96e7a014ceb1eb2c973ca37225ac93988dab558d
[rainbowstream.git] / rainbowstream / image.c
1 typedef struct {
2 int r;
3 int g;
4 int b;
5 } rgb_t;
6 int CUBE_STEPS[] = { 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF };
7 rgb_t BASIC16[] =
8 { { 0, 0, 0 }, { 205, 0, 0}, { 0, 205, 0 },
9 { 205, 205, 0 }, { 0, 0, 238}, { 205, 0, 205 },
10 { 0, 205, 205 }, { 229, 229, 229}, { 127, 127, 127 },
11 { 255, 0, 0 }, { 0, 255, 0}, { 255, 255, 0 },
12 { 92, 92, 255 }, { 255, 0, 255}, { 0, 255, 255 },
13 { 255, 255, 255 } };
14 rgb_t COLOR_TABLE[256];
15
16
17 rgb_t ansi_to_rgb(int xcolor)
18 {
19 rgb_t res;
20 if (xcolor < 16) {
21 res = BASIC16[xcolor];
22 } else if (16 <= xcolor && xcolor <= 231) {
23 xcolor -= 16;
24 res.r = CUBE_STEPS[(xcolor / 36) % 6];
25 res.g = CUBE_STEPS[(xcolor / 6) % 6];
26 res.b = CUBE_STEPS[xcolor % 6];
27 } else if (232 <= xcolor && xcolor <= 255) {
28 res.r = res.g = res.b = 8 + (xcolor - 232) * 0x0A;
29 }
30 return res;
31 }
32
33 int init()
34 {
35 int c;
36 for (c = 0; c < 256; c++) {
37 COLOR_TABLE[c] = ansi_to_rgb(c);
38 }
39 return 0;
40 }
41
42 int rgb_to_ansi(int r, int g, int b)
43 {
44 int best_match = 0;
45 int smallest_distance = 1000000000;
46 int c, d;
47 for (c = 16; c < 256; c++) {
48 d = (COLOR_TABLE[c].r - r)*(COLOR_TABLE[c].r - r) +
49 (COLOR_TABLE[c].g - g)*(COLOR_TABLE[c].g - g) +
50 (COLOR_TABLE[c].b - b)*(COLOR_TABLE[c].b - b);
51 if (d < smallest_distance) {
52 smallest_distance = d;
53 best_match = c;
54 }
55 }
56 return best_match;
57 }