color: common library for RGB and HSV colors
The component is a set of functions and small inline helpers: no hardware, no I2C, no allocation, nothing to initialise. It is used by the LED and display drivers of the project, and it is useful on its own whenever a program has to generate or mix colors.
Color types
rgb_t keeps three 8-bit channels (r, g, b, also reachable as
red, green, blue), and hsv_t keeps hue, saturation and value
(h/hue, s/sat, v/val). Both are plain structs, compared
and copied by value.
rgb_t red = rgb_from_code(0xFF0000); // 0x00RRGGBB
hsv_t cyan = hsv_from_values(128, 255, 255);
bool dark = rgb_is_zero(black);
The hue constants HUE_RED, HUE_ORANGE, HUE_YELLOW, HUE_GREEN,
HUE_AQUA, HUE_BLUE, HUE_PURPLE and HUE_PINK are spaced 32 apart
on the 0…255 hue circle.
HSV to RGB
Function |
Hue range |
Character |
|---|---|---|
|
0…255 |
Visually balanced rainbow, the best yellows and oranges |
|
0…255 |
Mathematically straight spectrum, more green and blue |
|
0…191 |
Same straight spectrum, fastest, the hue must be scaled to 0…191 |
Saturation and value are always 0…255.
rgb2hsv_approximate() goes back from RGB to HSV. The two 8-bit spaces are
not a bijection (for example, no HSV value converts to RGB 255,255,0), so the
result is an approximation. It is most accurate for fully saturated colors that
came from the rainbow conversion, and it is noticeably slower than the forward
conversion.
rgb_heat_color() maps a heat level 0…255 to an approximation of the black
body spectrum, which is handy for fire effects.
Filling arrays
rgb_fill_solid_rgb(leds, count, rgb_from_code(0x002040));
rgb_fill_solid_hsv(leds, count, hsv_from_values(HUE_AQUA, 255, 64));
hsv_fill_solid_hsv(target, count, color);
Gradients come in two families. The HSV family takes a direction, because hue is
a circle: COLOR_FORWARD_HUES (upwards), COLOR_BACKWARD_HUES
(downwards), COLOR_SHORTEST_HUES (the shorter of the two paths) and
COLOR_LONGEST_HUES (the longer one).
rgb_fill_gradient_hsv(target, startpos, startcolor, endpos, endcolor, direction)
fills from position startpos to endpos; the wrappers
rgb_fill_gradient2_hsv(), rgb_fill_gradient3_hsv() and
rgb_fill_gradient4_hsv() fill one, two and three consecutive segments, so
the 2-colour helper builds a single ramp. The
hsv_fill_gradient*_hsv() variants do the same with HSV output. The RGB
family has no direction, because RGB has no color wheel:
rgb_fill_gradient_rgb() and its rgb_fill_gradient2_rgb(),
rgb_fill_gradient3_rgb() and rgb_fill_gradient4_rgb() wrappers.
Positions are array indices and must stay inside the array; to fill only part of a strip, pass that part with its own offsets. If the end position is lower than the start, the two colors are swapped and the range is filled anyway.
Palettes
rgb_t palette[3] = { rgb_from_code(0x200000), rgb_from_code(0x002000), rgb_from_code(0x000020) };
rgb_t c = color_from_palette_rgb(palette, 3, index, 255, true);
color_from_palette_hsv() and color_from_palette_rgb() take an index
of 0…255 and spread the pal_size explicit entries evenly over that range, so
a three-entry palette works for a full 256-step ramp. With blend set, the
values between entries are interpolated (including the wrap from the last entry
back to the first); without it, the entry covering the index is returned (the lower one of the two
neighbours). brightness
scales the result.
blend() mixes two HSV colors by an amount of 0…255 and honours the same
direction constants.
Blur
blur1d(leds, count, 64);
blur2d(leds, width, height, 128, xy_to_offset, &layout);
blur1d() spreads light to the two neighbours; 0 keeps the array untouched,
64 is moderate, about 172 gives a smooth even spread.
blur_rows(), blur_columns() and blur2d() work on a rectangular
matrix and need the application to map (x, y) to an array offset through the
xy_to_offs_cb callback. That is what makes serpentine (zigzag) and other
non-linear layouts work: the filter asks for the neighbour of a pixel and the
callback answers where that pixel lives in memory.
Gamma
uint8_t b = apply_gamma2brightness(128, 2.2f);
rgb_t c = apply_gamma2rgb(color, 2.2f);
rgb_t g = apply_gamma2rgb_channels(color, 2.2f, 2.4f, 2.0f);
The gamma functions raise a channel to the given power through powf(). They
never turn a non-zero channel into zero, so a dim color does not disappear.
Per-channel gamma corrects the different curves of individual LEDs.
Dependencies
The component depends on lib8tion
for the fixed-point helpers (fract8, scaling and addition of 8-bit values).
Example
The component has no runnable example: it needs no hardware and no setup. The
library in action can be seen in led_strip_spi and in the pixelfont
examples.
Reference
Typedefs
- typedef size_t (*xy_to_offs_cb)(void *ctx, size_t x, size_t y)
Function which must be provided by the application for use in two-dimensional filter functions.
Functions
- rgb_t hsv2rgb_rainbow(hsv_t hsv)
Convert HSV to RGB using balanced rainbow.
Convert a hue, saturation, and value to RGB using a visually balanced rainbow (vs a straight mathematical spectrum). This ‘rainbow’ yields better yellow and orange than a straight ‘spectrum’.
Note
here hue is 0-255, not just 0-191
- Parameters:
hsv – HSV color
- Returns:
RGB color
- rgb_t hsv2rgb_spectrum(hsv_t hsv)
Convert HSV to RGB using mathematically straight spectrum.
Convert a hue, saturation, and value to RGB using a mathematically straight spectrum (vs a visually balanced rainbow). This ‘spectrum’ will have more green & blue than a ‘rainbow’, and less yellow and orange.
Note
here hue is 0-255, not just 0-191
- Parameters:
hsv – HSV color
- Returns:
RGB color
- rgb_t hsv2rgb_raw(hsv_t hsv)
Convert HSV to RGB using spectrum.
Convert hue, saturation, and value to RGB. This ‘spectrum’ conversion will be more green & blue than a real ‘rainbow’, and the hue is specified just in the range 0-191. Together, these result in a slightly faster conversion speed, at the expense of color balance.
Note
Hue is 0-191 only! Saturation & value are 0-255 each.
- Parameters:
hsv – HSV color
- Returns:
RGB color
- hsv_t rgb2hsv_approximate(rgb_t rgb)
Recover approximate HSV values from RGB.
This function is a long-term work in process; expect results to change slightly over time as this function is refined and improved.
This function is most accurate when the input is an RGB color that came from a fully-saturated HSV color to start with.
This function is not nearly as fast as HSV-to-RGB. It is provided for those situations when the need for this function cannot be avoided, or when extremely high performance is not needed.
Why is this ‘only’ an “approximation”? Not all RGB colors have HSV equivalents! For example, there is no HSV value that will ever convert to RGB(255,255,0) using the code provided in this library. So if you try to convert RGB(255,255,0) ‘back’ to HSV, you’ll necessarily get only an approximation. Emphasis has been placed on getting the ‘hue’ as close as usefully possible, but even that’s a bit of a challenge. The 8-bit HSV and 8-bit RGB color spaces are not a “bijection”. Nevertheless, this function does a pretty good job, particularly at recovering the ‘hue’ from fully saturated RGB colors that originally came from HSV rainbow colors. The more desaturated the original RGB color is, the rougher the approximation, and the less accurate the results.
- Parameters:
rgb – RGB color
- Returns:
Approximated HSV color
- rgb_t rgb_heat_color(uint8_t temperature)
Approximates a ‘black body radiation’ spectrum for a given ‘heat’ level.
This is useful for animations of ‘fire’. Heat is specified as an arbitrary scale from 0 (cool) to 255 (hot). This is NOT a chromatically correct ‘black body radiation’ spectrum, but it’s surprisingly close, and it’s fast and small.
- void hsv_fill_solid_hsv(hsv_t *target, hsv_t color, size_t num)
Fill an array of HSV colors with a solid HSV color.
- void rgb_fill_solid_hsv(rgb_t *target, hsv_t color, size_t num)
Fill an array of RGB colors with a solid HSV color.
- void rgb_fill_solid_rgb(rgb_t *target, rgb_t color, size_t num)
Fill an array of RGB colors with a solid RGB color.
- void hsv_fill_gradient_hsv(hsv_t *target, size_t startpos, hsv_t startcolor, size_t endpos, hsv_t endcolor, color_gradient_direction_t direction)
Fill an array of HSV colors with a smooth HSV gradient between two specified HSV colors.
Since ‘hue’ is a value around a color wheel, there are always two ways to sweep from one hue to another. This function lets you specify which way you want the hue gradient to sweep around the color wheel:
The default is SHORTEST_HUES, as this is nearly always what is wanted.FORWARD_HUES: hue always goes clockwise BACKWARD_HUES: hue always goes counter-clockwise SHORTEST_HUES: hue goes whichever way is shortest LONGEST_HUES: hue goes whichever way is longest
- static inline void hsv_fill_gradient2_hsv(hsv_t *target, size_t num, hsv_t c1, hsv_t c2, color_gradient_direction_t direction)
- static inline void hsv_fill_gradient3_hsv(hsv_t *target, size_t num, hsv_t c1, hsv_t c2, hsv_t c3, color_gradient_direction_t direction)
- static inline void hsv_fill_gradient4_hsv(hsv_t *target, size_t num, hsv_t c1, hsv_t c2, hsv_t c3, hsv_t c4, color_gradient_direction_t direction)
- void rgb_fill_gradient_hsv(rgb_t *target, size_t startpos, hsv_t startcolor, size_t endpos, hsv_t endcolor, color_gradient_direction_t direction)
Same as hsv_fill_gradient_hsv(), but for array of RGB.
The gradient is computed in HSV space, and then HSV values are converted to RGB as they’re written into the RGB array.
- static inline void rgb_fill_gradient2_hsv(rgb_t *target, size_t num, hsv_t c1, hsv_t c2, color_gradient_direction_t direction)
- static inline void rgb_fill_gradient3_hsv(rgb_t *target, size_t num, hsv_t c1, hsv_t c2, hsv_t c3, color_gradient_direction_t direction)
- static inline void rgb_fill_gradient4_hsv(rgb_t *target, size_t num, hsv_t c1, hsv_t c2, hsv_t c3, hsv_t c4, color_gradient_direction_t direction)
- void rgb_fill_gradient_rgb(rgb_t *leds, size_t startpos, rgb_t startcolor, size_t endpos, rgb_t endcolor)
Fill a range of LEDs with a smooth RGB gradient between two specified RGB colors.
Unlike HSV, there is no ‘color wheel’ in RGB space, and therefore there’s only one ‘direction’ for the gradient to go, and no ‘direction’ is needed.
- static inline void rgb_fill_gradient2_rgb(rgb_t *target, size_t num, rgb_t c1, rgb_t c2)
- static inline void rgb_fill_gradient3_rgb(rgb_t *target, size_t num, rgb_t c1, rgb_t c2, rgb_t c3)
- static inline void rgb_fill_gradient4_rgb(rgb_t *target, size_t num, rgb_t c1, rgb_t c2, rgb_t c3, rgb_t c4)
- hsv_t color_from_palette_hsv(const hsv_t *palette, uint8_t pal_size, uint8_t index, uint8_t brightness, bool blend)
Return an HSV color with ‘index’ from ‘palette’ (array of HSV colors).
Even though palette has lesser than 256 explicily defined entries, you can use an ‘index’ from 0..255. The ‘pal_size’ explicit palette entries will be spread evenly across the 0..255 range, and the intermedate values will be HSV-interpolated between adjacent explicit entries.
- rgb_t color_from_palette_rgb(const rgb_t *palette, uint8_t pal_size, uint8_t index, uint8_t brightness, bool blend)
Same for RGB palette.
- void blur1d(rgb_t *leds, size_t num_leds, fract8 blur_amount)
One-dimensional blur filter.
Spreads light to 2 line neighbors.
0 = no spread at all 64 = moderate spreading 172 = maximum smooth, even spreading
173..255 = wider spreading, but increasing flicker
Total light is NOT entirely conserved, so many repeated calls to ‘blur’ will also result in the light fading, eventually all the way to black; this is by design so that it can be used to (slowly) clear the LEDs to black.
- void blur_columns(rgb_t *leds, size_t width, size_t height, fract8 blur_amount, xy_to_offs_cb xy, void *ctx)
Perform a blur1d on each column of a rectangular matrix.
- void blur_rows(rgb_t *leds, size_t width, size_t height, fract8 blur_amount, xy_to_offs_cb xy, void *ctx)
Perform a blur1d on each row of a rectangular matrix.
- void blur2d(rgb_t *leds, size_t width, size_t height, fract8 blur_amount, xy_to_offs_cb xy, void *ctx)
Two-dimensional blur filter.
Spreads light to 8 XY neighbors.
0 = no spread at all 64 = moderate spreading 172 = maximum smooth, even spreading
173..255 = wider spreading, but increasing flicker
Total light is NOT entirely conserved, so many repeated calls to ‘blur’ will also result in the light fading, eventually all the way to black; this is by design so that it can be used to (slowly) clear the LEDs to black.
- uint8_t apply_gamma2brightness(uint8_t brightness, float gamma)
Single gamma adjustment to a single scalar value.
Bear in mind that RGB leds have only eight bits per channel of color resolution, and that very small, subtle shadings may not be visible.
- rgb_t apply_gamma2rgb(rgb_t c, float gamma)
Single gamma adjustment to each channel of a RGB color.
- rgb_t apply_gamma2rgb_channels(rgb_t c, float gamma_r, float gamma_g, float gamma_b)
Different gamma adjustments for each channel of a RGB color.