-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhsbColor.h
109 lines (93 loc) · 2.77 KB
/
hsbColor.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
#pragma once
#include <glm/glm.hpp>
#include "mathutil.h"
struct HSBColor {
float h;
float s;
float b;
float a;
HSBColor(float h, float s, float b, float a) : h(h), s(s), b(b), a(a) {
}
HSBColor(float h, float s, float b) : h(h), s(s), b(b), a(1.0f) {
}
HSBColor() : h(0.0f), s(0.0f), b(0.0f), a(1.0f) {
}
static HSBColor fromRGB(float r, float g, float b, float a) {
HSBColor ret;
float max = std::max(r, std::max(g, b));
if (max <= 0) {
return ret;
}
float min = std::min(r, std::min(g, b));
float dif = max - min;
if (max > min) {
if (g == max) {
ret.h = (b - r) / dif * 60.0f + 120.0f;
} else if (b == max) {
ret.h = (r - g) / dif * 60.0f + 240.0f;
} else if (b > g) {
ret.h = (g - b) / dif * 60.0f + 360.0f;
} else {
ret.h = (g - b) / dif * 60.0f;
}
if (ret.h < 0) {
ret.h = ret.h + 360.0f;
}
} else {
ret.h = 0;
}
ret.h *= 1.0f / 360.0f;
ret.s = (dif / max) * 1.0f;
ret.b = max;
ret.a = a;
return ret;
}
static glm::vec3 toRGB(HSBColor hsbColor) {
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0) {
float max = hsbColor.b;
float dif = hsbColor.b * hsbColor.s;
float min = hsbColor.b - dif;
float h = hsbColor.h * 360.0f;
if (h < 60.0f) {
r = max;
g = h * dif / 60.0f + min;
b = min;
} else if (h < 120.0f) {
r = -(h - 120.0f) * dif / 60.0f + min;
g = max;
b = min;
} else if (h < 180.0f) {
r = min;
g = max;
b = (h - 120.0f) * dif / 60.0f + min;
} else if (h < 240.0f) {
r = min;
g = -(h - 240.0f) * dif / 60.0f + min;
b = max;
} else if (h < 300.0f) {
r = (h - 240.0f) * dif / 60.0f + min;
g = min;
b = max;
} else if (h <= 360.0f) {
r = max;
g = min;
b = -(h - 360.0f) * dif / 60 + min;
} else {
r = 0;
g = 0;
b = 0;
}
}
return glm::vec3(Mth::saturate(r), Mth::saturate(g), Mth::saturate(b));
}
static glm::vec4 toRGBA(HSBColor hsbColor) {
return glm::vec4(hsbColor.toRGB(), hsbColor.a);
}
// convert to RGB color
glm::vec3 toRGB() {
return toRGB(*this);
}
};