use super::Rgb;
#[inline]
fn mix(a: u8, b: u8, t: f64) -> u8 {
let v = a as f64 + (b as f64 - a as f64) * t;
v.floor() as u8
}
pub fn heat(t: f64) -> Rgb {
let t = t.clamp(0.0, 1.0);
const GOLD: (u8, u8, u8) = (217, 164, 65);
const BONE: (u8, u8, u8) = (233, 223, 201);
const CRIMSON: (u8, u8, u8) = (196, 58, 46);
let (from, to, k) = if t < 0.5 {
(GOLD, BONE, t * 2.0)
} else {
(BONE, CRIMSON, (t - 0.5) * 2.0)
};
Rgb(
mix(from.0, to.0, k),
mix(from.1, to.1, k),
mix(from.2, to.2, k),
)
}
pub fn to_ansi256(c: Rgb) -> u8 {
let Rgb(r, g, b) = c;
if r == g && g == b {
let v = r as f64;
if v < 8.0 {
return 16;
}
if v > 248.0 {
return 231;
}
let step = ((v - 8.0) / 247.0 * 24.0).round() as i32;
return (232 + step) as u8;
}
let cube = |ch: u8| -> u32 { (ch as f64 / 255.0 * 5.0).round() as u32 };
let idx = 16 + 36 * cube(r) + 6 * cube(g) + cube(b);
idx as u8
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Palette {
TrueColor,
Ansi256,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct LitSubcell {
pub(crate) color: Rgb,
pub(crate) depth: f64,
}
pub(crate) fn pick_fg_bg(lit: &[LitSubcell]) -> (Rgb, Rgb) {
if lit.is_empty() {
return (Rgb(0, 0, 0), Rgb(0, 0, 0));
}
struct Group {
color: Rgb,
count: usize,
min_depth: f64,
first_index: usize,
}
let mut groups: Vec<Group> = Vec::new();
for (i, s) in lit.iter().enumerate() {
if let Some(g) = groups.iter_mut().find(|g| g.color == s.color) {
g.count += 1;
if s.depth < g.min_depth {
g.min_depth = s.depth;
}
} else {
groups.push(Group {
color: s.color,
count: 1,
min_depth: s.depth,
first_index: i,
});
}
}
groups.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| {
a.min_depth
.partial_cmp(&b.min_depth)
.unwrap_or(core::cmp::Ordering::Equal)
})
.then_with(|| a.first_index.cmp(&b.first_index))
});
let fg = groups[0].color;
let bg = groups.get(1).map(|g| g.color).unwrap_or(Rgb(0, 0, 0));
(fg, bg)
}