Skip to content

Commit a26cdca

Browse files
committed
Add Color::fromHSV() method to replace DeepSkyObject::hsv2rgb()
1 parent 7cf93d9 commit a26cdca

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/celutil/color.cpp

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,49 @@ bool parseHexColor(std::string_view s, Color& c)
216216

217217
} // end unnamed namespace
218218

219+
/*!
220+
* @brief Convert HSV to RGB.
221+
* @param h Hue, [0, 360]
222+
* @param s Saturation, [0, 1]
223+
* @param v Value, [0, 1]
224+
* @return RGBA color
225+
*/
226+
Color Color::fromHSV(float h, float s, float v)
227+
{
228+
if (s == 0.0f)
229+
{
230+
// achromatic (grey)
231+
return { v, v, v };
232+
}
233+
234+
235+
h /= 60.0f; // sector 0 to 5
236+
float j = std::floor(h);
237+
238+
float f = h - j; // fractional part of h
239+
float p = v * (1.0f - s);
240+
float q = v * (1.0f - s * f);
241+
float t = v * (1.0f - s * (1.0f - f));
242+
243+
switch(static_cast<int>(j))
244+
{
245+
case 0:
246+
return { v, t, p };
247+
case 1:
248+
return { q, v, p };
249+
case 2:
250+
return { p, v, t };
251+
case 3:
252+
return { p, q, v };
253+
case 4:
254+
return { t, p, v };
255+
default:
256+
return { v, p, q };
257+
}
258+
}
219259

220260
const Color Color::White = Color(1.0f, 1.0f, 1.0f);
221-
const Color Color::Black = Color(0.0f,0.0f, 0.0f);
261+
const Color Color::Black = Color(0.0f, 0.0f, 0.0f);
222262

223263
/*! Parse a color string and return true if it was a valid color, otherwise
224264
* false. Accetable inputs are HTML/X11 style #xxxxxx colors (where x is

src/celutil/color.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ class Color
115115
static /*constexpr*/ const Color Black/* = Color(1.0f, 1.0f, 1.0f)*/;
116116
static /*constexpr*/ const Color White/* = Color(0.0f,0.0f, 0.0f)*/;
117117

118+
static Color fromHSV(float h, float s, float v);
119+
118120
static bool parse(std::string_view, Color&);
119121
};
120122

0 commit comments

Comments
 (0)