Skip to content

Commit

Permalink
Use a negative-safe cube root in LMS conversions (#2121)
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed Oct 18, 2023
1 parent 95a0ec5 commit 67a1109
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/src/value/color/space/lms.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ class LmsColorSpace extends ColorSpace {
switch (dest) {
case ColorSpace.oklab:
// Algorithm from https://drafts.csswg.org/css-color-4/#color-conversion-code
var longScaled = math.pow(long, 1 / 3);
var mediumScaled = math.pow(medium, 1 / 3);
var shortScaled = math.pow(short, 1 / 3);
var longScaled = _cubeRootPreservingSign(long);
var mediumScaled = _cubeRootPreservingSign(medium);
var shortScaled = _cubeRootPreservingSign(short);
var lightness = lmsToOklab[0] * longScaled +
lmsToOklab[1] * mediumScaled +
lmsToOklab[2] * shortScaled;
Expand All @@ -62,9 +62,9 @@ class LmsColorSpace extends ColorSpace {
// This is equivalent to converting to OKLab and then to OKLCH, but we
// do it inline to avoid extra list allocations since we expect
// conversions to and from OKLCH to be very common.
var longScaled = math.pow(long, 1 / 3);
var mediumScaled = math.pow(medium, 1 / 3);
var shortScaled = math.pow(short, 1 / 3);
var longScaled = _cubeRootPreservingSign(long);
var mediumScaled = _cubeRootPreservingSign(medium);
var shortScaled = _cubeRootPreservingSign(short);
return labToLch(
dest,
lmsToOklab[0] * longScaled +
Expand All @@ -83,6 +83,11 @@ class LmsColorSpace extends ColorSpace {
}
}

/// Returns the cube root of the absolute value of [number] with the same sign
/// as [number].
double _cubeRootPreservingSign(double number) =>
math.pow(number.abs(), 1 / 3) * number.sign;

@protected
double toLinear(double channel) => channel;

Expand Down

0 comments on commit 67a1109

Please sign in to comment.