Skip to main content

mln_util/
color.rs

1// Note the central quirk, kept on purpose: Color stores a *premultiplied*
2// color, all four channels 0..1. `parse` premultiplies; `to_array` /
3// `stringify` un-premultiply back to 0..255 channels (with alpha rounded to
4// two decimals). A color outside sRGB is clipped to it channel by channel, and
5// keeps its unclipped red, green and blue for interpolation, as the style
6// spec's Color does.
7
8use std::f32::consts::{PI, TAU};
9
10use feature::Value;
11
12use crate::interpolate::interpolate as util_interpolate;
13use crate::string::to_string_double;
14
15mod css;
16
17/// The space a color interpolation runs in: RGB blends the premultiplied
18/// channels, LAB and HCL the 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/// Stores a premultiplied color, with all four channels ranging from 0..1.
30#[derive(Clone, Copy, Debug, Default, PartialEq, mln_wire::Wire)]
31pub struct Color {
32    pub r: f32,
33    pub g: f32,
34    pub b: f32,
35    pub a: f32,
36    /// A color outside sRGB: its straight red, green and blue before `r`, `g`
37    /// and `b` clipped them to 0..1, which interpolation reads (the style
38    /// spec's `unclippedRgb`). `None` inside sRGB.
39    #[wire(skip)]
40    pub unclipped: Option<[f32; 3]>,
41}
42
43// Below these chromas a hue is missing: GL JS's for HCL, which rounds the
44// chroma to four decimals, and CSS Color 4's for OKLCH
45// (https://drafts.csswg.org/css-color-4/#powerless). The conversions give
46// grays a tiny chroma and some hue.
47const HCL_POWERLESS_CHROMA: f32 = 0.000_05;
48const OKLCH_POWERLESS_CHROMA: f64 = 0.000_004;
49
50// Conversions between sRGB, Oklab and Display P3, as the style spec's
51// color_spaces.ts makes them: CSS Color 4's matrices
52// (https://drafts.csswg.org/css-color-4/#color-conversion-code) in f64, and
53// sRGB's transfer function odd about 0, so a color outside sRGB converts
54// with its channels outside 0..1, and back.
55
56type Vector3 = [f64; 3];
57type Matrix3 = [Vector3; 3];
58
59const LINEAR_SRGB_TO_XYZ: Matrix3 = [
60    [506_752.0 / 1_228_815.0, 87_881.0 / 245_763.0, 12_673.0 / 70_218.0],
61    [87_098.0 / 409_605.0, 175_762.0 / 245_763.0, 12_673.0 / 175_545.0],
62    [7_918.0 / 409_605.0, 87_881.0 / 737_289.0, 1_001_167.0 / 1_053_270.0],
63];
64const XYZ_TO_LINEAR_SRGB: Matrix3 = [
65    [12_831.0 / 3_959.0, -329.0 / 214.0, -1_974.0 / 3_959.0],
66    [-851_781.0 / 878_810.0, 1_648_619.0 / 878_810.0, 36_519.0 / 878_810.0],
67    [705.0 / 12_673.0, -2_585.0 / 12_673.0, 705.0 / 667.0],
68];
69const XYZ_TO_LMS: Matrix3 = [
70    [0.819_022_437_996_703, 0.361_906_260_052_890_4, -0.128_873_781_520_987_9],
71    [0.032_983_653_932_388_5, 0.929_286_861_586_343_4, 0.036_144_666_350_642_4],
72    [0.048_177_189_359_624_2, 0.264_239_531_752_730_8, 0.633_547_828_469_430_9],
73];
74const LMS_TO_OKLAB: Matrix3 = [
75    [0.210_454_268_309_314, 0.793_617_774_702_305_4, -0.004_072_043_011_619_3],
76    [1.977_998_532_431_168_4, -2.428_592_242_048_58, 0.450_593_709_617_411],
77    [0.025_904_042_465_547_8, 0.782_771_712_457_529_6, -0.808_675_754_923_077_4],
78];
79const OKLAB_TO_LMS: Matrix3 = [
80    [1.0, 0.396_337_777_376_174_9, 0.215_803_757_309_913_6],
81    [1.0, -0.105_561_345_815_658_6, -0.063_854_172_825_813_3],
82    [1.0, -0.089_484_177_529_811_9, -1.291_485_548_019_409_2],
83];
84const LMS_TO_XYZ: Matrix3 = [
85    [1.226_879_875_845_924_3, -0.557_814_994_460_217_1, 0.281_391_045_665_964_7],
86    [-0.040_575_745_214_800_8, 1.112_286_803_280_317, -0.071_711_058_065_516_4],
87    [-0.076_372_936_674_660_1, -0.421_493_332_402_243_2, 1.586_924_019_836_781_6],
88];
89const LINEAR_DISPLAY_P3_TO_XYZ: Matrix3 = [
90    [608_311.0 / 1_250_200.0, 189_793.0 / 714_400.0, 198_249.0 / 1_000_160.0],
91    [35_783.0 / 156_275.0, 247_089.0 / 357_200.0, 198_249.0 / 2_500_400.0],
92    [0.0, 32_229.0 / 714_400.0, 5_220_557.0 / 5_000_800.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
148// CIE Lab (D50) and its polar form, HCL, as the style spec converts them
149// (https://observablehq.com/@mbostock/lab-and-rgb), with sRGB's transfer
150// function odd about 0 both ways.
151const LAB_XN: f64 = 0.964_22;
152const LAB_YN: f64 = 1.0;
153const LAB_ZN: f64 = 0.825_21;
154const LAB_T0: f64 = 4.0 / 29.0;
155const LAB_T1: f64 = 6.0 / 29.0;
156const LAB_T2: f64 = 3.0 * LAB_T1 * LAB_T1;
157const LAB_T3: f64 = LAB_T1 * LAB_T1 * LAB_T1;
158
159fn xyz_to_lab(t: f64) -> f64 {
160    if t > LAB_T3 { t.powf(1.0 / 3.0) } else { t / LAB_T2 + LAB_T0 }
161}
162
163fn lab_to_xyz(t: f64) -> f64 {
164    if t > LAB_T1 { t * t * t } else { LAB_T2 * (t - LAB_T0) }
165}
166
167/// The style spec's own encoding back to sRGB, whose linear part ends at
168/// 0.00304.
169fn xyz_to_srgb(x: f64) -> f64 {
170    let abs = x.abs();
171    if abs <= 0.003_04 { 12.92 * x } else { (1.055 * abs.powf(1.0 / 2.4) - 0.055).copysign(x) }
172}
173
174fn srgb_to_lab(rgb: Vector3) -> Vector3 {
175    let [r, g, b] = rgb.map(srgb_to_linear);
176    let y = xyz_to_lab((0.222_504_5 * r + 0.716_878_6 * g + 0.060_616_9 * b) / LAB_YN);
177    let (x, z) = if r == g && g == b {
178        (y, y)
179    } else {
180        (
181            xyz_to_lab((0.436_074_7 * r + 0.385_064_9 * g + 0.143_080_4 * b) / LAB_XN),
182            xyz_to_lab((0.013_932_2 * r + 0.097_104_5 * g + 0.714_173_3 * b) / LAB_ZN),
183        )
184    };
185    [116.0 * y - 16.0, 500.0 * (x - y), 200.0 * (y - z)]
186}
187
188fn lab_to_srgb([l, a, b]: Vector3) -> Vector3 {
189    let y = (l + 16.0) / 116.0;
190    let x = if a.is_nan() { y } else { y + a / 500.0 };
191    let z = if b.is_nan() { y } else { y - b / 200.0 };
192    let (x, y, z) = (LAB_XN * lab_to_xyz(x), LAB_YN * lab_to_xyz(y), LAB_ZN * lab_to_xyz(z));
193    [
194        xyz_to_srgb(3.133_856_1 * x - 1.616_866_7 * y - 0.490_614_6 * z),
195        xyz_to_srgb(-0.978_768_4 * x + 1.916_141_5 * y + 0.033_454 * z),
196        xyz_to_srgb(0.071_945_3 * x - 0.228_991_4 * y + 1.405_242_7 * z),
197    ]
198}
199
200/// HCL with its hue in radians, a missing (NaN) hue converting as 0.
201fn hcl_to_srgb(l: f64, c: f64, h: f64) -> Vector3 {
202    let hue = if h.is_nan() { 0.0 } else { h };
203    lab_to_srgb([l, hue.cos() * c, hue.sin() * c])
204}
205
206fn lerp(a: f32, b: f32, t: f32) -> f32 {
207    a * (1.0 - t) + b * t
208}
209
210/// How far `to` is from `from` the shorter way around, in radians.
211fn hue_difference(from: f32, to: f32) -> f32 {
212    let difference = to - from;
213    if difference > PI {
214        difference - TAU
215    } else if difference < -PI {
216        difference + TAU
217    } else {
218        difference
219    }
220}
221
222/// `[l, c, h, alpha]` in the polar form of CIE Lab, the hue in radians, NaN
223/// when it's missing. A color darker than black keeps its lightness below 0.
224fn to_hcl(color: &Color) -> [f32; 4] {
225    let [r, g, b, alpha] = color.straight_rgba();
226    let [l, a, b] = srgb_to_lab([r, g, b].map(f64::from));
227    let c = (a * a + b * b).sqrt() as f32;
228    [l as f32, c, if c < HCL_POWERLESS_CHROMA { f32::NAN } else { b.atan2(a) as f32 }, alpha]
229}
230
231/// The style spec's LAB interpolation: lightness, a, b and alpha, straight.
232fn interpolate_lab(from: &Color, to: &Color, t: f64) -> Color {
233    let [r1, g1, b1, alpha1] = from.straight_rgba().map(f64::from);
234    let [r2, g2, b2, alpha2] = to.straight_rgba().map(f64::from);
235    let (lab1, lab2) = (srgb_to_lab([r1, g1, b1]), srgb_to_lab([r2, g2, b2]));
236    let mix = |a: f64, b: f64| a + t * (b - a);
237    let rgb = lab_to_srgb([mix(lab1[0], lab2[0]), mix(lab1[1], lab2[1]), mix(lab1[2], lab2[2])]);
238    Color::from_straight(rgb, mix(alpha1, alpha2))
239}
240
241/// `[l, a, b, alpha]` in Oklab.
242fn to_oklab(color: &Color) -> [f32; 4] {
243    let [r, g, b, alpha] = color.straight_rgba();
244    let [l, a, b] = srgb_to_oklab([r, g, b].map(f64::from));
245    [l as f32, a as f32, b as f32, alpha]
246}
247
248/// `[l, c, h, alpha]` in Oklch, the hue in radians: NaN, with no chroma, when
249/// it's missing.
250fn to_oklch(color: &Color) -> [f32; 4] {
251    let [r, g, b, alpha] = color.straight_rgba();
252    let [l, a, b] = srgb_to_oklab([r, g, b].map(f64::from));
253    let c = (a * a + b * b).sqrt();
254    if c <= OKLCH_POWERLESS_CHROMA {
255        [l as f32, 0.0, f32::NAN, alpha]
256    } else {
257        [l as f32, c as f32, b.atan2(a) as f32, alpha]
258    }
259}
260
261// GL JS's interpolateHcl: a missing hue takes the other's, and so does the
262// chroma when the other is black or white.
263fn interpolate_hcl(from: &Color, to: &Color, t: f32) -> Color {
264    let [l1, c1, h1, alpha1] = to_hcl(from);
265    let [l2, c2, h2, alpha2] = to_hcl(to);
266    let mut chroma = lerp(c1, c2, t);
267    let hue = match (h1.is_nan(), h2.is_nan()) {
268        (false, false) => h1 + t * hue_difference(h1, h2),
269        (false, true) => {
270            if l2 == 1.0 || l2 == 0.0 {
271                chroma = c1;
272            }
273            h1
274        }
275        (true, false) => {
276            if l1 == 1.0 || l1 == 0.0 {
277                chroma = c2;
278            }
279            h2
280        }
281        (true, true) => f32::NAN,
282    };
283    let rgb = hcl_to_srgb(f64::from(lerp(l1, l2, t)), f64::from(chroma), f64::from(hue));
284    Color::from_straight(rgb, f64::from(lerp(alpha1, alpha2, t)))
285}
286
287// https://drafts.csswg.org/css-color-4/#interpolation: a missing hue takes the
288// other's, and lightness and chroma are premultiplied.
289fn interpolate_oklch(from: &Color, to: &Color, t: f32) -> Color {
290    let [l1, c1, h1, alpha1] = to_oklch(from);
291    let [l2, c2, h2, alpha2] = to_oklch(to);
292    let (h1, h2) = (if h1.is_nan() { h2 } else { h1 }, if h2.is_nan() { h1 } else { h2 });
293    let alpha = lerp(alpha1, alpha2, t);
294    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
295    let rgb = oklch_to_srgb(
296        f64::from(lerp(l1 * alpha1, l2 * alpha2, t) / divisor),
297        f64::from(lerp(c1 * alpha1, c2 * alpha2, t) / divisor),
298        f64::from(h1 + t * hue_difference(h1, h2)),
299    );
300    Color::from_straight(rgb, f64::from(alpha))
301}
302
303// https://drafts.csswg.org/css-color-4/#interpolation: lightness, a and b
304// are premultiplied, and there is no hue to fix up.
305fn interpolate_oklab(from: &Color, to: &Color, t: f32) -> Color {
306    let [l1, a1, b1, alpha1] = to_oklab(from);
307    let [l2, a2, b2, alpha2] = to_oklab(to);
308    let alpha = lerp(alpha1, alpha2, t);
309    let divisor = if alpha == 0.0 { 1.0 } else { alpha };
310    let rgb = oklab_via_oklch_to_srgb(
311        f64::from(lerp(l1 * alpha1, l2 * alpha2, t) / divisor),
312        f64::from(lerp(a1 * alpha1, a2 * alpha2, t) / divisor),
313        f64::from(lerp(b1 * alpha1, b2 * alpha2, t) / divisor),
314    );
315    Color::from_straight(rgb, f64::from(alpha))
316}
317
318/// RGB interpolation, which blends the premultiplied channels, of a color
319/// outside sRGB: its unclipped channels blend.
320fn interpolate_unclipped_rgb(from: &Color, to: &Color, t: f64) -> Color {
321    let [r1, g1, b1, alpha1] = from.straight_rgba().map(f64::from);
322    let [r2, g2, b2, alpha2] = to.straight_rgba().map(f64::from);
323    let alpha = alpha1 * (1.0 - t) + alpha2 * t;
324    if alpha == 0.0 {
325        return Color::new(0.0, 0.0, 0.0, 0.0);
326    }
327    let blend = |c1: f64, c2: f64| (c1 * alpha1 * (1.0 - t) + c2 * alpha2 * t) / alpha;
328    Color::from_straight([blend(r1, r2), blend(g1, g2), blend(b1, b2)], alpha)
329}
330
331impl Color {
332    #[must_use]
333    pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
334        debug_assert!((0.0..=1.0).contains(&r));
335        debug_assert!((0.0..=1.0).contains(&g));
336        debug_assert!((0.0..=1.0).contains(&b));
337        debug_assert!((0.0..=1.0).contains(&a));
338        Color { r, g, b, a, unclipped: None }
339    }
340
341    /// Internal constructor without range asserts (interpolation can
342    /// transiently leave 0..1 in the same way the C++ aggregate init does).
343    #[must_use]
344    pub const fn new_unchecked(r: f32, g: f32, b: f32, a: f32) -> Self {
345        Color { r, g, b, a, unclipped: None }
346    }
347
348    /// A straight color, its channels clipped to 0..1 and premultiplied, and
349    /// kept unclipped when any is outside: the style spec's `new Color(r, g,
350    /// b, alpha, false)`.
351    fn from_straight(rgb: [f64; 3], alpha: f64) -> Color {
352        let a = alpha as f32;
353        let [r, g, b] = rgb.map(|c| c.clamp(0.0, 1.0) as f32);
354        let mut color = Color::new(r * a, g * a, b * a, a);
355        if rgb.iter().any(|c| !(0.0..=1.0).contains(c)) {
356            color.unclipped = Some(rgb.map(|c| c as f32));
357        }
358        color
359    }
360
361    /// The straight color, unclipped (the style spec's `unclippedRgb`).
362    fn straight_rgba(&self) -> [f32; 4] {
363        match self.unclipped {
364            Some([r, g, b]) => [r, g, b, self.a],
365            None if self.a == 0.0 => [0.0; 4],
366            None => [self.r / self.a, self.g / self.a, self.b / self.a, self.a],
367        }
368    }
369
370    #[must_use]
371    pub const fn black() -> Self {
372        Color::new_unchecked(0.0, 0.0, 0.0, 1.0)
373    }
374    #[must_use]
375    pub const fn white() -> Self {
376        Color::new_unchecked(1.0, 1.0, 1.0, 1.0)
377    }
378    #[must_use]
379    pub const fn red() -> Self {
380        Color::new_unchecked(1.0, 0.0, 0.0, 1.0)
381    }
382    #[must_use]
383    pub const fn green() -> Self {
384        Color::new_unchecked(0.0, 1.0, 0.0, 1.0)
385    }
386    #[must_use]
387    pub const fn blue() -> Self {
388        Color::new_unchecked(0.0, 0.0, 1.0, 1.0)
389    }
390
391    /// Parse a CSS color string as the style spec does, returning a
392    /// premultiplied Color. Unlike the C++ core, it keeps the channels'
393    /// precision rather than rounding them to 8 bits.
394    #[must_use]
395    pub fn parse(s: &str) -> Option<Color> {
396        let (rgb, alpha) = css::parse(s)?;
397        Some(Color::from_straight(rgb, alpha))
398    }
399
400    /// The straight `[r, g, b, a]` of a CSS color string, as the style spec
401    /// parses it: red, green and blue are 0..1 inside sRGB and unclipped
402    /// outside it.
403    #[must_use]
404    pub fn parse_straight(s: &str) -> Option<[f64; 4]> {
405        let ([r, g, b], alpha) = css::parse(s)?;
406        Some([r, g, b, alpha])
407    }
408
409    #[must_use]
410    pub fn interpolate(from: &Color, to: &Color, t: f64, space: ColorSpace) -> Color {
411        match space {
412            ColorSpace::Rgb if from.unclipped.is_some() || to.unclipped.is_some() => {
413                interpolate_unclipped_rgb(from, to, t)
414            }
415            ColorSpace::Rgb => util_interpolate(from, to, t),
416            ColorSpace::Lab => interpolate_lab(from, to, t),
417            ColorSpace::Hcl => interpolate_hcl(from, to, t as f32),
418            ColorSpace::Oklch => interpolate_oklch(from, to, t as f32),
419            ColorSpace::Oklab => interpolate_oklab(from, to, t as f32),
420        }
421    }
422
423    /// Un-premultiplied `[r*255, g*255, b*255, a]`.
424    #[must_use]
425    pub fn to_array(&self) -> [f64; 4] {
426        if self.a == 0.0 {
427            [0.0, 0.0, 0.0, 0.0]
428        } else {
429            [
430                // r * 255 / a: float arithmetic, promoted afterwards.
431                f64::from(self.r * 255.0f32 / self.a),
432                f64::from(self.g * 255.0f32 / self.a),
433                f64::from(self.b * 255.0f32 / self.a),
434                f64::from(self.a),
435            ]
436        }
437    }
438
439    /// Port-only: `to_array` in double precision and without rounding alpha.
440    fn exact_array(&self) -> [f64; 4] {
441        let a = f64::from(self.a);
442        let channel = |c: f32| (f64::from(c) / a * 255.0).clamp(0.0, 255.0);
443        [channel(self.r), channel(self.g), channel(self.b), a]
444    }
445
446    /// Whether the "rgba" expression of these values makes this color: the
447    /// premultiplication of `mln_style`'s `rgba` expression.
448    fn is_made_by(&self, [r, g, b, a]: [f64; 4]) -> bool {
449        let premultiplied = |c: f64| (c / 255.0 * a) as f32;
450        premultiplied(r) == self.r && premultiplied(g) == self.g && premultiplied(b) == self.b && a as f32 == self.a
451    }
452
453    #[must_use]
454    pub fn to_float_array(&self) -> [f32; 4] {
455        [self.r, self.g, self.b, self.a]
456    }
457
458    #[must_use]
459    pub fn stringify(&self) -> String {
460        // Match GL JS's Color.toString: whole channels, alpha as is.
461        let array = self.to_array();
462        let channel = |value: f64| to_string_double((value + 0.5).floor());
463        format!(
464            "rgba({},{},{},{})",
465            channel(array[0]),
466            channel(array[1]),
467            channel(array[2]),
468            to_string_double(array[3])
469        )
470    }
471
472    /// Emit as an rgba expression array for expression serialization (avoids
473    /// "Bare objects invalid" parse errors in expression round trips).
474    ///
475    /// Port-only: when the C++ values (`to_array`) don't make this color
476    /// again (the "rgba" expression premultiplies them back), it writes
477    /// values that do. `to_array` divides in float, so a serialized layer
478    /// could parse back to slightly other colors, and a tile worker in
479    /// another wasm instance, which gets its layers that way, would write
480    /// other colors into its buckets.
481    #[must_use]
482    pub fn serialize(&self) -> Value {
483        let mut array = self.to_array();
484        if !self.is_made_by(array) {
485            let exact = self.exact_array();
486            if self.is_made_by(exact) {
487                array = exact;
488            }
489        }
490        Value::Array(vec![
491            Value::String("rgba".to_owned()),
492            Value::Double(array[0]),
493            Value::Double(array[1]),
494            Value::Double(array[2]),
495            Value::Double(array[3]),
496        ])
497    }
498}
499
500impl std::ops::Mul<f32> for Color {
501    type Output = Color;
502    fn mul(self, alpha: f32) -> Color {
503        debug_assert!((0.0..=1.0).contains(&alpha));
504        // The straight color, and so its unclipped channels, stay as they are.
505        Color { r: self.r * alpha, g: self.g * alpha, b: self.b * alpha, a: self.a * alpha, ..self }
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    // Ports (a subset of) test/util/color.test.cpp — extend when porting the
512    // full file.
513    use super::*;
514
515    #[test]
516    fn parse_named() {
517        assert_eq!(Color::parse("red"), Some(Color::red()));
518        assert_eq!(Color::parse("white"), Some(Color::white()));
519        assert_eq!(Color::parse("not-a-color"), None);
520    }
521
522    #[test]
523    fn parse_premultiplies() {
524        let c = Color::parse("rgba(255, 0, 0, 0.5)").unwrap();
525        assert!((c.r - 0.5).abs() < 1e-6);
526        assert_eq!(c.g, 0.0);
527        assert_eq!(c.b, 0.0);
528        assert!((c.a - 0.5).abs() < 1e-6);
529    }
530
531    #[test]
532    fn roundtrip_array() {
533        let c = Color::parse("rgba(255, 51, 0, 1)").unwrap();
534        let a = c.to_array();
535        assert!((a[0] - 255.0).abs() < 1e-3);
536        assert!((a[1] - 51.0).abs() < 1e-3);
537        assert!((a[2] - 0.0).abs() < 1e-3);
538        assert_eq!(a[3], 1.0);
539    }
540
541    #[test]
542    fn interpolate_rgb_midpoint() {
543        let c = Color::interpolate(&Color::black(), &Color::white(), 0.5, ColorSpace::Rgb);
544        assert!((c.r - 0.5).abs() < 1e-6);
545        assert!((c.a - 1.0).abs() < 1e-6);
546    }
547
548    fn serialized(c: &Color) -> [f64; 4] {
549        let Value::Array(a) = c.serialize() else { panic!("not an array") };
550        let n = |v: &Value| match v {
551            Value::Double(d) => *d,
552            _ => panic!("not a number"),
553        };
554        [n(&a[1]), n(&a[2]), n(&a[3]), n(&a[4])]
555    }
556
557    /// Port-only: what `serialize` writes makes the same color again,
558    /// premultiplied as the "rgba" expression does; and it is the C++
559    /// `to_array` when that does.
560    #[test]
561    fn serialize_makes_the_same_color() {
562        for css in ["red", "rgba(255, 0, 0, 0.5)", "rgba(170, 255, 0, 0.6)", "rgba(1, 2, 3, 0.678)", "#123456"] {
563            let c = Color::parse(css).unwrap();
564            let [r, g, b, a] = serialized(&c);
565            let premultiplied = |v: f64| (v / 255.0 * a) as f32;
566            assert_eq!((premultiplied(r), premultiplied(g), premultiplied(b), a as f32), (c.r, c.g, c.b, c.a), "{css}");
567        }
568        assert_eq!(serialized(&Color::parse("rgba(255, 0, 0, 0.5)").unwrap()), [255.0, 0.0, 0.0, 0.5]);
569        assert_eq!(serialized(&Color::parse("rgba(1, 2, 3, 0.678)").unwrap())[3], f64::from(0.678f32));
570    }
571}