]> git.lizzy.rs Git - nothing.git/blob - src/color.c
Remove ./ prefix from includes
[nothing.git] / src / color.c
1 #include <SDL2/SDL.h>
2 #include <string.h>
3
4 #include "color.h"
5
6 color_t color(float r, float g, float b, float a)
7 {
8     const color_t result = {
9         .r = r,
10         .g = g,
11         .b = b,
12         .a = a
13     };
14
15     return result;
16 }
17
18 color_t color256(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
19 {
20     return color(
21         (float) r / 255.0f,
22         (float) g / 255.0f,
23         (float) b / 255.0f,
24         (float) a / 255.0f);
25 }
26
27 static Uint8 hex2dec_digit(char c)
28 {
29     if (c >= '0' && c <= '9') {
30         return (Uint8) (c - '0');
31     }
32
33     if (c >= 'A' && c <= 'F') {
34         return (Uint8) (10 + c - 'A');
35     }
36
37     if (c >= 'a' && c <= 'f') {
38         return (Uint8) (10 + c - 'a');
39     }
40
41     return 0;
42 }
43
44 static Uint8 parse_color_component(const char *component)
45 {
46     return (Uint8) (hex2dec_digit(component[0]) * 16 + hex2dec_digit(component[1]));
47 }
48
49 color_t color_from_hexstr(const char *hexstr)
50 {
51     if (strlen(hexstr) != 6) {
52         return color(0.0f, 0.0f, 0.0f, 1.0f);
53     }
54
55     return color256(
56         parse_color_component(hexstr),
57         parse_color_component(hexstr + 2),
58         parse_color_component(hexstr + 4),
59         255);
60 }
61
62 SDL_Color color_for_sdl(color_t color)
63 {
64     const SDL_Color result = {
65         .r = (Uint8)roundf(color.r * 255.0f),
66         .g = (Uint8)roundf(color.g * 255.0f),
67         .b = (Uint8)roundf(color.b * 255.0f),
68         .a = (Uint8)roundf(color.a * 255.0f)
69     };
70
71     return result;
72 }
73
74 color_t color_desaturate(color_t c)
75 {
76     const float k = (c.r + c.g + c.b) / 3.0f;
77     return color(k, k, k, c.a);
78 }