Skip to content

Commit 7a31e2b

Browse files
authored
Oklab: Fix rollover error (#1529)
* oklab: Removed unnecessary type conversions * oklab: Fixed rollover error in color conversion
1 parent 80aafa2 commit 7a31e2b

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

libsrc/utils/ColorSys.cpp

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ inline uint8_t clamp(int x)
88
return (x<0) ? 0 : ((x>255) ? 255 : uint8_t(x));
99
}
1010

11+
inline double clamp(double x)
12+
{
13+
return std::max(0.0, std::min(x, 1.0));
14+
}
15+
1116
void ColorSys::rgb2hsl(uint8_t red, uint8_t green, uint8_t blue, uint16_t & hue, float & saturation, float & luminance)
1217
{
1318
QColor color(red,green,blue);
@@ -60,9 +65,9 @@ void ColorSys::yuv2rgb(uint8_t y, uint8_t u, uint8_t v, uint8_t &r, uint8_t &g,
6065

6166
void ColorSys::rgb2okhsv(uint8_t red, uint8_t green, uint8_t blue, double & hue, double & saturation, double & value)
6267
{
63-
ok_color::HSV color = ok_color::srgb_to_okhsv({ static_cast<float>(red) / 255.F,
64-
static_cast<float>(green) / 255.F,
65-
static_cast<float>(blue) / 255.F
68+
ok_color::HSV color = ok_color::srgb_to_okhsv({ static_cast<double>(red) / 255.0,
69+
static_cast<double>(green) / 255.0,
70+
static_cast<double>(blue) / 255.0
6671
});
6772
hue = color.h;
6873
saturation = color.s;
@@ -71,8 +76,9 @@ void ColorSys::rgb2okhsv(uint8_t red, uint8_t green, uint8_t blue, double & hue,
7176

7277
void ColorSys::okhsv2rgb(double hue, double saturation, double value, uint8_t & red, uint8_t & green, uint8_t & blue)
7378
{
74-
ok_color::RGB color = ok_color::okhsv_to_srgb({ static_cast<float>(hue), static_cast<float>(saturation), static_cast<float>(value) });
75-
red = static_cast<uint8_t>(std::lround(color.r * 255));
76-
green = static_cast<uint8_t>(std::lround(color.g * 255));
77-
blue = static_cast<uint8_t>(std::lround(color.b * 255));
79+
ok_color::RGB color = ok_color::okhsv_to_srgb({ hue, saturation, value });
80+
// okhsv_to_srgb can output rgb colors with slightly negative components. Clamping them before casting prevents rollover errors
81+
red = static_cast<uint8_t>(std::lround(clamp(color.r) * 255.0));
82+
green = static_cast<uint8_t>(std::lround(clamp(color.g) * 255.0));
83+
blue = static_cast<uint8_t>(std::lround(clamp(color.b) * 255.0));
7884
}

libsrc/utils/OkhsvTransform.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
#include <utils/ColorSys.h>
55

66
/// Clamps between 0.f and 1.f. Should generally be branchless
7-
double clamp(double value)
7+
inline double clamp(double value)
88
{
99
return std::max(0.0, std::min(value, 1.0));
1010
}

0 commit comments

Comments
 (0)