MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
ColorSpace.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <glm/glm.hpp>
4
5namespace MayaFlux::Kinesis {
6
7/**
8 * @brief Convert hue, saturation and value to red, green and blue.
9 *
10 * All components are in [0, 1]. Hue wraps, so 1 is the same colour as 0;
11 * saturation and value are clamped.
12 *
13 * @param hsv Hue in x, saturation in y, value in z.
14 * @return Red in x, green in y, blue in z.
15 */
16[[nodiscard]] inline glm::vec3 hsv_to_rgb(glm::vec3 hsv) noexcept
17{
18 const float hue = hsv.x - std::floor(hsv.x);
19 const float saturation = std::clamp(hsv.y, 0.F, 1.F);
20 const float value = std::clamp(hsv.z, 0.F, 1.F);
21 const float sector = hue * 6.F;
22
23 const auto channel = [&](float offset) {
24 const float k = std::fmod(offset + sector, 6.F);
25 return value - value * saturation * std::clamp(std::min(k, 4.F - k), 0.F, 1.F);
26 };
27
28 return { channel(5.F), channel(3.F), channel(1.F) };
29}
30
31/**
32 * @brief Convert red, green and blue to hue, saturation and value.
33 *
34 * Inverse of hsv_to_rgb. Hue is 0 for greys, where it is undefined.
35 *
36 * @param rgb Red in x, green in y, blue in z, each in [0, 1].
37 * @return Hue in x, saturation in y, value in z, each in [0, 1].
38 */
39[[nodiscard]] inline glm::vec3 rgb_to_hsv(glm::vec3 rgb) noexcept
40{
41 const float cmax = std::max({ rgb.x, rgb.y, rgb.z });
42 const float cmin = std::min({ rgb.x, rgb.y, rgb.z });
43 const float delta = cmax - cmin;
44
45 float hue = 0.F;
46 if (delta > 0.F) {
47 if (cmax == rgb.x) {
48 hue = std::fmod((rgb.y - rgb.z) / delta, 6.F);
49 } else if (cmax == rgb.y) {
50 hue = (rgb.z - rgb.x) / delta + 2.F;
51 } else {
52 hue = (rgb.x - rgb.y) / delta + 4.F;
53 }
54 hue /= 6.F;
55 if (hue < 0.F)
56 hue += 1.F;
57 }
58
59 return { hue, cmax > 0.F ? delta / cmax : 0.F, cmax };
60}
61
62} // namespace MayaFlux::Kinesis
uint64_t offset
Definition Composite.cpp:10
glm::vec3 value
glm::vec3 rgb_to_hsv(glm::vec3 rgb) noexcept
Convert red, green and blue to hue, saturation and value.
glm::vec3 hsv_to_rgb(glm::vec3 hsv) noexcept
Convert hue, saturation and value to red, green and blue.