Skip to content

Commit 03f314e

Browse files
authored
Allow negative rgb and rgba values and clamp them to range 0-255 (#1129)
When converting rgb and rgba strings to colors, browsers tolerate numbers out of the acceptable color range but BabylonNative does not. This change updates the color string regex to accept negative numbers and clamps them to the acceptable color range of 0 to 255.
1 parent 235552a commit 03f314e

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

Polyfills/Canvas/Source/Colors.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -212,19 +212,19 @@ namespace Babylon::Polyfills::Internal
212212
}
213213

214214
// matches strings of the form rgb(#,#,#) or rgba(#,#,#,#)
215-
static const std::regex rgbRegex("rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(?:,\\s*(\\d{1,3}))?\\s*\\)");
215+
static const std::regex rgbRegex("rgba?\\(\\s*(-?\\d{1,3})\\s*,\\s*(-?\\d{1,3})\\s*,\\s*(-?\\d{1,3})\\s*(?:,\\s*(-?\\d{1,3}))?\\s*\\)");
216216
std::smatch rgbMatch;
217217
if (std::regex_match(str, rgbMatch, rgbRegex))
218218
{
219219
if (rgbMatch.size() == 5)
220220
{
221221
if (rgbMatch[4].matched)
222222
{
223-
return nvgRGBA(std::stoi(rgbMatch[1]), std::stoi(rgbMatch[2]), std::stoi(rgbMatch[3]), std::stoi(rgbMatch[4]));
223+
return nvgRGBA(std::clamp(std::stoi(rgbMatch[1]), 0, 255), std::clamp(std::stoi(rgbMatch[2]), 0, 255), std::clamp(std::stoi(rgbMatch[3]), 0, 255), std::clamp(std::stoi(rgbMatch[4]), 0, 255));
224224
}
225225
else
226226
{
227-
return nvgRGB(std::stoi(rgbMatch[1]), std::stoi(rgbMatch[2]), std::stoi(rgbMatch[3]));
227+
return nvgRGB(std::clamp(std::stoi(rgbMatch[1]), 0, 255), std::clamp(std::stoi(rgbMatch[2]), 0, 255), std::clamp(std::stoi(rgbMatch[3]), 0, 255));
228228
}
229229
}
230230
}

0 commit comments

Comments
 (0)