-
Notifications
You must be signed in to change notification settings - Fork 93
/
hsvtorgb.h
125 lines (113 loc) · 2.85 KB
/
hsvtorgb.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/************************************************************************/
/* */
/* This file is part of VDrift. */
/* */
/* VDrift is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* VDrift is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with VDrift. If not, see <http://www.gnu.org/licenses/>. */
/* */
/************************************************************************/
#ifndef _HSVTORGB_H
#define _HSVTORGB_H
#include <cmath>
inline void HSVtoRGB(float h, float s, float v, float & r, float & g, float & b)
{
float hi = std::floor(h * 6 + 1.0E-5); // add eps to avoid nummerical precision issues
float f = h * 6 - hi;
float p = v * (1 - s);
float q = v * (1 - (s * f));
float t = v * (1 - (s * (1 - f)));
if (hi == 1)
{
r = q;
g = v;
b = p;
}
else if (hi == 2)
{
r = p;
g = v;
b = t;
}
else if (hi == 3)
{
r = p;
g = q;
b = v;
}
else if (hi == 4)
{
r = t;
g = p;
b = v;
}
else if (hi == 5)
{
r = v;
g = p;
b = q;
}
else
{
r = v;
g = t;
b = p;
}
}
inline void RGBtoHSV(float r, float g, float b, float & h, float & s, float & v)
{
float max = (r > g ? r : g) > b ? (r > g ? r : g) : b;
float min = (r < g ? r : g) < b ? (r < g ? r : g) : b;
float delta = max - min;
v = max;
if (delta == 0)
{
h = 0;
s = 0;
}
else
{
s = delta / max;
if (r == max)
{
h = (g - b) / delta;
}
else if (g == max)
{
h = 2 + (b - r) / delta;
}
else
{
h = 4 + (r - g) / delta;
}
h = h / 6;
if (h < 0)
{
h += 1;
}
}
}
inline unsigned packRGB(float r, float g, float b)
{
unsigned rgb = 0;
rgb |= (unsigned(r * 255) & 255) << 16;
rgb |= (unsigned(g * 255) & 255) << 8;
rgb |= (unsigned(b * 255) & 255) << 0;
return rgb;
}
inline void unpackRGB(unsigned rgb, float & r, float & g, float & b)
{
r = float((rgb >> 16) & 255) / 255;
g = float((rgb >> 8) & 255) / 255;
b = float((rgb >> 0) & 255) / 255;
}
#endif //_HSVTORGB_H