Last active
August 29, 2015 14:23
-
-
Save mfrischknecht/ba8ab9a36565eea9979c to your computer and use it in GitHub Desktop.
Convert HSVA to RGBA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<class T> | |
T clip(const T& n, const T& lower, const T& upper) { | |
return std::max(lower, std::min(n, upper)); | |
} | |
typedef std::array<GLfloat, 4> Color; | |
//Conversion according to http://www.rapidtables.com/convert/color/hsv-to-rgb.htm | |
Color hsva2rgba(const Color &hsva) | |
{ | |
static const double PI = 3.14159265359; | |
GLfloat h = fmod(fmod(hsva[0], 2 * PI) + 2 * PI, 2 * PI); // 0° <= H <= 360° | |
GLfloat s = clip(hsva[1], 0.0f, 1.0f); | |
GLfloat v = clip(hsva[2], 0.0f, 1.0f); | |
GLfloat a = clip(hsva[3], 0.0f, 1.0f); | |
float c = v * s; | |
float x = c * (1.0f - fabs(fmod(h*3.0f / PI, 2.0f) - 1.0f)); | |
float m = v - c; | |
switch (int(floor(h*3.0f / PI))) | |
{ | |
case 0: //[0°,60°) | |
return{ m + c, m + x, m, a }; | |
case 1: //[60°,120°) | |
return{ m + x, m + c, m, a }; | |
case 2: //[120°,180°) | |
return{ m, m + c, m + x, a }; | |
case 3: //[180°,240°) | |
return{ m, m + x, m + c, a }; | |
case 4: //[240°,300°) | |
return{ m + x, m, m + c, a }; | |
case 5: //[300°,360°) | |
return{ m + c, m, m + x, a }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment