Skip to main content

mln_style/
color.rs

1// Color stores straight, unclipped extended-sRGB channels (`r`, `g`, `b` in
2// `0..=1` inside sRGB and outside it for wide-gamut colors) plus `a` in `0..=1`.
3// `to_premultiplied` clips to sRGB and premultiplies for GPU rendering;
4// `to_array` / `stringify` clip to sRGB `0..=255` as the style spec's `to-rgba`
5// and `to-string` require; `serialize` / `serialize_string` preserve wide-gamut
6// channels as `color(display-p3 ...)` so JSON round-trips keep interpolation
7// intact.
8
9use std::f64::consts::{PI, TAU};
10
11use crate::feature::Value;
12use crate::interpolate::Interpolate;
13use crate::string::to_string_double;
14
15mod css;
16
17/// The space a color interpolation runs in: RGB, LAB and HCL blend the
18/// straight color, OKLCH the premultiplied lightness
19/// and chroma, and OKLAB the premultiplied lightness, a and b.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
21pub enum ColorSpace {
22    Rgb,
23    Lab,
24    Hcl,
25    Oklch,
26    Oklab,
27}
28
29/// A straight, unclipped extended-sRGB color: `r`, `g` and `b` are in `0..=1`
30/// inside sRGB and outside it for wide-gamut colors, and `a` is in `0..=1`.
31#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
32pub struct Color {
33    r: f32,
34    g: f32,
35    b: f32,
36    a: f32,
37}
38
39// Below these chromas a hue is missing: for HCL, a chroma that rounds to 0
40// at four decimals, and CSS Color 4's for OKLCH
41// (https://drafts.csswg.org/css-color-4/#powerless). The conversions give
42// grays a tiny chroma and some hue.
43const HCL_POWERLESS_CHROMA: f64 = 0.000_05;
44const OKLCH_POWERLESS_CHROMA: f64 = 0.000_004;
45
46// Conversions between sRGB, Oklab and Display P3: CSS Color 4's matrices
47// (https://drafts.csswg.org/css-color-4/#color-conversion-code) in f64, and
48// sRGB's transfer function odd about 0, so a color outside sRGB converts
49// with its channels outside 0..1, and back.
50
51type Vector3 = [f64; 3];
52type Matrix3 = [Vector3; 3];
53
54const LINEAR_SRGB_TO_XYZ: Matrix3 = [
55    [506_752.0 / 1_228_815.0, 87_881.0 / 245_763.0, 12_673.0 / 70_218.0],
56    [87_098.0 / 409_605.0, 175_762.0 / 245_763.0, 12_673.0 / 175_545.0],
57    [7_918.0 / 409_605.0, 87_881.0 / 737_289.0, 1_001_167.0 / 1_053_270.0],
58];
59const XYZ_TO_LINEAR_SRGB: Matrix3 = [
60    [12_831.0 / 3_959.0, -329.0 / 214.0, -1_974.0 / 3_959.0],
61    [-851_781.0 / 878_810.0, 1_648_619.0 / 878_810.0, 36_519.0 / 878_810.0],
62    [705.0 / 12_673.0, -2_585.0 / 12_673.0, 705.0 / 667.0],
63];
64const XYZ_TO_LMS: Matrix3 = [
65    [0.819_022_437_996_703, 0.361_906_260_052_890_4, -0.128_873_781_520_987_9],
66    [0.032_983_653_932_388_5, 0.929_286_861_586_343_4, 0.036_144_666_350_642_4],
67    [0.048_177_189_359_624_2, 0.264_239_531_752_730_8, 0.633_547_828_469_430_9],
68];
69const LMS_TO_OKLAB: Matrix3 = [
70    [0.210_454_268_309_314, 0.793_617_774_702_305_4, -0.004_072_043_011_619_3],
71    [1.977_998_532_431_168_4, -2.428_592_242_048_58, 0.450_593_709_617_411],
72    [0.025_904_042_465_547_8, 0.782_771_712_457_529_6, -0.808_675_754_923_077_4],
73];
74const OKLAB_TO_LMS: Matrix3 = [
75    [1.0, 0.396_337_777_376_174_9, 0.215_803_757_309_913_6],
76    [1.0, -0.105_561_345_815_658_6, -0.063_854_172_825_813_3],
77    [1.0, -0.089_484_177_529_811_9, -1.291_485_548_019_409_2],
78];
79const LMS_TO_XYZ: Matrix3 = [
80    [1.226_879_875_845_924_3, -0.557_814_994_460_217_1, 0.281_391_045_665_964_7],
81    [-0.040_575_745_214_800_8, 1.112_286_803_280_317, -0.071_711_058_065_516_4],
82    [-0.076_372_936_674_660_1, -0.421_493_332_402_243_2, 1.586_924_019_836_781_6],
83];
84const LINEAR_DISPLAY_P3_TO_XYZ: Matrix3 = [
85    [608_311.0 / 1_250_200.0, 189_793.0 / 714_400.0, 198_249.0 / 1_000_160.0],
86    [35_783.0 / 156_275.0, 247_089.0 / 357_200.0, 198_249.0 / 2_500_400.0],
87    [0.0, 32_229.0 / 714_400.0, 5_220_557.0 / 5_000_800.0],
88];
89const XYZ_TO_LINEAR_DISPLAY_P3: Matrix3 = [
90    [446_124.0 / 178_915.0, -333_277.0 / 357_830.0, -72_051.0 / 178_915.0],
91    [-14_852.0 / 17_905.0, 63_121.0 / 35_810.0, 423.0 / 17_905.0],
92    [11_844.0 / 330_415.0, -50_337.0 / 660_830.0, 316_169.0 / 330_415.0],
93];
94
95/// Past this chroma an Oklch color clips to the same sRGB color: the style
96/// spec's bound, which keeps the conversion finite.
97const MAX_CHROMA: f64 = 1e6;
98/// The same bound on a Display P3 component.
99const MAX_DISPLAY_P3_COMPONENT: f64 = 1e6;
100
101fn multiply(m: &Matrix3, [x, y, z]: Vector3) -> Vector3 {
102    [
103        m[0][0] * x + m[0][1] * y + m[0][2] * z,
104        m[1][0] * x + m[1][1] * y + m[1][2] * z,
105        m[2][0] * x + m[2][1] * y + m[2][2] * z,
106    ]
107}
108
109/// sRGB's (and Display P3's) transfer function, to linear light.
110fn srgb_to_linear(x: f64) -> f64 {
111    let abs = x.abs();
112    if abs <= 0.040_45 { x / 12.92 } else { ((abs + 0.055) / 1.055).powf(2.4).copysign(x) }
113}
114
115fn linear_to_srgb(x: f64) -> f64 {
116    let abs = x.abs();
117    if abs > 0.003_130_8 { (1.055 * abs.powf(1.0 / 2.4) - 0.055).copysign(x) } else { 12.92 * x }
118}
119
120fn srgb_to_oklab(rgb: Vector3) -> Vector3 {
121    let [l, m, s] = multiply(&XYZ_TO_LMS, multiply(&LINEAR_SRGB_TO_XYZ, rgb.map(srgb_to_linear)));
122    multiply(&LMS_TO_OKLAB, [l.cbrt(), m.cbrt(), s.cbrt()])
123}
124
125fn oklab_to_srgb(lab: Vector3) -> Vector3 {
126    let [l, m, s] = multiply(&OKLAB_TO_LMS, lab);
127    multiply(&XYZ_TO_LINEAR_SRGB, multiply(&LMS_TO_XYZ, [l * l * l, m * m * m, s * s * s])).map(linear_to_srgb)
128}
129
130/// Oklch with its hue in radians, a missing (NaN) hue converting as 0.
131fn oklch_to_srgb(l: f64, c: f64, h: f64) -> Vector3 {
132    let hue = if h.is_nan() { 0.0 } else { h };
133    let chroma = c.min(MAX_CHROMA);
134    oklab_to_srgb([l, chroma * hue.cos(), chroma * hue.sin()])
135}
136
137/// Oklab through its polar form, as the style spec converts it, which bounds
138/// the chroma.
139fn oklab_via_oklch_to_srgb(l: f64, a: f64, b: f64) -> Vector3 {
140    oklch_to_srgb(l, a.hypot(b), b.atan2(a))
141}
142
143fn display_p3_to_srgb(rgb: Vector3) -> Vector3 {
144    let linear = rgb.map(|c| srgb_to_linear(c.clamp(-MAX_DISPLAY_P3_COMPONENT, MAX_DISPLAY_P3_COMPONENT)));
145    multiply(&XYZ_TO_LINEAR_SRGB, multiply(&LINEAR_DISPLAY_P3_TO_XYZ, linear)).map(linear_to_srgb)
146}
147
148fn srgb_to_display_p3(rgb: Vector3) -> Vector3 {
149    let xyz = multiply(&LINEAR_SRGB_TO_XYZ, rgb.map(srgb_to_linear));
150    multiply(&XYZ_TO_LINEAR_DISPLAY_P3, xyz).map(linear_to_srgb)
151}
152
153// CIE Lab (D50) and its polar form, HCL, as the style spec converts them
154// (https://observablehq.com/@mbostock/lab-and-rgb), with sRGB's transfer
155// function odd about 0 both ways.
156const LAB_XN: f64 = 0.964_22;
157const LAB_YN: f64 = 1.0;
158const LAB_ZN: f64 = 0.825_21;
159const LAB_T0: f64 = 4.0 / 29.0;
160const LAB_T1: f64 = 6.0 / 29.0;
161const LAB_T2: f64 = 3.0 * LAB_T1 * LAB_T1;
162const LAB_T3: f64 = LAB_T1 * LAB_T1 * LAB_T1;
163
164fn xyz_to_lab(t: f64) -> f64 {
165    if t > LAB_T3 { t.powf(1.0 / 3.0) } else { t / LAB_T2 + LAB_T0 }
166}
167
168fn lab_to_xyz(t: f64) -> f64 {
169    if t > LAB_T1 { t * t * t } else { LAB_T2 * (t - LAB_T0) }
170}
171
172/// The style spec's own encoding back to sRGB, whose linear part ends at
173/// 0.00304.
174fn xyz_to_srgb(x: f64) -> f64 {
175    let abs = x.abs();
176    if abs <= 0.003_04 { 12.92 * x } else { (1.055 * abs.powf(1.0 / 2.4) - 0.055).copysign(x) }
177}
178
179fn srgb_to_lab(rgb: Vector3) -> Vector3 {
180    let [r, g, b] = rgb.map(srgb_to_linear);
181    let y = xyz_to_lab((0.222_504_5 * r + 0.716_878_6 * g + 0.060_616_9 * b) / LAB_YN);
182    let (x, z) = if r == g && g == b {
183        (y, y)
184    } else {
185        (
186            xyz_to_lab((0.436_074_7 * r + 0.385_064_9 * g + 0.143_080_4 * b) / LAB_XN),
187            xyz_to_lab((0.013_932_2 * r + 0.097_104_5 * g + 0.714_173_3 * b) / LAB_ZN),
188        )
189    };
190    [116.0 * y - 16.0, 500.0 * (x - y), 200.0 * (y - z)]
191}
192
193fn lab_to_srgb([l, a, b]: Vector3) -> Vector3 {
194    let y = (l + 16.0) / 116.0;
195    let x = if a.is_nan() { y } else { y + a / 500.0 };
196    let z = if b.is_nan() { y } else { y - b / 200.0 };
197    let (x, y, z) = (LAB_XN * lab_to_xyz(x), LAB_YN * lab_to_xyz(y), LAB_ZN * lab_to_xyz(z));
198    [
199        xyz_to_srgb(3.133_856_1 * x - 1.616_866_7 * y - 0.490_614_6 * z),
200        xyz_to_srgb(-0.978_768_4 * x + 1.916_141_5 * y + 0.033_454 * z),
201        xyz_to_srgb(0.071_945_3 * x - 0.228_991_4 * y + 1.405_242_7 * z),
202    ]
203}
204
205/// HCL with its hue in radians, a missing (NaN) hue converting as 0.
206fn hcl_to_srgb(l: f64, c: f64, h: f64) -> Vector3 {
207    let hue = if h.is_nan() { 0.0 } else { h };
208    lab_to_srgb([l, hue.cos() * c, hue.sin() * c])
209}
210
211fn lerp(a: f64, b: f64, t: f64) -> f64 {
212    a * (1.0 - t) + b * t
213}
214
215/// How far `to` is from `from` the shorter way around, in radians.
216fn hue_difference(from: f64, to: f64) -> f64 {
217    let difference = to - from;
218    if difference > PI {
219        difference - TAU
220    } else if difference < -PI {
221        difference + TAU
222    } else {
223        difference
224    }
225}
226
227/// `[l, c, h, alpha]` in the polar form of CIE Lab, the hue in radians, NaN
228/// when it's missing. A color darker than black keeps its lightness below 0.
229fn to_hcl(color: &Color) -> [f64; 4] {
230    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
231    let [l, a, b] = srgb_to_lab([r, g, b]);
232    let c = (a * a + b * b).sqrt();
233    [l, c, if c < HCL_POWERLESS_CHROMA { f64::NAN } else { b.atan2(a) }, alpha]
234}
235
236/// The style spec's LAB interpolation: lightness, a, b and alpha, straight.
237fn interpolate_lab(from: &Color, to: &Color, t: f64) -> Color {
238    let [r1, g1, b1, alpha1] = from.straight_rgba().map(f64::from);
239    let [r2, g2, b2, alpha2] = to.straight_rgba().map(f64::from);
240    let (lab1, lab2) = (srgb_to_lab([r1, g1, b1]), srgb_to_lab([r2, g2, b2]));
241    let mix = |a: f64, b: f64| a + t * (b - a);
242    let rgb = lab_to_srgb([mix(lab1[0], lab2[0]), mix(lab1[1], lab2[1]), mix(lab1[2], lab2[2])]);
243    Color::from_straight(rgb, mix(alpha1, alpha2))
244}
245
246/// `[l, a, b, alpha]` in Oklab.
247fn to_oklab(color: &Color) -> [f64; 4] {
248    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
249    let [l, a, b] = srgb_to_oklab([r, g, b]);
250    [l, a, b, alpha]
251}
252
253/// `[l, c, h, alpha]` in Oklch, the hue in radians: NaN, with no chroma, when
254/// it's missing.
255fn to_oklch(color: &Color) -> [f64; 4] {
256    let [r, g, b, alpha] = color.straight_rgba().map(f64::from);
257    let [l, a, b] = srgb_to_oklab([r, g, b]);
258    let c = (a * a + b * b).sqrt();
259    if c <= OKLCH_POWERLESS_CHROMA { [l, 0.0, f64::NAN, alpha] } else { [l, c, b.atan2(a), alpha] }
260}
261
262// In HCL, a missing hue takes the other color's, and so does the chroma when
263// the color missing it is black or white.
264fn interpolate_hcl(from: &Color, to: &Color, t: f64) -> Color {
265    let [l1, c1, h1, alpha1] = to_hcl(from);
266    let [l2, c2, h2, alpha2] = to_hcl(to);
267    let mut chroma = lerp(c1, c2, t);
268    let hue = match (h1.is_nan(), h2.is_nan()) {
269        (false, false) => h1 + t * hue_difference(h1, h2),
270        (false, true) => {
271            if l2 == 1.0 || l2 == 0.0 {
272                chroma = c1;
273            }
274            h1
275        }
276        (true, false) => {
277            if l1 == 1.0 || l1 == 0.0 {
278                chroma = c2;
279            }
280            h2
281        }
282        (true, true) => f64::NAN,
283    };
284    let rgb = hcl_to_srgb(lerp(l1, l2, t), chroma, hue);
285    Color::from_straight(rgb, lerp(alpha1, alpha2, t))
286}
287
288// https://drafts.csswg.org/css-color-4/#interpolation: a missing hue takes the
289// other's, and lightness and chroma are premultiplied.
290fn interpolate_oklch(from: &Color, to: &Color, t: f64) -> Color {
291    let [l1, c1, h1, alpha1] = to_oklch(from);
292    let [l2, c2, h2, alpha2] = to_oklch(to);
293    let (h1, h2) = (if h1.is_nan() { h2 } else { h1 }, if h2.is_nan() { h1 } else { h2 });
294    let alpha = lerp(alpha1, alpha2, t);
295    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
296    let rgb = oklch_to_srgb(
297        lerp(l1 * alpha1, l2 * alpha2, t) / divisor,
298        lerp(c1 * alpha1, c2 * alpha2, t) / divisor,
299        h1 + t * hue_difference(h1, h2),
300    );
301    Color::from_straight(rgb, alpha)
302}
303
304// https://drafts.csswg.org/css-color-4/#interpolation: lightness, a and b
305// are premultiplied, and there is no hue to fix up.
306fn interpolate_oklab(from: &Color, to: &Color, t: f64) -> Color {
307    let [l1, a1, b1, alpha1] = to_oklab(from);
308    let [l2, a2, b2, alpha2] = to_oklab(to);
309    let alpha = lerp(alpha1, alpha2, t);
310    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
311    let rgb = oklab_via_oklch_to_srgb(
312        lerp(l1 * alpha1, l2 * alpha2, t) / divisor,
313        lerp(a1 * alpha1, a2 * alpha2, t) / divisor,
314        lerp(b1 * alpha1, b2 * alpha2, t) / divisor,
315    );
316    Color::from_straight(rgb, alpha)
317}
318
319/// The style spec's RGB interpolation: red, green, blue and alpha, straight.
320fn interpolate_rgb(from: &Color, to: &Color, t: f64) -> Color {
321    let from = from.straight_rgba().map(f64::from);
322    let to = to.straight_rgba().map(f64::from);
323    let [r, g, b, alpha] = from.interpolate(&to, t);
324    Color::from_straight([r, g, b], alpha)
325}
326
327const fn normalize_zero(v: f32) -> f32 {
328    if v == 0.0 { 0.0 } else { v }
329}
330
331/// Scales a straight sRGB channel in `0..=1` to `0..=255`, returning the exact
332/// integer when `c` is its `f32` representation.
333fn channel_255(c: f32) -> f64 {
334    let scaled = f64::from(c) * 255.0;
335    let rounded = scaled.round();
336    if (rounded / 255.0) as f32 == c { rounded } else { scaled }
337}
338
339impl Color {
340    /// A straight extended-sRGB color with alpha in `0..=1`.
341    #[must_use]
342    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
343        debug_assert!(a >= 0.0 && a <= 1.0);
344        Color { r: normalize_zero(r), g: normalize_zero(g), b: normalize_zero(b), a: normalize_zero(a) }
345    }
346
347    /// A straight extended-sRGB color from `f64` channels.
348    #[must_use]
349    pub(crate) fn from_straight(rgb: [f64; 3], alpha: f64) -> Color {
350        Color::rgba(rgb[0] as f32, rgb[1] as f32, rgb[2] as f32, alpha as f32)
351    }
352
353    /// The alpha channel, in `0..=1`.
354    #[must_use]
355    pub const fn alpha(self) -> f32 {
356        self.a
357    }
358
359    /// The straight color, unclipped (the style spec's `unclippedRgb`).
360    #[must_use]
361    pub const fn straight_rgba(self) -> [f32; 4] {
362        [self.r, self.g, self.b, self.a]
363    }
364
365    /// The straight color, clipped channel by channel to sRGB (`0..=1`).
366    #[must_use]
367    pub fn to_srgb(self) -> [f32; 4] {
368        [self.r.clamp(0.0, 1.0), self.g.clamp(0.0, 1.0), self.b.clamp(0.0, 1.0), self.a]
369    }
370
371    /// Premultiplied sRGB `[r*a, g*a, b*a, a]`, clipped to `0..=1`.
372    #[must_use]
373    pub fn to_premultiplied(self) -> [f32; 4] {
374        let [r, g, b, a] = self.to_srgb();
375        [r * a, g * a, b * a, a]
376    }
377
378    /// Whether every RGB channel lies within the sRGB gamut (`0..=1`).
379    fn is_in_srgb(self) -> bool {
380        [self.r, self.g, self.b].iter().all(|c| (0.0..=1.0).contains(c))
381    }
382
383    #[must_use]
384    pub const fn black() -> Self {
385        Color::rgba(0.0, 0.0, 0.0, 1.0)
386    }
387    #[must_use]
388    pub const fn white() -> Self {
389        Color::rgba(1.0, 1.0, 1.0, 1.0)
390    }
391    #[must_use]
392    pub const fn red() -> Self {
393        Color::rgba(1.0, 0.0, 0.0, 1.0)
394    }
395    #[must_use]
396    pub const fn green() -> Self {
397        Color::rgba(0.0, 1.0, 0.0, 1.0)
398    }
399    #[must_use]
400    pub const fn blue() -> Self {
401        Color::rgba(0.0, 0.0, 1.0, 1.0)
402    }
403
404    /// Parse a CSS color string as the style spec does, keeping straight
405    /// extended-sRGB channel precision rather than rounding to 8 bits.
406    #[must_use]
407    pub fn parse(s: &str) -> Option<Color> {
408        let (rgb, alpha) = css::parse(s)?;
409        Some(Color::from_straight(rgb, alpha))
410    }
411
412    /// The straight `[r, g, b, a]` of a CSS color string, as the style spec
413    /// parses it: red, green and blue are 0..1 inside sRGB and unclipped
414    /// outside it.
415    #[must_use]
416    pub fn parse_straight(s: &str) -> Option<[f64; 4]> {
417        let ([r, g, b], alpha) = css::parse(s)?;
418        Some([r, g, b, alpha])
419    }
420
421    #[must_use]
422    pub fn interpolate(from: &Color, to: &Color, t: f64, space: ColorSpace) -> Color {
423        match space {
424            ColorSpace::Rgb => interpolate_rgb(from, to, t),
425            ColorSpace::Lab => interpolate_lab(from, to, t),
426            ColorSpace::Hcl => interpolate_hcl(from, to, t),
427            ColorSpace::Oklch => interpolate_oklch(from, to, t),
428            ColorSpace::Oklab => interpolate_oklab(from, to, t),
429        }
430    }
431
432    /// Straight `[r*255, g*255, b*255, a]`, clipped to sRGB (`0..=255`).
433    #[must_use]
434    pub fn to_array(self) -> [f64; 4] {
435        let [r, g, b, a] = self.to_srgb();
436        [channel_255(r), channel_255(g), channel_255(b), f64::from(a)]
437    }
438
439    #[must_use]
440    pub fn stringify(&self) -> String {
441        // The style spec's `rgba(r,g,b,a)`: whole sRGB channels, alpha as is.
442        let array = self.to_array();
443        let channel = |value: f64| to_string_double((value + 0.5).floor());
444        format!(
445            "rgba({},{},{},{})",
446            channel(array[0]),
447            channel(array[1]),
448            channel(array[2]),
449            to_string_double(array[3])
450        )
451    }
452
453    /// A CSS color string that [`Self::parse`] recovers with full channel
454    /// precision: `rgba(r,g,b,a)` inside sRGB and `color(display-p3 ...)`
455    /// outside it.
456    #[must_use]
457    pub(crate) fn serialize_string(&self) -> String {
458        if self.is_in_srgb() {
459            let [r, g, b, a] = self.to_array();
460            format!(
461                "rgba({},{},{},{})",
462                to_string_double(r),
463                to_string_double(g),
464                to_string_double(b),
465                to_string_double(a)
466            )
467        } else {
468            let [r, g, b] = srgb_to_display_p3([f64::from(self.r), f64::from(self.g), f64::from(self.b)]);
469            if self.a == 1.0 {
470                format!("color(display-p3 {} {} {})", to_string_double(r), to_string_double(g), to_string_double(b))
471            } else {
472                format!(
473                    "color(display-p3 {} {} {} / {})",
474                    to_string_double(r),
475                    to_string_double(g),
476                    to_string_double(b),
477                    to_string_double(f64::from(self.a))
478                )
479            }
480        }
481    }
482
483    /// Emit as a color-typed expression for expression serialization:
484    /// `["rgba", r, g, b, a]` inside sRGB, or `["to-color", "color(display-p3 ...)"]`
485    /// outside sRGB so unclipped channels survive JSON round-trips.
486    #[must_use]
487    pub fn serialize(&self) -> Value {
488        if self.is_in_srgb() {
489            let [r, g, b, a] = self.to_array();
490            Value::Array(vec![
491                Value::String("rgba".to_owned()),
492                Value::Double(r),
493                Value::Double(g),
494                Value::Double(b),
495                Value::Double(a),
496            ])
497        } else {
498            Value::Array(vec![Value::String("to-color".to_owned()), Value::String(self.serialize_string())])
499        }
500    }
501}
502
503impl std::ops::Mul<f32> for Color {
504    type Output = Color;
505    fn mul(self, alpha: f32) -> Color {
506        debug_assert!((0.0..=1.0).contains(&alpha));
507        Color { a: normalize_zero(self.a * alpha), ..self }
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    use approx::assert_abs_diff_eq;
514
515    use super::*;
516
517    /// `parse` keeps straight channels; `to_premultiplied` premultiplies and
518    /// `to_array` scales to 0..255, even where alpha is 0.
519    #[test]
520    fn parse_and_views_preserve_straight_and_premultiplied_channels() {
521        for (css, premultiplied, straight) in [
522            ("rgba(255, 0, 0, 0.5)", [0.5, 0.0, 0.0, 0.5], [255.0, 0.0, 0.0, 0.5]),
523            ("rgba(255, 51, 0, 1)", [1.0, 0.2, 0.0, 1.0], [255.0, 51.0, 0.0, 1.0]),
524            ("rgba(255, 0, 0, 0)", [0.0, 0.0, 0.0, 0.0], [255.0, 0.0, 0.0, 0.0]),
525        ] {
526            let c = Color::parse(css).unwrap();
527            assert_abs_diff_eq!(&c.to_premultiplied()[..], &premultiplied[..], epsilon = 1e-6);
528            assert_abs_diff_eq!(&c.to_array()[..], &straight[..], epsilon = 1e-3);
529        }
530    }
531
532    fn serialized_rgba(c: &Color) -> [f64; 4] {
533        let Value::Array(a) = c.serialize() else { panic!("not an array") };
534        assert_eq!(a[0], Value::String("rgba".to_owned()));
535        let n = |v: &Value| match v {
536            Value::Double(d) => *d,
537            _ => panic!("not a number"),
538        };
539        [n(&a[1]), n(&a[2]), n(&a[3]), n(&a[4])]
540    }
541
542    /// What `serialize` and `serialize_string` write parses back to the exact
543    /// same color, for sRGB, translucent, transparent, and wide-gamut colors.
544    #[test]
545    fn serialize_round_trips_srgb_and_wide_gamut_colors() {
546        for css in [
547            "red",
548            "rgba(255, 0, 0, 0.5)",
549            "rgba(170, 255, 0, 0.6)",
550            "rgba(1, 2, 3, 0.678)",
551            "rgba(9, 0, 0, 0.2)",
552            "rgba(255, 0, 0, 0)",
553            "#123456",
554        ] {
555            let c = Color::parse(css).unwrap();
556            let [r, g, b, a] = serialized_rgba(&c);
557            assert_eq!(Color::from_straight([r / 255.0, g / 255.0, b / 255.0], a), c, "{css}");
558            assert_eq!(Color::parse(&c.serialize_string()), Some(c), "{css}");
559        }
560        assert_eq!(serialized_rgba(&Color::parse("rgba(255, 0, 0, 0.5)").unwrap()), [255.0, 0.0, 0.0, 0.5]);
561        assert_eq!(
562            serialized_rgba(&Color::parse("rgba(1, 2, 3, 0.678)").unwrap()),
563            [1.0, 2.0, 3.0, f64::from(0.678f32)]
564        );
565
566        let wide_gamut = [
567            Color::parse("color(display-p3 0 1 0)").unwrap(),
568            Color::parse("color(display-p3 0 1 0 / 0.5)").unwrap(),
569            Color::parse("color(display-p3 0 1 0 / 0)").unwrap(),
570            Color::parse("color(display-p3 -0.1 -0.1 -0.1)").unwrap(),
571            Color::parse("color(display-p3 1.2 -0.1 0.3)").unwrap(),
572            Color::parse("oklch(0.7 0.3 140)").unwrap(),
573            Color::parse("oklab(0.7 -0.229813 0.192836)").unwrap(),
574        ];
575        for c in wide_gamut {
576            let css = c.serialize_string();
577            assert!(css.starts_with("color(display-p3 "), "{css}");
578            let Value::Array(expr) = c.serialize() else { panic!("not an array") };
579            assert_eq!(expr, vec![Value::String("to-color".to_owned()), Value::String(css.clone())]);
580            let reparsed = Color::parse(&css).unwrap_or_else(|| panic!("failed to reparse {css}"));
581            assert_eq!(reparsed, c, "{css}");
582            assert_eq!(reparsed.serialize_string(), css);
583        }
584
585        // Exact-zero channels alongside out-of-gamut channels, and large
586        // channel ratios, round-trip through Display P3 within f32 matrix noise.
587        for c in [Color::rgba(0.0, 1.2, 0.0, 1.0), Color::rgba(80_000.0, 0.5, 0.2, 1.0)] {
588            let css = c.serialize_string();
589            let reparsed = Color::parse(&css).unwrap_or_else(|| panic!("failed to reparse {css}"));
590            assert_abs_diff_eq!(&reparsed.straight_rgba()[..], &c.straight_rgba()[..], epsilon = 1e-5);
591        }
592    }
593
594    /// `actual` is the premultiplied sRGB color `r, g, b, a`, within 1e-5.
595    #[track_caller]
596    fn assert_color(actual: Color, [r, g, b, a]: [f32; 4]) {
597        assert_abs_diff_eq!(&[r, g, b, a][..], &actual.to_premultiplied()[..], epsilon = 1e-5);
598    }
599
600    /// A transparent color keeps its straight channels: they blend, survive
601    /// multiplying alpha to 0, and cross the wire to a worker with the color.
602    #[test]
603    fn a_transparent_color_keeps_its_channels() {
604        let red = Color::parse("rgba(255,0,0,0)").unwrap();
605        assert_color(Color::interpolate(&red, &Color::blue(), 0.5, ColorSpace::Rgb), [0.25, 0.0, 0.25, 0.5]);
606        assert_eq!(Color::red() * 0.0, red);
607        let transparent = Color::interpolate(&red, &Color::parse("rgba(0,0,255,0)").unwrap(), 0.5, ColorSpace::Rgb);
608        assert_eq!(transparent.to_array(), [127.5, 0.0, 127.5, 0.0]);
609        let crossed: Color = mln_wire::from_slice(&mln_wire::to_vec(&red).unwrap()).unwrap();
610        assert_eq!(crossed, red);
611    }
612
613    /// A color outside sRGB clips channel by channel, and interpolation reads
614    /// it unclipped, lightness below 0 included.
615    #[test]
616    fn interpolation_reads_a_color_outside_srgb_unclipped() {
617        let green = Color::parse("color(display-p3 0 1 0)").unwrap();
618        assert_color(green, [0.0, 1.0, 0.0, 1.0]);
619        // Halfway to white from (-0.511_605, 1.018_266, -0.310_675), not from (0, 1, 0).
620        assert_color(
621            Color::interpolate(&green, &Color::white(), 0.5, ColorSpace::Rgb),
622            [0.244_197_5, 1.0, 0.344_662_7, 1.0],
623        );
624        // Halfway from darker than black to as light a gray is black.
625        let darker_than_black = Color::parse("color(display-p3 -0.1 -0.1 -0.1)").unwrap();
626        let dark_gray = Color::parse("color(display-p3 0.1 0.1 0.1)").unwrap();
627        for space in [ColorSpace::Hcl, ColorSpace::Lab] {
628            assert_color(Color::interpolate(&darker_than_black, &dark_gray, 0.5, space), [0.0, 0.0, 0.0, 1.0]);
629        }
630    }
631}