Commit | Line | Data |
---|---|---|
f5677fb1 | 1 | /* |
b13c6a0d | 2 | * This source is borrowed from following link |
f5677fb1 O |
3 | * https://github.com/jart/fabulous/blob/master/fabulous/_xterm256.c |
4 | * I make a slightly change to fit my module here | |
5 | */ | |
60431c3b | 6 | typedef struct { |
7 | int r; | |
8 | int g; | |
9 | int b; | |
10 | } rgb_t; | |
11 | int CUBE_STEPS[] = { 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF }; | |
991c30af | 12 | rgb_t BASIC16[] = |
60431c3b | 13 | { { 0, 0, 0 }, { 205, 0, 0}, { 0, 205, 0 }, |
14 | { 205, 205, 0 }, { 0, 0, 238}, { 205, 0, 205 }, | |
15 | { 0, 205, 205 }, { 229, 229, 229}, { 127, 127, 127 }, | |
16 | { 255, 0, 0 }, { 0, 255, 0}, { 255, 255, 0 }, | |
17 | { 92, 92, 255 }, { 255, 0, 255}, { 0, 255, 255 }, | |
18 | { 255, 255, 255 } }; | |
19 | rgb_t COLOR_TABLE[256]; | |
20 | ||
21 | ||
991c30af | 22 | rgb_t ansi_to_rgb(int xcolor) |
60431c3b | 23 | { |
24 | rgb_t res; | |
25 | if (xcolor < 16) { | |
26 | res = BASIC16[xcolor]; | |
27 | } else if (16 <= xcolor && xcolor <= 231) { | |
28 | xcolor -= 16; | |
29 | res.r = CUBE_STEPS[(xcolor / 36) % 6]; | |
30 | res.g = CUBE_STEPS[(xcolor / 6) % 6]; | |
31 | res.b = CUBE_STEPS[xcolor % 6]; | |
32 | } else if (232 <= xcolor && xcolor <= 255) { | |
33 | res.r = res.g = res.b = 8 + (xcolor - 232) * 0x0A; | |
34 | } | |
35 | return res; | |
36 | } | |
37 | ||
38 | int init() | |
39 | { | |
40 | int c; | |
41 | for (c = 0; c < 256; c++) { | |
991c30af | 42 | COLOR_TABLE[c] = ansi_to_rgb(c); |
60431c3b | 43 | } |
44 | return 0; | |
45 | } | |
46 | ||
47 | int rgb_to_ansi(int r, int g, int b) | |
48 | { | |
49 | int best_match = 0; | |
50 | int smallest_distance = 1000000000; | |
51 | int c, d; | |
52 | for (c = 16; c < 256; c++) { | |
53 | d = (COLOR_TABLE[c].r - r)*(COLOR_TABLE[c].r - r) + | |
54 | (COLOR_TABLE[c].g - g)*(COLOR_TABLE[c].g - g) + | |
55 | (COLOR_TABLE[c].b - b)*(COLOR_TABLE[c].b - b); | |
56 | if (d < smallest_distance) { | |
57 | smallest_distance = d; | |
58 | best_match = c; | |
59 | } | |
60 | } | |
61 | return best_match; | |
62 | } |