Added support for HSV color space

This commit is contained in:
Robert 2020-05-17 12:25:09 +02:00
parent 05f52a5b79
commit 0c81a94a37
3 changed files with 60 additions and 1 deletions

View file

@ -1,5 +1,7 @@
#include "Color.hpp"
#include <math.h>
namespace sdlu
{
const Color Color::Black = Color(0, 0, 0);
@ -43,4 +45,52 @@ namespace sdlu
color |= a;
return color;
}
Color& Color::FromHSV(Uint16 h, Uint8 s, Uint8 v)
{
// Normalize parameters
// H : [0, 360)
// S : [0, 1]
// V : [0, 1]
h -= floor(h / 360) * 360;
s = (s > 1) ? 1 : s;
v = (v > 1) ? 1 : v;
// Convert to RGBA
Uint16 H = floor(h / 60.f);
float f = (h / 60.f) - H;
Uint8 p = static_cast<Uint8>((v * (1 - s)) * 255);
Uint8 q = static_cast<Uint8>((v * (1 - s * f)) * 255);
Uint8 t = static_cast<Uint8>((v * (1 - s * (1 - f))) * 255);
v *= 255;
Color output;
switch (H)
{
case 0:
case 6:
output = Color(v, t, p);
break;
case 1:
output = Color(q, v, p);
break;
case 2:
output = Color(p, v, t);
break;
case 3:
output = Color(p, q, v);
break;
case 4:
output = Color(t, p, v);
break;
case 5:
output = Color(v, p, q);
break;
default:
break;
}
return output;
}
}

View file

@ -53,6 +53,13 @@ namespace sdlu
*/
Uint32 ToInt();
/**
* @brief Generate color from HSV values
*
* @return An RGBA Color object generated from HSV
*/
static Color& FromHSV(Uint16 h, Uint8 s, Uint8 v);
/////////////////// DEFAULT COLORS ///////////////////

View file

@ -9,6 +9,7 @@ int main(int argc, char** argv)
window.SetMouseCursorGrabbed(true);
SDL_Event event;
float t = 0.f;
while (window.IsOpen())
{
while (window.PollEvent(&event))
@ -21,9 +22,10 @@ int main(int argc, char** argv)
}
}
window.Clear(sdlu::Color::Magenta);
window.Clear(sdlu::Color::FromHSV(floor(t), 100, 100));
window.Display();
t += 0.01;
}
SDL_Quit();