Skip to main content

ttfx_rs/
gradient.rs

1/// Color gradient system matching TTE's gradient engine.
2/// Supports multi-stop linear interpolation, coordinate mapping, and direction-based gradients.
3use crossterm::style::Color;
4
5/// An RGB color for interpolation
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct Rgb {
8    pub r: u8,
9    pub g: u8,
10    pub b: u8,
11}
12
13impl Rgb {
14    pub fn new(r: u8, g: u8, b: u8) -> Self {
15        Self { r, g, b }
16    }
17
18    pub fn from_hex(hex: &str) -> Self {
19        let hex = hex.trim_start_matches('#');
20        let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
21        let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
22        let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
23        Self { r, g, b }
24    }
25
26    pub fn to_crossterm(self) -> Color {
27        Color::Rgb {
28            r: self.r,
29            g: self.g,
30            b: self.b,
31        }
32    }
33
34    /// Adjust HSL lightness by a factor (0.0 = black, 1.0 = same, 2.0 = double).
35    /// Matches TTE's `Animation.adjust_color_brightness`: converts to HSL,
36    /// scales L, converts back, preserving hue and saturation.
37    pub fn adjust_brightness(self, factor: f64) -> Rgb {
38        let r_n = self.r as f64 / 255.0;
39        let g_n = self.g as f64 / 255.0;
40        let b_n = self.b as f64 / 255.0;
41
42        let max_v = r_n.max(g_n).max(b_n);
43        let min_v = r_n.min(g_n).min(b_n);
44        let mut lightness = (max_v + min_v) / 2.0;
45
46        let (hue, saturation) = if max_v == min_v {
47            (0.0, 0.0)
48        } else {
49            let diff = max_v - min_v;
50            let saturation = if lightness > 0.5 {
51                diff / (2.0 - max_v - min_v)
52            } else {
53                diff / (max_v + min_v)
54            };
55            let mut h = if (max_v - r_n).abs() < f64::EPSILON {
56                (g_n - b_n) / diff + (if g_n < b_n { 6.0 } else { 0.0 })
57            } else if (max_v - g_n).abs() < f64::EPSILON {
58                (b_n - r_n) / diff + 2.0
59            } else {
60                (r_n - g_n) / diff + 4.0
61            };
62            h /= 6.0;
63            (h, saturation)
64        };
65
66        lightness = (lightness * factor).clamp(0.0, 1.0);
67
68        let (red, green, blue) = if saturation == 0.0 {
69            (lightness, lightness, lightness)
70        } else {
71            let q = if lightness < 0.5 {
72                lightness * (1.0 + saturation)
73            } else {
74                lightness + saturation - lightness * saturation
75            };
76            let p = 2.0 * lightness - q;
77            (
78                hue_to_rgb(p, q, hue + 1.0 / 3.0),
79                hue_to_rgb(p, q, hue),
80                hue_to_rgb(p, q, hue - 1.0 / 3.0),
81            )
82        };
83
84        Rgb {
85            r: (red * 255.0) as u8,
86            g: (green * 255.0) as u8,
87            b: (blue * 255.0) as u8,
88        }
89    }
90
91    /// Lerp between two colors
92    pub fn lerp(a: Rgb, b: Rgb, t: f64) -> Rgb {
93        let t = t.clamp(0.0, 1.0);
94        Rgb {
95            r: (a.r as f64 + (b.r as f64 - a.r as f64) * t) as u8,
96            g: (a.g as f64 + (b.g as f64 - a.g as f64) * t) as u8,
97            b: (a.b as f64 + (b.b as f64 - a.b as f64) * t) as u8,
98        }
99    }
100}
101
102fn hue_to_rgb(p: f64, q: f64, h: f64) -> f64 {
103    let h = if h < 0.0 {
104        h + 1.0
105    } else if h > 1.0 {
106        h - 1.0
107    } else {
108        h
109    };
110    if h < 1.0 / 6.0 {
111        p + (q - p) * 6.0 * h
112    } else if h < 1.0 / 2.0 {
113        q
114    } else if h < 2.0 / 3.0 {
115        p + (q - p) * (2.0 / 3.0 - h) * 6.0
116    } else {
117        p
118    }
119}
120
121/// Direction for coordinate-mapped gradients
122#[derive(Clone, Copy, Debug)]
123pub enum GradientDirection {
124    Vertical,
125    Horizontal,
126    Diagonal,
127    Radial,
128}
129
130/// A multi-stop color gradient
131#[derive(Clone, Debug)]
132pub struct Gradient {
133    pub stops: Vec<Rgb>,
134    pub steps: usize,
135    spectrum: Vec<Rgb>,
136}
137
138impl Gradient {
139    /// Create a gradient with the given color stops and number of interpolation steps per segment
140    pub fn new(stops: &[Rgb], steps: usize) -> Self {
141        let steps = steps.max(1);
142        let mut spectrum = Vec::new();
143
144        if stops.is_empty() {
145            spectrum.push(Rgb::new(255, 255, 255));
146        } else if stops.len() == 1 {
147            spectrum.push(stops[0]);
148        } else {
149            for i in 0..stops.len() - 1 {
150                for s in 0..steps {
151                    let t = s as f64 / steps as f64;
152                    spectrum.push(Rgb::lerp(stops[i], stops[i + 1], t));
153                }
154            }
155            spectrum.push(*stops.last().unwrap());
156        }
157
158        Self {
159            stops: stops.to_vec(),
160            steps,
161            spectrum,
162        }
163    }
164
165    /// Get the color at position t in [0.0, 1.0]
166    pub fn at(&self, t: f64) -> Rgb {
167        if self.spectrum.is_empty() {
168            return Rgb::new(255, 255, 255);
169        }
170        let t = t.clamp(0.0, 1.0);
171        let idx = (t * (self.spectrum.len() - 1) as f64) as usize;
172        self.spectrum[idx.min(self.spectrum.len() - 1)]
173    }
174
175    /// Get full spectrum
176    pub fn spectrum(&self) -> &[Rgb] {
177        &self.spectrum
178    }
179
180    /// Number of colors in the spectrum
181    pub fn len(&self) -> usize {
182        self.spectrum.len()
183    }
184
185    /// Get color by index
186    pub fn get(&self, idx: usize) -> Rgb {
187        self.spectrum[idx.min(self.spectrum.len() - 1)]
188    }
189
190    /// Build a coordinate-to-color mapping for the given bounds
191    pub fn color_at_coord(
192        &self,
193        row: usize,
194        col: usize,
195        max_row: usize,
196        max_col: usize,
197        direction: GradientDirection,
198    ) -> Rgb {
199        let t = match direction {
200            GradientDirection::Vertical => {
201                if max_row == 0 {
202                    0.0
203                } else {
204                    1.0 - row as f64 / max_row as f64
205                }
206            }
207            GradientDirection::Horizontal => {
208                if max_col == 0 {
209                    0.0
210                } else {
211                    col as f64 / max_col as f64
212                }
213            }
214            GradientDirection::Diagonal => {
215                // TTE: `((row*2) + col) / ((max_row*2) + max_col)` in bottom-up
216                // coords (row 0 = visual bottom, max_row = visual top). The
217                // 2× weights the row dimension so the diagonal looks
218                // approximately equal-angled despite the terminal cell aspect.
219                // In rtte top-down (row 0 = visual top), flip the row to keep
220                // the visual orientation: bottom-left = first stop, top-right
221                // = last stop.
222                let denom = 2 * max_row + max_col;
223                if denom == 0 {
224                    0.0
225                } else {
226                    let flipped_row = max_row.saturating_sub(row);
227                    (2 * flipped_row + col) as f64 / denom as f64
228                }
229            }
230            GradientDirection::Radial => {
231                let cr = max_row as f64 / 2.0;
232                let cc = max_col as f64 / 2.0;
233                let max_dist = (cr * cr + cc * cc).sqrt();
234                if max_dist == 0.0 {
235                    0.0
236                } else {
237                    let dr = row as f64 - cr;
238                    let dc = col as f64 - cc;
239                    (dr * dr + dc * dc).sqrt() / max_dist
240                }
241            }
242        };
243        self.at(t)
244    }
245}
246
247/// Fluent builder for creating multi-stop color gradients
248#[derive(Default, Debug, Clone)]
249pub struct GradientBuilder {
250    stops: Vec<Rgb>,
251    steps: usize,
252}
253
254impl GradientBuilder {
255    pub fn new() -> Self {
256        Self {
257            stops: Vec::new(),
258            steps: 12,
259        }
260    }
261
262    pub fn stop_hex(mut self, hex: &str) -> Self {
263        self.stops.push(Rgb::from_hex(hex));
264        self
265    }
266
267    pub fn stop_rgb(mut self, r: u8, g: u8, b: u8) -> Self {
268        self.stops.push(Rgb::new(r, g, b));
269        self
270    }
271
272    pub fn steps(mut self, steps: usize) -> Self {
273        self.steps = steps;
274        self
275    }
276
277    pub fn build(self) -> Gradient {
278        Gradient::new(&self.stops, self.steps)
279    }
280}
281
282#[cfg(test)]
283#[path = "tests/gradient.rs"]
284mod tests;
285
286/// Predefined color palettes matching TTE defaults
287pub mod palettes {
288    use super::Rgb;
289
290    pub fn matrix_rain() -> Vec<Rgb> {
291        vec![Rgb::from_hex("92be92"), Rgb::from_hex("185318")]
292    }
293    pub fn matrix_highlight() -> Rgb {
294        Rgb::from_hex("dbffdb")
295    }
296    pub fn fire() -> Vec<Rgb> {
297        vec![
298            Rgb::new(255, 255, 255),
299            Rgb::new(255, 255, 0),
300            Rgb::new(255, 165, 0),
301            Rgb::new(200, 50, 0),
302            Rgb::new(40, 40, 40),
303        ]
304    }
305    pub fn decrypt_cipher() -> Vec<Rgb> {
306        vec![
307            Rgb::from_hex("008000"),
308            Rgb::from_hex("00cb00"),
309            Rgb::from_hex("00ff00"),
310        ]
311    }
312    pub fn decrypt_final() -> Rgb {
313        Rgb::from_hex("eda000")
314    }
315    pub fn default_final() -> Vec<Rgb> {
316        vec![
317            Rgb::from_hex("8A008A"),
318            Rgb::from_hex("00D1FF"),
319            Rgb::from_hex("FFFFFF"),
320        ]
321    }
322    pub fn purple_cyan_white() -> Vec<Rgb> {
323        vec![
324            Rgb::from_hex("8A008A"),
325            Rgb::from_hex("00D1FF"),
326            Rgb::from_hex("FFFFFF"),
327        ]
328    }
329    pub fn rainbow() -> Vec<Rgb> {
330        vec![
331            Rgb::new(255, 0, 0),
332            Rgb::new(255, 165, 0),
333            Rgb::new(255, 255, 0),
334            Rgb::new(0, 255, 0),
335            Rgb::new(0, 0, 255),
336            Rgb::new(75, 0, 130),
337            Rgb::new(238, 130, 238),
338        ]
339    }
340    pub fn star_colors() -> Vec<Rgb> {
341        vec![
342            Rgb::from_hex("ffcc0d"),
343            Rgb::from_hex("ff7326"),
344            Rgb::from_hex("ff194d"),
345            Rgb::from_hex("bf2669"),
346            Rgb::from_hex("702a8c"),
347            Rgb::new(255, 255, 255),
348        ]
349    }
350    pub fn lightning() -> Rgb {
351        Rgb::from_hex("68A3E8")
352    }
353    pub fn error_red() -> Rgb {
354        Rgb::from_hex("e74c3c")
355    }
356    pub fn correct_green() -> Rgb {
357        Rgb::from_hex("45bf55")
358    }
359}