use crate::{Color, Theme};
use std::collections::HashMap;
use std::f64::consts::PI;
use std::sync::OnceLock;
pub const GOOGLE_BLUE: Color = Color(0x1b, 0x6e, 0xf3, 255);
const MIN_CHROMA: f64 = 5.0;
const ACCENT1_CHROMA: f64 = 48.0;
const MIDDLE_LSTAR: f64 = 49.6;
const MAX_EXTRACTION_AREA: f64 = 112.0 * 112.0;
pub const BASIC_COLOR_SEEDS: [(&str, Color); 16] = [
("Google Blue", Color(0x1b, 0x6e, 0xf3, 255)),
("Sky Blue", Color(0x00, 0x67, 0x83, 255)),
("Ocean Teal", Color(0x00, 0x6a, 0x6a, 255)),
("Mint Green", Color(0x14, 0x6c, 0x2e, 255)),
("Sage Green", Color(0x38, 0x6a, 0x20, 255)),
("Lime Olive", Color(0x5b, 0x63, 0x00, 255)),
("Amber Gold", Color(0x78, 0x59, 0x00, 255)),
("Warm Terracotta", Color(0x98, 0x47, 0x16, 255)),
("Coral Red", Color(0xb3, 0x26, 0x1e, 255)),
("Rose Pink", Color(0x98, 0x40, 0x61, 255)),
("Orchid Magenta", Color(0x8e, 0x43, 0x7f, 255)),
("Berry Plum", Color(0x7b, 0x49, 0x97, 255)),
("Lavender Purple", Color(0x67, 0x50, 0xa4, 255)),
("Deep Indigo", Color(0x43, 0x55, 0xb9, 255)),
("Periwinkle", Color(0x3a, 0x60, 0x8f, 255)),
("Cool Slate", Color(0x4d, 0x61, 0x6c, 255)),
];
const WHITE_POINT_D65: [f64; 3] = [95.047, 100.0, 108.883];
const XYZ_TO_CAM16RGB: [[f64; 3]; 3] = [
[0.401288, 0.650173, -0.051461],
[-0.250268, 1.204414, 0.045854],
[-0.002079, 0.048952, 0.953127],
];
const SCALED_DISCOUNT_FROM_LINRGB: [[f64; 3]; 3] = [
[0.001200833568784504, 0.002389694492170889, 0.0002795742885861124],
[0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398],
[0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076],
];
const LINRGB_FROM_SCALED_DISCOUNT: [[f64; 3]; 3] = [
[1373.2198709594231, -1100.4251190754821, -7.278681089101213],
[-271.815969077903, 559.6580465940733, -32.46047482791194],
[1.9622899599665666, -57.173814538844006, 308.7233197812385],
];
const Y_FROM_LINRGB: [f64; 3] = [0.2126, 0.7152, 0.0722];
#[derive(Clone, Copy, Debug)]
struct ViewingConditions {
aw: f64,
nbb: f64,
ncb: f64,
c: f64,
nc: f64,
n: f64,
rgb_d: [f64; 3],
fl: f64,
z: f64,
}
fn default_viewing_conditions() -> &'static ViewingConditions {
static DEFAULT: OnceLock<ViewingConditions> = OnceLock::new();
DEFAULT.get_or_init(|| {
let wp = WHITE_POINT_D65;
let adapting_luminance = (200.0 / PI) * y_from_lstar(50.0) / 100.0;
let background_lstar = 50.0;
let surround = 2.0;
let rw = wp[0] * XYZ_TO_CAM16RGB[0][0] + wp[1] * XYZ_TO_CAM16RGB[0][1] + wp[2] * XYZ_TO_CAM16RGB[0][2];
let gw = wp[0] * XYZ_TO_CAM16RGB[1][0] + wp[1] * XYZ_TO_CAM16RGB[1][1] + wp[2] * XYZ_TO_CAM16RGB[1][2];
let bw = wp[0] * XYZ_TO_CAM16RGB[2][0] + wp[1] * XYZ_TO_CAM16RGB[2][1] + wp[2] * XYZ_TO_CAM16RGB[2][2];
let f = 0.8 + surround / 10.0;
let c = 0.59 + (0.69 - 0.59) * ((f - 0.9) * 10.0);
let d = (f * (1.0 - (1.0 / 3.6) * ((-adapting_luminance - 42.0) / 92.0).exp())).clamp(0.0, 1.0);
let nc = f;
let rgb_d = [
d * (100.0 / rw) + 1.0 - d,
d * (100.0 / gw) + 1.0 - d,
d * (100.0 / bw) + 1.0 - d,
];
let k = 1.0 / (5.0 * adapting_luminance + 1.0);
let k4 = k * k * k * k;
let k4f = 1.0 - k4;
let fl = k4 * adapting_luminance + 0.1 * k4f * k4f * (5.0 * adapting_luminance).cbrt();
let n = y_from_lstar(background_lstar) / wp[1];
let z = 1.48 + n.sqrt();
let nbb = 0.725 / n.powf(0.2);
let ncb = nbb;
let raf = [
(fl * rgb_d[0] * rw / 100.0).powf(0.42),
(fl * rgb_d[1] * gw / 100.0).powf(0.42),
(fl * rgb_d[2] * bw / 100.0).powf(0.42),
];
let ra = [
400.0 * raf[0] / (raf[0] + 27.13),
400.0 * raf[1] / (raf[1] + 27.13),
400.0 * raf[2] / (raf[2] + 27.13),
];
let aw = (2.0 * ra[0] + ra[1] + 0.05 * ra[2]) * nbb;
ViewingConditions {
aw,
nbb,
ncb,
c,
nc,
n,
rgb_d,
fl,
z,
}
})
}
#[inline]
fn linearized_f64(channel: f64) -> f64 {
let normalized = channel / 255.0;
if normalized <= 0.040449936 {
normalized / 12.92 * 100.0
} else {
((normalized + 0.055) / 1.055).powf(2.4) * 100.0
}
}
#[inline]
fn linearized(channel: u8) -> f64 {
linearized_f64(channel as f64)
}
#[inline]
fn true_delinearized(rgb_component: f64) -> f64 {
let normalized = rgb_component / 100.0;
let d = if normalized <= 0.0031308 {
normalized * 12.92
} else {
1.055 * normalized.powf(1.0 / 2.4) - 0.055
};
d * 255.0
}
#[inline]
fn delinearized(rgb_component: f64) -> u8 {
true_delinearized(rgb_component).round().clamp(0.0, 255.0) as u8
}
#[inline]
fn lab_f(t: f64) -> f64 {
const E: f64 = 216.0 / 24389.0;
const KAPPA: f64 = 24389.0 / 27.0;
if t > E {
t.cbrt()
} else {
(KAPPA * t + 16.0) / 116.0
}
}
#[inline]
fn lab_invf(ft: f64) -> f64 {
const E: f64 = 216.0 / 24389.0;
const KAPPA: f64 = 24389.0 / 27.0;
let ft3 = ft * ft * ft;
if ft3 > E {
ft3
} else {
(116.0 * ft - 16.0) / KAPPA
}
}
pub fn y_from_lstar(lstar: f64) -> f64 {
100.0 * lab_invf((lstar + 16.0) / 116.0)
}
pub fn lstar_from_rgb(color: Color) -> f64 {
let rl = linearized(color.0);
let gl = linearized(color.1);
let bl = linearized(color.2);
let y = 0.2126 * rl + 0.7152 * gl + 0.0722 * bl;
116.0 * lab_f(y / 100.0) - 16.0
}
#[inline]
fn color_from_lstar(lstar: f64) -> Color {
let y = y_from_lstar(lstar.clamp(0.0, 100.0));
let c = delinearized(y);
Color(c, c, c, 255)
}
#[inline]
fn color_from_linrgb(linrgb: [f64; 3]) -> Color {
Color(
delinearized(linrgb[0]),
delinearized(linrgb[1]),
delinearized(linrgb[2]),
255,
)
}
pub fn hct_from_rgb(color: Color) -> (f64, f64, f64) {
let vc = default_viewing_conditions();
let rl = linearized(color.0);
let gl = linearized(color.1);
let bl = linearized(color.2);
let x = 0.41233895 * rl + 0.35762064 * gl + 0.18051042 * bl;
let y = 0.2126 * rl + 0.7152 * gl + 0.0722 * bl;
let z = 0.01932141 * rl + 0.11916382 * gl + 0.95034478 * bl;
let rt = x * XYZ_TO_CAM16RGB[0][0] + y * XYZ_TO_CAM16RGB[0][1] + z * XYZ_TO_CAM16RGB[0][2];
let gt = x * XYZ_TO_CAM16RGB[1][0] + y * XYZ_TO_CAM16RGB[1][1] + z * XYZ_TO_CAM16RGB[1][2];
let bt = x * XYZ_TO_CAM16RGB[2][0] + y * XYZ_TO_CAM16RGB[2][1] + z * XYZ_TO_CAM16RGB[2][2];
let rd = vc.rgb_d[0] * rt;
let gd = vc.rgb_d[1] * gt;
let bd = vc.rgb_d[2] * bt;
let raf = (vc.fl * rd.abs() / 100.0).powf(0.42);
let gaf = (vc.fl * gd.abs() / 100.0).powf(0.42);
let baf = (vc.fl * bd.abs() / 100.0).powf(0.42);
let ra = signum_zero(rd) * 400.0 * raf / (raf + 27.13);
let ga = signum_zero(gd) * 400.0 * gaf / (gaf + 27.13);
let ba = signum_zero(bd) * 400.0 * baf / (baf + 27.13);
let a = (11.0 * ra - 12.0 * ga + ba) / 11.0;
let b = (ra + ga - 2.0 * ba) / 9.0;
let u = (20.0 * ra + 20.0 * ga + 21.0 * ba) / 20.0;
let p2 = (40.0 * ra + 20.0 * ga + ba) / 20.0;
let atan_deg = b.atan2(a).to_degrees();
let hue = wrap_degrees(atan_deg);
let ac = p2 * vc.nbb;
let j = if ac <= 0.0 {
0.0
} else {
100.0 * (ac / vc.aw).powf(vc.c * vc.z)
};
let hue_prime = if hue < 20.14 { hue + 360.0 } else { hue };
let e_hue = 0.25 * ((hue_prime.to_radians() + 2.0).cos() + 3.8);
let p1 = (50000.0 / 13.0) * e_hue * vc.nc * vc.ncb;
let t = p1 * a.hypot(b) / (u + 0.305);
let alpha = (1.64 - 0.29_f64.powf(vc.n)).powf(0.73) * t.powf(0.9);
let chroma = alpha * (j / 100.0).sqrt();
let tone = 116.0 * lab_f(y / 100.0) - 16.0;
(hue, chroma, tone)
}
#[inline]
fn signum_zero(x: f64) -> f64 {
if x < 0.0 {
-1.0
} else if x > 0.0 {
1.0
} else {
0.0
}
}
#[inline]
fn mat_mul(v: [f64; 3], m: [[f64; 3]; 3]) -> [f64; 3] {
[
v[0] * m[0][0] + v[1] * m[0][1] + v[2] * m[0][2],
v[0] * m[1][0] + v[1] * m[1][1] + v[2] * m[1][2],
v[0] * m[2][0] + v[1] * m[2][1] + v[2] * m[2][2],
]
}
#[inline]
fn sanitize_radians(angle: f64) -> f64 {
(angle + PI * 8.0).rem_euclid(PI * 2.0)
}
#[inline]
fn are_in_cyclic_order(a: f64, b: f64, c: f64) -> bool {
sanitize_radians(b - a) < sanitize_radians(c - a)
}
#[inline]
fn chromatic_adaptation(component: f64) -> f64 {
let af = component.abs().powf(0.42);
signum_zero(component) * 400.0 * af / (af + 27.13)
}
#[inline]
fn inverse_chromatic_adaptation(adapted: f64) -> f64 {
let abs = adapted.abs();
let base = (27.13 * abs / (400.0 - abs).max(1e-12)).max(0.0);
signum_zero(adapted) * base.powf(1.0 / 0.42)
}
fn hue_of_linrgb(linrgb: [f64; 3]) -> f64 {
let scaled = mat_mul(linrgb, SCALED_DISCOUNT_FROM_LINRGB);
let ra = chromatic_adaptation(scaled[0]);
let ga = chromatic_adaptation(scaled[1]);
let ba = chromatic_adaptation(scaled[2]);
let a = (11.0 * ra - 12.0 * ga + ba) / 11.0;
let b = (ra + ga - 2.0 * ba) / 9.0;
b.atan2(a)
}
fn nth_vertex(y: f64, n: usize) -> Option<[f64; 3]> {
let [kr, kg, kb] = Y_FROM_LINRGB;
let coord_a = if n % 4 <= 1 { 0.0 } else { 100.0 };
let coord_b = if n.is_multiple_of(2) { 0.0 } else { 100.0 };
let (r, g, b) = if n < 4 {
let (g, b) = (coord_a, coord_b);
((y - g * kg - b * kb) / kr, g, b)
} else if n < 8 {
let (b, r) = (coord_a, coord_b);
(r, (y - r * kr - b * kb) / kg, b)
} else {
let (r, g) = (coord_a, coord_b);
(r, g, (y - r * kr - g * kg) / kb)
};
if (0.0..=100.0).contains(&r) && (0.0..=100.0).contains(&g) && (0.0..=100.0).contains(&b) {
Some([r, g, b])
} else {
None
}
}
fn bisect_to_segment(y: f64, target_hue: f64) -> ([f64; 3], [f64; 3]) {
let mut left = [-1.0; 3];
let mut right = [-1.0; 3];
let mut left_hue = 0.0;
let mut right_hue = 0.0;
let mut initialized = false;
let mut uncut = true;
for n in 0..12 {
let Some(mid) = nth_vertex(y, n) else {
continue;
};
let mid_hue = hue_of_linrgb(mid);
if !initialized {
left = mid;
right = mid;
left_hue = mid_hue;
right_hue = mid_hue;
initialized = true;
continue;
}
if uncut || are_in_cyclic_order(left_hue, mid_hue, right_hue) {
uncut = false;
if are_in_cyclic_order(left_hue, target_hue, mid_hue) {
right = mid;
right_hue = mid_hue;
} else {
left = mid;
left_hue = mid_hue;
}
}
}
(left, right)
}
fn set_coordinate(source: [f64; 3], coordinate: f64, target: [f64; 3], axis: usize) -> [f64; 3] {
let t = (coordinate - source[axis]) / (target[axis] - source[axis]);
[
source[0] + (target[0] - source[0]) * t,
source[1] + (target[1] - source[1]) * t,
source[2] + (target[2] - source[2]) * t,
]
}
fn bisect_to_limit(y: f64, target_hue: f64) -> [f64; 3] {
let (mut left, mut right) = bisect_to_segment(y, target_hue);
let mut left_hue = hue_of_linrgb(left);
for axis in 0..3 {
if left[axis] != right[axis] {
let (mut l_plane, mut r_plane) = if left[axis] < right[axis] {
(
(true_delinearized(left[axis]) - 0.5).floor() as i32,
(true_delinearized(right[axis]) - 0.5).ceil() as i32,
)
} else {
(
(true_delinearized(left[axis]) - 0.5).ceil() as i32,
(true_delinearized(right[axis]) - 0.5).floor() as i32,
)
};
for _ in 0..8 {
if (r_plane - l_plane).abs() <= 1 {
break;
}
let m_plane = ((l_plane + r_plane) as f64 / 2.0).floor() as i32;
let mid_coord = linearized_f64(m_plane as f64 + 0.5);
let mid = set_coordinate(left, mid_coord, right, axis);
let mid_hue = hue_of_linrgb(mid);
if are_in_cyclic_order(left_hue, target_hue, mid_hue) {
right = mid;
r_plane = m_plane;
} else {
left = mid;
left_hue = mid_hue;
l_plane = m_plane;
}
}
}
}
[
(left[0] + right[0]) * 0.5,
(left[1] + right[1]) * 0.5,
(left[2] + right[2]) * 0.5,
]
}
fn find_result_by_j(hue_rad: f64, chroma: f64, y: f64) -> Option<Color> {
let vc = default_viewing_conditions();
let mut j = y.sqrt() * 11.0;
let t_inner_coeff = 1.0 / (1.64 - 0.29_f64.powf(vc.n)).powf(0.73);
let e_hue = 0.25 * ((hue_rad + 2.0).cos() + 3.8);
let p1 = e_hue * (50000.0 / 13.0) * vc.nc * vc.ncb;
let h_sin = hue_rad.sin();
let h_cos = hue_rad.cos();
for round in 0..5 {
let j_norm = j / 100.0;
let alpha = if chroma == 0.0 || j <= 0.0 {
0.0
} else {
chroma / j_norm.sqrt()
};
let t = (alpha * t_inner_coeff).powf(1.0 / 0.9);
let ac = vc.aw * j_norm.powf(1.0 / vc.c / vc.z);
let p2 = ac / vc.nbb;
let gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11.0 * t * h_cos + 108.0 * t * h_sin);
let a = gamma * h_cos;
let b = gamma * h_sin;
let ra = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0;
let ga = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0;
let ba = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0;
let linrgb = mat_mul(
[
inverse_chromatic_adaptation(ra),
inverse_chromatic_adaptation(ga),
inverse_chromatic_adaptation(ba),
],
LINRGB_FROM_SCALED_DISCOUNT,
);
if linrgb[0] < 0.0 || linrgb[1] < 0.0 || linrgb[2] < 0.0 {
return None;
}
let fnj = Y_FROM_LINRGB[0] * linrgb[0]
+ Y_FROM_LINRGB[1] * linrgb[1]
+ Y_FROM_LINRGB[2] * linrgb[2];
if fnj <= 0.0 {
return None;
}
if round == 4 || (fnj - y).abs() < 0.002 {
if linrgb[0] > 100.01 || linrgb[1] > 100.01 || linrgb[2] > 100.01 {
return None;
}
return Some(color_from_linrgb(linrgb));
}
j -= (fnj - y) * j / (2.0 * fnj);
}
None
}
pub fn rgb_from_hct(hue: f64, chroma: f64, tone: f64) -> Color {
let tone = if tone.is_finite() {
tone.clamp(0.0, 100.0)
} else {
50.0
};
let chroma = if chroma.is_finite() {
chroma.max(0.0)
} else {
0.0
};
if chroma < 0.0001 || tone < 0.0001 || tone > 99.9999 {
return color_from_lstar(tone);
}
let hue_deg = wrap_degrees(if hue.is_finite() { hue } else { 0.0 });
let hue_rad = hue_deg.to_radians();
let y = y_from_lstar(tone);
if let Some(exact) = find_result_by_j(hue_rad, chroma, y) {
return exact;
}
let linrgb = bisect_to_limit(y, hue_rad);
if linrgb[0] < 0.0 {
color_from_lstar(tone)
} else {
color_from_linrgb(linrgb)
}
}
#[inline]
fn wrap_degrees(deg: f64) -> f64 {
let r = deg.rem_euclid(360.0);
if r >= 360.0 { 0.0 } else { r }
}
#[inline]
fn wrap_degrees_i32(deg: i32) -> usize {
deg.rem_euclid(360) as usize
}
#[inline]
fn hue_diff(a: f64, b: f64) -> f64 {
180.0 - ((a - b).abs() - 180.0).abs()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MonetStyle {
#[default]
TonalSpot,
Spritz,
Vibrant,
Expressive,
Rainbow,
FruitSalad,
Content,
}
#[derive(Clone, Copy)]
enum HueSpec {
Source,
Add(f64),
Subtract(f64),
Table(&'static [(i32, i32)]),
}
#[derive(Clone, Copy)]
enum ChromaSpec {
Constant(f64),
MaxOut,
Source,
Multiple(f64),
}
const VIBRANT_SECONDARY_ROTATIONS: &[(i32, i32)] = &[
(0, 18), (41, 15), (61, 10), (101, 12), (131, 15), (181, 18), (251, 15), (301, 12), (360, 12),
];
const VIBRANT_TERTIARY_ROTATIONS: &[(i32, i32)] = &[
(0, 35), (41, 30), (61, 20), (101, 25), (131, 30), (181, 35), (251, 30), (301, 25), (360, 25),
];
const EXPRESSIVE_SECONDARY_ROTATIONS: &[(i32, i32)] = &[
(0, 45), (21, 95), (51, 45), (121, 20), (151, 45), (191, 90), (271, 45), (321, 45), (360, 45),
];
const EXPRESSIVE_TERTIARY_ROTATIONS: &[(i32, i32)] = &[
(0, 120), (21, 120), (51, 20), (121, 45), (151, 20), (191, 15), (271, 20), (321, 120), (360, 120),
];
impl HueSpec {
fn resolve(self, source_hue: f64) -> f64 {
match self {
Self::Source => wrap_degrees(source_hue),
Self::Add(delta) => wrap_degrees(source_hue + delta),
Self::Subtract(delta) => wrap_degrees(source_hue - delta),
Self::Table(table) => {
let sanitized = if !(0.0..360.0).contains(&source_hue) {
0.0
} else {
source_hue
};
for w in table.windows(2) {
let lo = w[0].0 as f64;
let hi = w[1].0 as f64;
if lo <= sanitized && sanitized < hi {
return wrap_degrees(sanitized + w[0].1 as f64);
}
}
wrap_degrees(source_hue)
}
}
}
}
impl ChromaSpec {
fn resolve(self, source_chroma: f64) -> f64 {
match self {
Self::Constant(c) => c,
Self::MaxOut => 130.0,
Self::Source => source_chroma,
Self::Multiple(m) => source_chroma * m,
}
}
}
impl MonetStyle {
fn core_specs(self) -> [(HueSpec, ChromaSpec); 5] {
use ChromaSpec as C;
use HueSpec as H;
match self {
Self::Spritz => [
(H::Source, C::Constant(12.0)),
(H::Source, C::Constant(8.0)),
(H::Source, C::Constant(16.0)),
(H::Source, C::Constant(2.0)),
(H::Source, C::Constant(2.0)),
],
Self::TonalSpot => [
(H::Source, C::Constant(36.0)),
(H::Source, C::Constant(16.0)),
(H::Add(60.0), C::Constant(24.0)),
(H::Source, C::Constant(4.0)),
(H::Source, C::Constant(8.0)),
],
Self::Vibrant => [
(H::Source, C::MaxOut),
(H::Table(VIBRANT_SECONDARY_ROTATIONS), C::Constant(24.0)),
(H::Table(VIBRANT_TERTIARY_ROTATIONS), C::Constant(32.0)),
(H::Source, C::Constant(10.0)),
(H::Source, C::Constant(12.0)),
],
Self::Expressive => [
(H::Add(240.0), C::Constant(40.0)),
(H::Table(EXPRESSIVE_SECONDARY_ROTATIONS), C::Constant(24.0)),
(H::Table(EXPRESSIVE_TERTIARY_ROTATIONS), C::Constant(32.0)),
(H::Add(15.0), C::Constant(8.0)),
(H::Add(15.0), C::Constant(12.0)),
],
Self::Rainbow => [
(H::Source, C::Constant(48.0)),
(H::Source, C::Constant(16.0)),
(H::Add(60.0), C::Constant(24.0)),
(H::Source, C::Constant(0.0)),
(H::Source, C::Constant(0.0)),
],
Self::FruitSalad => [
(H::Subtract(50.0), C::Constant(48.0)),
(H::Subtract(50.0), C::Constant(36.0)),
(H::Source, C::Constant(36.0)),
(H::Source, C::Constant(10.0)),
(H::Source, C::Constant(16.0)),
],
Self::Content => [
(H::Source, C::Source),
(H::Source, C::Multiple(0.33)),
(H::Source, C::Multiple(0.66)),
(H::Source, C::Multiple(0.0833)),
(H::Source, C::Multiple(0.1666)),
],
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TonalPalette {
hue: f64,
chroma: f64,
shades: [Color; 13],
}
impl TonalPalette {
pub const TONES: [u8; 13] = [100, 99, 95, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0];
pub fn new(hue: f64, chroma: f64) -> Self {
let hue = wrap_degrees(hue);
let chroma = chroma.max(0.0);
let shades = std::array::from_fn(|idx| {
let t = Self::TONES[idx];
Self::compute_tone(hue, chroma, t)
});
Self {
hue,
chroma,
shades,
}
}
fn compute_tone(hue: f64, chroma: f64, t: u8) -> Color {
match t {
100 => Color(255, 255, 255, 255),
0 => Color(0, 0, 0, 255),
99 | 95 => rgb_from_hct(hue, chroma.min(40.0), t as f64),
50 => rgb_from_hct(hue, chroma, MIDDLE_LSTAR),
other => {
let capped = if other >= 95 { chroma.min(40.0) } else { chroma };
rgb_from_hct(hue, capped, other.min(100) as f64)
}
}
}
pub fn tone(&self, t: u8) -> Color {
match t {
100 => self.shades[0],
99 => self.shades[1],
95 => self.shades[2],
90 => self.shades[3],
80 => self.shades[4],
70 => self.shades[5],
60 => self.shades[6],
50 => self.shades[7],
40 => self.shades[8],
30 => self.shades[9],
20 => self.shades[10],
10 => self.shades[11],
0 => self.shades[12],
other => Self::compute_tone(self.hue, self.chroma, other),
}
}
pub fn shades(&self) -> &[Color; 13] {
&self.shades
}
pub fn hue(&self) -> f64 {
self.hue
}
pub fn chroma(&self) -> f64 {
self.chroma
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WallpaperColors {
pub primary: Color,
pub secondary: Option<Color>,
pub tertiary: Option<Color>,
pub seeds: Vec<Color>,
pub supports_dark_text: bool,
pub supports_dark_theme: bool,
}
impl WallpaperColors {
pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Self {
let Some(expected_len) = (width as usize)
.checked_mul(height as usize)
.and_then(|px| px.checked_mul(4))
else {
return Self::fallback();
};
if width == 0 || height == 0 || rgba.len() < expected_len {
return Self::fallback();
}
let w = width as usize;
let h = height as usize;
let area = (w as f64) * (h as f64);
let scale = if area > MAX_EXTRACTION_AREA {
(MAX_EXTRACTION_AREA / area).sqrt()
} else {
1.0
};
let sw = ((w as f64 * scale).round() as usize).clamp(1, w);
let sh = ((h as f64 * scale).round() as usize).clamp(1, h);
let mut buckets: HashMap<u16, (u32, u64, u64, u64)> = HashMap::with_capacity(256);
let mut total_luminance = 0.0_f64;
let mut dark_pixels = 0usize;
let total_samples = sw * sh;
let mut opaque_samples = 0u32;
for sy in 0..sh {
let y = (sy * h) / sh;
let row_base = y * w;
for sx in 0..sw {
let x = (sx * w) / sw;
let idx = (row_base + x) * 4;
let r = rgba[idx];
let g = rgba[idx + 1];
let b = rgba[idx + 2];
let a = rgba[idx + 3];
let lum = (0.2126 * linearized(r) + 0.7152 * linearized(g) + 0.0722 * linearized(b))
/ 100.0;
total_luminance += lum;
let contrast_black = (lum + 0.05) / 0.05;
if contrast_black <= 5.5 && a != 0 {
dark_pixels += 1;
}
if a > 0 {
opaque_samples += 1;
let key = (((r as u16) >> 3) << 10)
| (((g as u16) >> 3) << 5)
| ((b as u16) >> 3);
let entry = buckets.entry(key).or_insert((0, 0, 0, 0));
entry.0 += 1;
entry.1 += r as u64;
entry.2 += g as u64;
entry.3 += b as u64;
}
}
}
let mean_luminance = total_luminance / total_samples.max(1) as f64;
let max_dark_pixels = (total_samples as f64 * 0.05) as usize;
let supports_dark_text = mean_luminance > 0.7 && dark_pixels < max_dark_pixels;
let supports_dark_theme = mean_luminance < 0.3;
if opaque_samples == 0 || buckets.is_empty() {
return Self {
primary: GOOGLE_BLUE,
secondary: None,
tertiary: None,
seeds: vec![GOOGLE_BLUE],
supports_dark_text,
supports_dark_theme,
};
}
let mut clusters: Vec<(Color, u32)> = buckets
.into_values()
.map(|(count, sr, sg, sb)| {
let c = count as u64;
(
Color(
((sr + c / 2) / c) as u8,
((sg + c / 2) / c) as u8,
((sb + c / 2) / c) as u8,
255,
),
count,
)
})
.collect();
clusters.sort_by(|a, b| {
b.1.cmp(&a.1)
.then_with(|| (a.0.0, a.0.1, a.0.2).cmp(&(b.0.0, b.0.1, b.0.2)))
});
clusters.truncate(256);
let total_pop: f64 = clusters.iter().map(|(_, p)| *p as f64).sum();
struct Entry {
color: Color,
proportion: f64,
hue: f64,
chroma: f64,
}
let entries: Vec<Entry> = clusters
.into_iter()
.map(|(color, pop)| {
let (hue, chroma, _) = hct_from_rgb(color);
Entry {
color,
proportion: pop as f64 / total_pop,
hue,
chroma,
}
})
.collect();
let mut filtered_hue_pop = [0.0_f64; 360];
let mut all_hue_pop = [0.0_f64; 360];
for e in &entries {
let h_bin = wrap_degrees_i32(e.hue.round() as i32);
all_hue_pop[h_bin] += e.proportion;
if e.chroma > MIN_CHROMA {
filtered_hue_pop[h_bin] += e.proportion;
}
}
let window_sum = |table: &[f64; 360], hue: f64| -> f64 {
let center = hue.round() as i32;
let mut sum = 0.0;
for deg in (center - 15)..=(center + 15) {
sum += table[wrap_degrees_i32(deg)];
}
sum
};
let mut scored_seeds: Vec<(usize, f64)> = Vec::new();
for (idx, e) in entries.iter().enumerate() {
let hue_prop = window_sum(&filtered_hue_pop, e.hue);
if e.chroma >= MIN_CHROMA && hue_prop > 0.01 {
let proportion_score = 0.7 * 100.0 * hue_prop;
let chroma_score = if e.chroma < ACCENT1_CHROMA {
0.1 * (e.chroma - ACCENT1_CHROMA)
} else {
0.3 * (e.chroma - ACCENT1_CHROMA)
};
scored_seeds.push((idx, proportion_score + chroma_score));
}
}
scored_seeds.sort_by(|a, b| {
b.1.total_cmp(&a.1).then_with(|| {
let ca = entries[a.0].color;
let cb = entries[b.0].color;
(ca.0, ca.1, ca.2).cmp(&(cb.0, cb.1, cb.2))
})
});
let mut seeds: Vec<Color> = Vec::with_capacity(4);
let mut seed_hues: Vec<f64> = Vec::with_capacity(4);
'outer: for min_dist in (15..=90).rev() {
seeds.clear();
seed_hues.clear();
let threshold = min_dist as f64;
for &(idx, _) in &scored_seeds {
let e = &entries[idx];
if seed_hues.iter().any(|&h| hue_diff(e.hue, h) < threshold) {
continue;
}
seeds.push(e.color);
seed_hues.push(e.hue);
if seeds.len() >= 4 {
break 'outer;
}
}
}
if seeds.is_empty() {
seeds.push(GOOGLE_BLUE);
}
let mut scored_main: Vec<(usize, f64)> = entries
.iter()
.enumerate()
.map(|(idx, e)| {
let hp = window_sum(&all_hue_pop, e.hue);
(idx, e.chroma + hp * 100.0)
})
.collect();
scored_main.sort_by(|a, b| b.1.total_cmp(&a.1));
let mut main_colors: Vec<Color> = Vec::with_capacity(3);
let mut main_hues: Vec<f64> = Vec::with_capacity(3);
for &(idx, _) in &scored_main {
let e = &entries[idx];
if main_hues.iter().any(|&h| hue_diff(e.hue, h) < 15.0) {
continue;
}
main_colors.push(e.color);
main_hues.push(e.hue);
if main_colors.len() >= 3 {
break;
}
}
let primary = main_colors.first().copied().unwrap_or(seeds[0]);
let secondary = main_colors.get(1).copied();
let tertiary = main_colors.get(2).copied();
Self {
primary,
secondary,
tertiary,
seeds,
supports_dark_text,
supports_dark_theme,
}
}
fn fallback() -> Self {
Self {
primary: GOOGLE_BLUE,
secondary: None,
tertiary: None,
seeds: vec![GOOGLE_BLUE],
supports_dark_text: false,
supports_dark_theme: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MonetScheme {
pub seed: Color,
pub dark: bool,
pub style: MonetStyle,
pub accent1: TonalPalette,
pub accent2: TonalPalette,
pub accent3: TonalPalette,
pub neutral1: TonalPalette,
pub neutral2: TonalPalette,
}
impl MonetScheme {
pub fn new(seed: Color, dark: bool, style: MonetStyle) -> Self {
let (_, proposed_chroma, _) = hct_from_rgb(seed);
let effective_seed = if seed.3 == 0 || (style != MonetStyle::Content && proposed_chroma < MIN_CHROMA) {
GOOGLE_BLUE
} else {
seed
};
let (src_hue, src_chroma, _) = hct_from_rgb(effective_seed);
let specs = style.core_specs();
let make = |(h, c): (HueSpec, ChromaSpec)| {
TonalPalette::new(h.resolve(src_hue), c.resolve(src_chroma))
};
Self {
seed: effective_seed,
dark,
style,
accent1: make(specs[0]),
accent2: make(specs[1]),
accent3: make(specs[2]),
neutral1: make(specs[3]),
neutral2: make(specs[4]),
}
}
pub fn from_wallpaper_colors(colors: &WallpaperColors, dark: bool, style: MonetStyle) -> Self {
let seed = colors.seeds.first().copied().unwrap_or(GOOGLE_BLUE);
Self::new(seed, dark, style)
}
pub fn to_theme(&self) -> Theme {
let error = TonalPalette::new(25.0, 84.0);
if self.dark {
Theme {
background: self.neutral1.tone(6),
text: self.neutral1.tone(90),
control: self.neutral1.tone(12),
hovered: self.neutral1.tone(22),
pressed: self.accent1.tone(30),
radius: 8.0,
primary: self.accent1.tone(80),
on_primary: self.accent1.tone(20),
secondary: self.accent2.tone(30),
outline: self.neutral2.tone(60),
error: error.tone(80),
on_error: error.tone(20),
on_secondary: self.accent2.tone(90),
secondary_container: self.accent2.tone(30),
on_secondary_container: self.accent2.tone(90),
surface_low: self.neutral1.tone(10),
surface_high: self.neutral1.tone(17),
surface_highest: self.neutral1.tone(22),
outline_variant: self.neutral2.tone(30),
primary_container: self.accent1.tone(30),
on_primary_container: self.accent1.tone(90),
tertiary_container: self.accent3.tone(30),
on_tertiary_container: self.accent3.tone(90),
inverse_surface: self.neutral1.tone(90),
inverse_on_surface: self.neutral1.tone(20),
inverse_primary: self.accent1.tone(40),
on_surface_variant: self.neutral2.tone(80),
surface_variant: self.neutral2.tone(30),
}
} else {
Theme {
background: self.neutral1.tone(98),
text: self.neutral1.tone(10),
control: self.neutral1.tone(94),
hovered: self.neutral1.tone(90),
pressed: self.accent1.tone(80),
radius: 8.0,
primary: self.accent1.tone(40),
on_primary: self.accent1.tone(100),
secondary: self.accent2.tone(90),
outline: self.neutral2.tone(50),
error: error.tone(40),
on_error: error.tone(100),
on_secondary: self.accent2.tone(10),
secondary_container: self.accent2.tone(90),
on_secondary_container: self.accent2.tone(10),
surface_low: self.neutral1.tone(96),
surface_high: self.neutral1.tone(92),
surface_highest: self.neutral1.tone(90),
outline_variant: self.neutral2.tone(80),
primary_container: self.accent1.tone(90),
on_primary_container: self.accent1.tone(10),
tertiary_container: self.accent3.tone(90),
on_tertiary_container: self.accent3.tone(10),
inverse_surface: self.neutral1.tone(20),
inverse_on_surface: self.neutral1.tone(95),
inverse_primary: self.accent1.tone(80),
on_surface_variant: self.neutral2.tone(30),
surface_variant: self.neutral2.tone(90),
}
}
}
pub fn preview_quadrants(&self) -> [Color; 4] {
if self.dark {
[
self.accent1.tone(80),
self.accent1.tone(30),
self.accent3.tone(80),
self.accent2.tone(60),
]
} else {
[
self.accent1.tone(40),
self.accent1.tone(80),
self.accent3.tone(80),
self.accent2.tone(90),
]
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn contrast_ratio(a: Color, b: Color) -> f64 {
let la = y_from_lstar(lstar_from_rgb(a)) / 100.0;
let lb = y_from_lstar(lstar_from_rgb(b)) / 100.0;
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
(hi + 0.05) / (lo + 0.05)
}
#[test]
fn hct_round_trip_and_lstar_accuracy() {
let samples = [
GOOGLE_BLUE,
Color(0x67, 0x50, 0xa4, 255),
Color(0xb3, 0x26, 0x1e, 255),
Color(0x14, 0x6c, 0x2e, 255),
Color(0xe6, 0x9f, 0x00, 255),
Color(0x00, 0x80, 0x80, 255),
Color(128, 128, 128, 255),
Color(255, 255, 255, 255),
Color(0, 0, 0, 255),
];
for c in samples {
let (h, ch, t) = hct_from_rgb(c);
let round = rgb_from_hct(h, ch, t);
assert!(
(round.0 as i32 - c.0 as i32).abs() <= 2
&& (round.1 as i32 - c.1 as i32).abs() <= 2
&& (round.2 as i32 - c.2 as i32).abs() <= 2,
"HCT round-trip drift for {:?}: h={:.2} c={:.2} t={:.2} -> {:?}",
c,
h,
ch,
t,
round
);
assert!((lstar_from_rgb(round) - t).abs() < 1.0);
}
assert!((y_from_lstar(0.0) - 0.0).abs() < 1e-6);
assert!((y_from_lstar(100.0) - 100.0).abs() < 1e-6);
assert!((y_from_lstar(50.0) - 18.418651851244416).abs() < 1e-6);
}
#[test]
fn monet_scheme_google_blue_and_all_seven_styles() {
let styles = [
MonetStyle::TonalSpot,
MonetStyle::Spritz,
MonetStyle::Vibrant,
MonetStyle::Expressive,
MonetStyle::Rainbow,
MonetStyle::FruitSalad,
MonetStyle::Content,
];
let base = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::TonalSpot);
assert_eq!(base.accent1.tone(100), Color(255, 255, 255, 255));
assert_eq!(base.accent1.tone(0), Color(0, 0, 0, 255));
let mut prev_l = 101.0;
for &t in &TonalPalette::TONES {
let l = lstar_from_rgb(base.accent1.tone(t));
assert!(l <= prev_l + 0.5, "non-monotonic tone {}: {} > {}", t, l, prev_l);
prev_l = l;
}
assert!(contrast_ratio(base.accent1.tone(50), Color(255, 255, 255, 255)) >= 4.4);
assert!(contrast_ratio(base.accent1.tone(50), Color(0, 0, 0, 255)) >= 4.4);
let mut primary40s = Vec::new();
for style in styles {
let light = MonetScheme::new(GOOGLE_BLUE, false, style);
let dark = MonetScheme::new(GOOGLE_BLUE, true, style);
primary40s.push((style, light.accent1.tone(40)));
let ql = light.preview_quadrants();
let qd = dark.preview_quadrants();
assert_ne!(ql[0], ql[1]);
assert_ne!(qd[0], qd[1]);
assert_ne!(ql, qd);
}
let tonal_h = base.accent1.hue();
let expr = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::Expressive);
let fruit = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::FruitSalad);
let rainbow = MonetScheme::new(GOOGLE_BLUE, false, MonetStyle::Rainbow);
assert!(hue_diff(expr.accent1.hue(), wrap_degrees(tonal_h + 240.0)) < 1e-6);
assert!(hue_diff(fruit.accent1.hue(), wrap_degrees(tonal_h - 50.0)) < 1e-6);
assert_eq!(rainbow.neutral1.chroma(), 0.0);
let gray = Color(120, 120, 120, 255);
assert_eq!(MonetScheme::new(gray, false, MonetStyle::TonalSpot).seed, GOOGLE_BLUE);
assert_eq!(MonetScheme::new(gray, false, MonetStyle::Content).seed, gray);
}
#[test]
fn wallpaper_colors_extracts_hints_and_four_hue_separated_seeds() {
let dark_img = vec![16, 16, 16, 255].repeat(64 * 64);
let wc_dark = WallpaperColors::from_rgba(64, 64, &dark_img);
assert!(wc_dark.supports_dark_theme);
assert!(!wc_dark.supports_dark_text);
assert_eq!(wc_dark.seeds, vec![GOOGLE_BLUE]);
let bright_img = vec![245, 248, 250, 255].repeat(64 * 64);
let wc_bright = WallpaperColors::from_rgba(64, 64, &bright_img);
assert!(wc_bright.supports_dark_text);
assert!(!wc_bright.supports_dark_theme);
let w = 128u32;
let h = 128u32;
let mut quad = vec![0u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let c = match (x < w / 2, y < h / 2) {
(true, true) => [220, 40, 40, 255], (false, true) => [30, 180, 70, 255], (true, false) => [35, 100, 235, 255], (false, false) => [235, 190, 20, 255], };
let i = ((y * w + x) * 4) as usize;
quad[i..i + 4].copy_from_slice(&c);
}
}
let wc_quad = WallpaperColors::from_rgba(w, h, &quad);
assert_eq!(wc_quad.seeds.len(), 4);
assert!(wc_quad.secondary.is_some());
assert!(wc_quad.tertiary.is_some());
for i in 0..wc_quad.seeds.len() {
let (hi, _, _) = hct_from_rgb(wc_quad.seeds[i]);
for j in (i + 1)..wc_quad.seeds.len() {
let (hj, _, _) = hct_from_rgb(wc_quad.seeds[j]);
assert!(
hue_diff(hi, hj) >= 45.0,
"quadrant seeds {} and {} too close in hue: {:.1} vs {:.1}",
i,
j,
hi,
hj
);
}
}
}
#[test]
fn to_theme_meets_m3_contrast_in_light_and_dark_modes_for_all_basic_seeds() {
assert_eq!(BASIC_COLOR_SEEDS.len(), 16);
for &(name, seed) in &BASIC_COLOR_SEEDS {
for dark in [false, true] {
let theme = MonetScheme::new(seed, dark, MonetStyle::TonalSpot).to_theme();
let pairs = [
("text/background", theme.text, theme.background),
("on_primary/primary", theme.on_primary, theme.primary),
(
"on_primary_container/primary_container",
theme.on_primary_container,
theme.primary_container,
),
("on_secondary/secondary", theme.on_secondary, theme.secondary),
(
"on_secondary_container/secondary_container",
theme.on_secondary_container,
theme.secondary_container,
),
(
"on_tertiary_container/tertiary_container",
theme.on_tertiary_container,
theme.tertiary_container,
),
("on_error/error", theme.on_error, theme.error),
(
"inverse_on_surface/inverse_surface",
theme.inverse_on_surface,
theme.inverse_surface,
),
(
"on_surface_variant/background",
theme.on_surface_variant,
theme.background,
),
];
for (pair_name, fg, bg) in pairs {
let cr = contrast_ratio(fg, bg);
assert!(
cr >= 4.5,
"Low contrast ({:.2}) for {} ({}) in dark={}",
cr,
pair_name,
name,
dark
);
}
}
}
}
}