Skip to main content

hypergraph_rs/raster/
color.rs

1//! Color under constraint (Task 4): the deck's gold->bone->crimson heat
2//! canon, a deterministic 256-palette quantization, and the per-cell
3//! "one fg + one bg" pick under the braille glyph floor.
4//!
5//! `heat` is a verbatim transcription of `topology-deck.html:277-284`
6//! (`mix(a,b,t)=a+(b-a)*t`, `|0` = `.floor() as u8`). `to_ansi256` mines
7//! the 6x6x6 cube + 24-step grayscale ramp technique described in the
8//! plan (Task 4 Step 3) — this crate carries no vendored copy of
9//! `tui-3d-renderer`, so the formula is transcribed from the plan text,
10//! which is itself the authoritative source for this fn.
11
12use super::Rgb;
13
14/// Linear mix: `a + (b-a)*t`, matching the deck's `mix`.
15#[inline]
16fn mix(a: u8, b: u8, t: f64) -> u8 {
17    let v = a as f64 + (b as f64 - a as f64) * t;
18    // Deck's `|0` is a floor-toward-zero on a non-negative float here
19    // (channel values stay within [0,255] for t in [0,1]).
20    v.floor() as u8
21}
22
23/// Gold(low) -> bone -> crimson(high), transcribed verbatim from the deck's
24/// `heat()` (`topology-deck.html:278-284`). `t` is clamped to `[0,1]`.
25pub fn heat(t: f64) -> Rgb {
26    let t = t.clamp(0.0, 1.0);
27    const GOLD: (u8, u8, u8) = (217, 164, 65);
28    const BONE: (u8, u8, u8) = (233, 223, 201);
29    const CRIMSON: (u8, u8, u8) = (196, 58, 46);
30
31    let (from, to, k) = if t < 0.5 {
32        (GOLD, BONE, t * 2.0)
33    } else {
34        (BONE, CRIMSON, (t - 0.5) * 2.0)
35    };
36
37    Rgb(
38        mix(from.0, to.0, k),
39        mix(from.1, to.1, k),
40        mix(from.2, to.2, k),
41    )
42}
43
44/// Quantize a truecolor `Rgb` to an ANSI-256 palette index: the 24-step
45/// grayscale ramp (232..=255) when `r==g==b`, else the 6x6x6 color cube
46/// (16..=231). Tie-break pinned to `f64::round` (round-half-away-from-zero,
47/// IEEE-754 reproducible per user CLAUDE.md §4) — never truncating `as u8`.
48pub fn to_ansi256(c: Rgb) -> u8 {
49    let Rgb(r, g, b) = c;
50    if r == g && g == b {
51        let v = r as f64;
52        if v < 8.0 {
53            return 16;
54        }
55        if v > 248.0 {
56            return 231;
57        }
58        let step = ((v - 8.0) / 247.0 * 24.0).round() as i32;
59        return (232 + step) as u8;
60    }
61
62    let cube = |ch: u8| -> u32 { (ch as f64 / 255.0 * 5.0).round() as u32 };
63    let idx = 16 + 36 * cube(r) + 6 * cube(g) + cube(b);
64    idx as u8
65}
66
67/// The output palette a `CellGrid` is rendered under.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Palette {
70    TrueColor,
71    Ansi256,
72}
73
74/// A lit subcell's color+depth, in the cell's fixed subcell scan order
75/// (`(sub_col,sub_row)`: (0,0),(1,0),(0,1),(1,1),(0,2),(1,2),(0,3),(1,3) —
76/// `grid::compose_braille`'s iteration order).
77#[derive(Debug, Clone, Copy)]
78pub(crate) struct LitSubcell {
79    pub(crate) color: Rgb,
80    pub(crate) depth: f64,
81}
82
83/// Pick `(fg, bg)` for one cell from its lit subcells, under the braille
84/// "one fg + one bg" constraint. `fg` = color of the **majority** of lit
85/// subcells; ties broken by (a) nearest depth (the minimum depth among a
86/// candidate color's own subcells — smaller wins), then (b) lowest subcell
87/// scan index. `bg` = the next-most-common lit color (by the same
88/// tie-break, excluding `fg`'s color), else `Rgb(0,0,0)` if no other color
89/// is present. Bounded: `lit.len() <= 8` (one cell's subcells).
90pub(crate) fn pick_fg_bg(lit: &[LitSubcell]) -> (Rgb, Rgb) {
91    if lit.is_empty() {
92        return (Rgb(0, 0, 0), Rgb(0, 0, 0));
93    }
94
95    // Group by color (first-seen order == scan order, since `lit` is
96    // built in scan order) — a bounded linear scan over <= 8 entries.
97    struct Group {
98        color: Rgb,
99        count: usize,
100        min_depth: f64,
101        first_index: usize,
102    }
103    let mut groups: Vec<Group> = Vec::new();
104    for (i, s) in lit.iter().enumerate() {
105        if let Some(g) = groups.iter_mut().find(|g| g.color == s.color) {
106            g.count += 1;
107            if s.depth < g.min_depth {
108                g.min_depth = s.depth;
109            }
110        } else {
111            groups.push(Group {
112                color: s.color,
113                count: 1,
114                min_depth: s.depth,
115                first_index: i,
116            });
117        }
118    }
119
120    // Rank: highest count first; ties by nearest (smallest) min_depth;
121    // remaining ties by lowest first-seen scan index.
122    groups.sort_by(|a, b| {
123        b.count
124            .cmp(&a.count)
125            .then_with(|| {
126                a.min_depth
127                    .partial_cmp(&b.min_depth)
128                    .unwrap_or(core::cmp::Ordering::Equal)
129            })
130            .then_with(|| a.first_index.cmp(&b.first_index))
131    });
132
133    let fg = groups[0].color;
134    let bg = groups.get(1).map(|g| g.color).unwrap_or(Rgb(0, 0, 0));
135    (fg, bg)
136}