getMaxValidChroma static method

double getMaxValidChroma(
  1. double lightness,
  2. double hue
)

Gets the maximum valid chroma for a given lightness and hue combination.

This function calculates the maximum chroma value that will produce a valid RGB color (within 0-255 range) for the specified lightness and hue. Values beyond this maximum will be outside the sRGB gamut.

Based on Björn Ottosson's research on gamut clipping in Oklab color space. This method finds the intersection of the color with the RGB gamut boundary.

Reference: Björn Ottosson - "Gamut clipping" https://bottosson.github.io/posts/gamutclipping/

Parameters:

  • lightness: Lightness value (0.0 to 1.0)
  • hue: Hue in degrees (0.0 to 360.0)

Returns: Maximum valid chroma for the given lightness and hue

Implementation

static double getMaxValidChroma(double lightness, double hue) {
  // Convert hue to radians for trigonometric calculations
  final hueRadians = hue * math.pi / 180.0;
  final a = math.cos(hueRadians);
  final b = math.sin(hueRadians);

  // Find the maximum chroma point (cusp) for this hue
  final maxChromaPoint = findMaxChromaPoint(a, b);
  final cuspL = maxChromaPoint[0];
  final cuspC = maxChromaPoint[1];

  // If we're at the cusp lightness, return the cusp chroma
  if ((lightness - cuspL).abs() < 1e-6) {
    return cuspC;
  }

  // Calculate maximum chroma for this lightness using gamut intersection
  double maxChroma;

  if (lightness < cuspL) {
    // Below cusp: interpolate between black point (0,0) and cusp
    maxChroma = cuspC * lightness / cuspL;
  } else {
    // Above cusp: interpolate between cusp and white point (1,0)
    final t = (lightness - cuspL) / (1.0 - cuspL);
    maxChroma = cuspC * (1.0 - t);
  }

  return math.max(0.0, maxChroma);
}