lambda-calculus/color_factory/new.c
2025-01-13 20:36:07 -06:00

108 lines
2 KiB
C

#include <limits.h>
#include <math.h>
#include <debug.h>
#include <defines/N.h>
#include <memory/smalloc.h>
#include <string/new.h>
#include "struct.h"
#include "new.h"
struct rgb
{
uint8_t r, g, b;
};
static struct rgb hsv_to_rgb(double hue, double sat, double val)
{
double c = val * sat;
double x = c * (1 - fabs(fmod(hue / (M_PI / 3), 2) - 1));
double m = val - c;
double r, g, b;
if (hue < 1 * M_PI / 3) r = c, g = x, b = 0;
else if (hue < 2 * M_PI / 3) r = x, g = c, b = 0;
else if (hue < 3 * M_PI / 3) r = 0, g = c, b = x;
else if (hue < 4 * M_PI / 3) r = 0, g = x, b = c;
else if (hue < 5 * M_PI / 3) r = x, g = 0, b = c;
else r = c, g = 0, b = x;
return (struct rgb) {
(uint8_t) ((r + m) * 255),
(uint8_t) ((g + m) * 255),
(uint8_t) ((b + m) * 255)};
}
static struct string* new_color_from_hue(
double hue,
double sat,
double val)
{
ENTER;
dpvlf(hue);
dpvlf(sat);
dpvlf(val);
struct rgb rgb = hsv_to_rgb(hue, sat, val);
struct string* string = new_string_from_ascii_format(
"\e[38;2;%hhu;%hhu;%hhum", rgb.r, rgb.g, rgb.b);
EXIT;
return string;
}
struct color_factory* new_color_factory(void)
{
ENTER;
struct color_factory* this = smalloc(sizeof(*this));
for (unsigned i = 0, n = N(this->colors); i < n; i++)
{
this->colors[i] = new_color_from_hue(
/* hue: */ (double) i / N(this->colors) * 2 * M_PI,
/* sat: */ 0.9,
/* val: */ 1.0);
}
this->numeric = new_color_from_hue(31.0 / 180 * M_PI, 0.80, 1.0);
this->string = new_color_from_hue(300.0 / 180 * M_PI, 0.80, 1.0);
this->variable = new_color_from_hue(263.0 / 180 * M_PI, 0.80, 1.0);
this->builtin = new_color_from_hue(0.0, 0.0, 0.52);
this->reset = new_string(L"\e[0m", ULONG_MAX);
EXIT;
return this;
}