README: mention SDL2 backend
[rofl0r-concol.git] / nearestcolor.c
blob1e392682ecb8e002e692b0f54fa6fd57f34d84ba
1 #include "console.h"
2 #include "colors.h"
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stddef.h>
6 #include <unistd.h>
7 #include <string.h>
10 #ifndef ARRAY_SIZE
11 #define ARRAY_SIZE(X) (sizeof(X) / sizeof((X)[0]))
12 #endif
14 #ifndef TB_BLACK
16 #define TB_BLACK 0x00
17 #define TB_RED 0x01
18 #define TB_GREEN 0x02
19 #define TB_YELLOW 0x03
20 #define TB_BLUE 0x04
21 #define TB_MAGENTA 0x05
22 #define TB_CYAN 0x06
23 #define TB_WHITE 0x07
25 #endif
27 static const rgb_t defcolors[] = {
28 [TB_BLACK] = RGB3(BLACK),
29 [TB_RED] = RGB3(RED),
30 [TB_GREEN] = RGB3(GREEN),
31 [TB_YELLOW] = RGB3(YELLOW),
32 [TB_BLUE] = RGB3(BLUE),
33 [TB_MAGENTA] = RGB3(MAGENTA),
34 [TB_CYAN] = RGB3(CYAN),
35 [TB_WHITE] = RGB3(WHITE),
38 #define ABS(X) ((X) < 0 ? (X) * -1 : (X))
39 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
40 static int getNearestColor(rgb_t col) {
41 unsigned dist[ARRAY_SIZE(defcolors)];
42 unsigned i;
43 unsigned nearest = 0xFFFFFFFF;
44 unsigned brightestcol = 0;
45 if(col.r == col.g && col.r == col.b) {
46 if(col.r < 128) return TB_BLACK;
47 else return TB_WHITE;
49 brightestcol = MAX(brightestcol, col.r);
50 brightestcol = MAX(brightestcol, col.g);
51 brightestcol = MAX(brightestcol, col.b);
52 brightestcol = MAX(brightestcol, 1);
53 int scale = (255*256) / brightestcol;
54 for(i = 0; i < ARRAY_SIZE(defcolors); i++) {
55 dist[i] = ABS(defcolors[i].r * 256 - col.r * scale) +
56 ABS(defcolors[i].g * 256 - col.g * scale) +
57 ABS(defcolors[i].b * 256 - col.b * scale);
58 if(dist[i] == 0) return i;
59 if(dist[i] < nearest) nearest = dist[i];
61 for(i = 0; i < ARRAY_SIZE(defcolors); i++) {
62 if(dist[i] == nearest) return i;
64 return 0;
68 #if 0
69 int console_setcolor(struct Console* self, int is_fg, rgb_t mycolor) {
70 struct TbConsole *c = &self->backend.tb;
71 int *dest = is_fg ? &c->fgcolor : &c->bgcolor;
72 *dest = getNearestColor(mycolor);
73 return 1;
75 #endif