Skip to main content

scala_chromatica/
colormap.rs

1//! Color gradients with smooth interpolation
2//!
3//! A ColorMap consists of multiple ColorStops positioned along a gradient (0.0 to 1.0).
4//! Colors between stops are computed using linear RGB interpolation.
5//!
6//! # Example
7//! ```
8//! use scala_chromatica::{ColorMap, ColorStop, Color};
9//!
10//! let mut map = ColorMap::new("RedToBlue");
11//! map.add_stop(ColorStop::new(0.0, Color::new(255, 0, 0)));
12//! map.add_stop(ColorStop::new(1.0, Color::new(0, 0, 255)));
13//!
14//! let mid_color = map.get_color(0.5); // Gets color halfway between red and blue
15//! ```
16
17use crate::color::Color;
18use serde::{Deserialize, Serialize};
19
20/// A color stop in a gradient (position + color)
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct ColorStop {
23    /// Position along the gradient (0.0 to 1.0)
24    pub position: f64,
25    /// RGB color at this position
26    pub color: Color,
27    /// Optional name for documentation/UI purposes
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub name: Option<String>,
30}
31
32impl ColorStop {
33    /// Create a new color stop
34    pub fn new(position: f64, color: Color) -> Self {
35        Self {
36            position: position.clamp(0.0, 1.0),
37            color,
38            name: None,
39        }
40    }
41
42    /// Create a new color stop with a name
43    pub fn with_name(position: f64, color: Color, name: impl Into<String>) -> Self {
44        Self {
45            position: position.clamp(0.0, 1.0),
46            color,
47            name: Some(name.into()),
48        }
49    }
50}
51
52/// A colormap with multiple color stops and smooth interpolation
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ColorMap {
55    /// Name of the colormap
56    pub name: String,
57    /// Ordered list of color stops
58    pub stops: Vec<ColorStop>,
59}
60
61impl ColorMap {
62    /// Create a new colormap with a given name
63    pub fn new(name: impl Into<String>) -> Self {
64        Self {
65            name: name.into(),
66            stops: Vec::new(),
67        }
68    }
69
70    /// Create a colormap with initial stops
71    pub fn with_stops(name: impl Into<String>, stops: Vec<ColorStop>) -> Self {
72        let mut colormap = Self {
73            name: name.into(),
74            stops,
75        };
76        colormap.sort_stops();
77        colormap
78    }
79
80    /// Add a color stop to the gradient
81    pub fn add_stop(&mut self, stop: ColorStop) {
82        self.stops.push(stop);
83        self.sort_stops();
84    }
85
86    /// Remove a color stop by index (minimum 2 stops required)
87    pub fn remove_stop(&mut self, index: usize) {
88        if index < self.stops.len() && self.stops.len() > 2 {
89            self.stops.remove(index);
90        }
91    }
92
93    /// Sort stops by position (maintains gradient order)
94    fn sort_stops(&mut self) {
95        self.stops
96            .sort_by(|a, b| a.position.partial_cmp(&b.position).unwrap());
97    }
98
99    /// Get color at a specific position (0.0 to 1.0) by interpolating between stops
100    pub fn get_color(&self, position: f64) -> Color {
101        let position = position.clamp(0.0, 1.0);
102
103        if self.stops.is_empty() {
104            return Color::black();
105        }
106
107        if self.stops.len() == 1 {
108            return self.stops[0].color;
109        }
110
111        // Before first stop
112        if position <= self.stops[0].position {
113            return self.stops[0].color;
114        }
115
116        // After last stop
117        if position >= self.stops.last().unwrap().position {
118            return self.stops.last().unwrap().color;
119        }
120
121        // Find surrounding stops and interpolate
122        for i in 0..self.stops.len() - 1 {
123            let stop1 = &self.stops[i];
124            let stop2 = &self.stops[i + 1];
125
126            if position >= stop1.position && position <= stop2.position {
127                let range = stop2.position - stop1.position;
128                let t = if range > 0.0 {
129                    (position - stop1.position) / range
130                } else {
131                    0.0
132                };
133                return stop1.color.lerp(&stop2.color, t);
134            }
135        }
136
137        // Fallback to last color
138        self.stops.last().unwrap().color
139    }
140
141    /// Create a new colormap with all stops reversed
142    ///
143    /// This reverses the gradient by flipping all stop positions:
144    /// a stop at position 0.2 becomes 0.8, etc.
145    ///
146    /// # Examples
147    /// ```
148    /// use scala_chromatica::{ColorMap, ColorStop, Color};
149    ///
150    /// let mut map = ColorMap::new("RedToBlue");
151    /// map.add_stop(ColorStop::new(0.0, Color::new(255, 0, 0)));
152    /// map.add_stop(ColorStop::new(1.0, Color::new(0, 0, 255)));
153    ///
154    /// let reversed = map.reversed();
155    /// // Now starts with blue at 0.0 and ends with red at 1.0
156    /// ```
157    pub fn reversed(&self) -> Self {
158        let reversed_stops = self
159            .stops
160            .iter()
161            .map(|stop| ColorStop {
162                position: 1.0 - stop.position,
163                color: stop.color,
164                name: stop.name.clone(),
165            })
166            .collect::<Vec<_>>();
167
168        Self::with_stops(format!("{} (Reversed)", self.name), reversed_stops)
169    }
170
171    /// Default HSV-based color scheme (smooth rainbow)
172    pub fn default_scheme() -> Self {
173        Self::with_stops(
174            "Default",
175            vec![
176                ColorStop::new(0.0, Color::black()),
177                ColorStop::new(0.2, Color::from_hsv(240.0, 1.0, 1.0)), // Blue
178                ColorStop::new(0.5, Color::from_hsv(120.0, 1.0, 1.0)), // Green
179                ColorStop::new(0.8, Color::from_hsv(0.0, 1.0, 1.0)),   // Red
180                ColorStop::new(1.0, Color::white()),
181            ],
182        )
183    }
184
185    /// Fire color scheme (black -> red -> orange -> yellow -> white)
186    pub fn fire_scheme() -> Self {
187        Self::with_stops(
188            "Fire",
189            vec![
190                ColorStop::new(0.0, Color::black()),
191                ColorStop::new(0.25, Color::new(128, 0, 0)), // Dark red
192                ColorStop::new(0.5, Color::new(255, 0, 0)),  // Red
193                ColorStop::new(0.75, Color::new(255, 128, 0)), // Orange
194                ColorStop::new(0.9, Color::new(255, 255, 0)), // Yellow
195                ColorStop::new(1.0, Color::white()),
196            ],
197        )
198    }
199
200    /// Ocean color scheme (black -> deep blue -> cyan -> white)
201    pub fn ocean_scheme() -> Self {
202        Self::with_stops(
203            "Ocean",
204            vec![
205                ColorStop::new(0.0, Color::black()),
206                ColorStop::new(0.3, Color::new(0, 0, 128)), // Deep blue
207                ColorStop::new(0.6, Color::new(0, 128, 255)), // Sky blue
208                ColorStop::new(0.85, Color::new(0, 255, 255)), // Cyan
209                ColorStop::new(1.0, Color::white()),
210            ],
211        )
212    }
213
214    /// Grayscale color scheme (black -> gray -> white)
215    pub fn grayscale_scheme() -> Self {
216        Self::with_stops(
217            "Grayscale",
218            vec![
219                ColorStop::new(0.0, Color::black()),
220                ColorStop::new(0.5, Color::new(128, 128, 128)),
221                ColorStop::new(1.0, Color::white()),
222            ],
223        )
224    }
225
226    /// Rainbow color scheme (full spectrum)
227    pub fn rainbow_scheme() -> Self {
228        Self::with_stops(
229            "Rainbow",
230            vec![
231                ColorStop::new(0.0, Color::from_hsv(0.0, 1.0, 1.0)), // Red
232                ColorStop::new(0.17, Color::from_hsv(60.0, 1.0, 1.0)), // Yellow
233                ColorStop::new(0.33, Color::from_hsv(120.0, 1.0, 1.0)), // Green
234                ColorStop::new(0.5, Color::from_hsv(180.0, 1.0, 1.0)), // Cyan
235                ColorStop::new(0.67, Color::from_hsv(240.0, 1.0, 1.0)), // Blue
236                ColorStop::new(0.83, Color::from_hsv(300.0, 1.0, 1.0)), // Magenta
237                ColorStop::new(1.0, Color::from_hsv(360.0, 1.0, 1.0)), // Red
238            ],
239        )
240    }
241}
242
243/// Convert iteration count to color using a colormap
244///
245/// This is a utility function for fractal rendering and similar applications
246/// where you need to map iteration counts to colors.
247///
248/// # Arguments
249/// * `iterations` - Number of iterations performed
250/// * `max_iterations` - Maximum iterations allowed
251/// * `colormap` - The colormap to use for coloring
252/// * `use_period` - Enable periodic color cycling
253/// * `period` - Period for color cycling (if enabled)
254/// * `use_interior_color` - Use custom color for interior points
255/// * `interior_color` - RGB color for interior points
256/// * `use_log_scale` - Apply logarithmic scaling to colors
257#[allow(clippy::too_many_arguments)]
258pub fn color_from_iterations(
259    iterations: u32,
260    max_iterations: u32,
261    colormap: &ColorMap,
262    use_period: bool,
263    period: u32,
264    use_interior_color: bool,
265    interior_color: [u8; 3],
266    use_log_scale: bool,
267) -> Color {
268    // Check if point is inside the set and custom interior color is enabled
269    if iterations >= max_iterations && use_interior_color {
270        return Color {
271            r: interior_color[0],
272            g: interior_color[1],
273            b: interior_color[2],
274        };
275    }
276
277    // Apply period modulation if enabled
278    let effective_iterations = if use_period && period > 0 {
279        iterations % period
280    } else {
281        iterations
282    };
283
284    // Normalize iterations to 0.0-1.0 range
285    let divisor = if use_period && period > 0 {
286        period as f64
287    } else {
288        max_iterations as f64
289    };
290    let t = effective_iterations as f64 / divisor;
291
292    // Apply smooth coloring - use log scale if enabled, otherwise linear
293    let smooth_t = if use_log_scale {
294        (t * 10.0).log10() / 1.0 // log10(10) = 1
295    } else {
296        t // Linear scaling
297    };
298
299    colormap.get_color(smooth_t.clamp(0.0, 1.0))
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    #[test]
307    fn test_colorstop_creation() {
308        let stop = ColorStop::new(0.5, Color::new(255, 0, 0));
309        assert_eq!(stop.position, 0.5);
310        assert_eq!(stop.color.r, 255);
311        assert!(stop.name.is_none());
312
313        let named_stop = ColorStop::with_name(0.3, Color::new(0, 255, 0), "Green");
314        assert_eq!(named_stop.name, Some("Green".to_string()));
315    }
316
317    #[test]
318    fn test_colormap_gradient() {
319        let mut map = ColorMap::new("Test");
320        map.add_stop(ColorStop::new(0.0, Color::new(0, 0, 0)));
321        map.add_stop(ColorStop::new(1.0, Color::new(255, 255, 255)));
322
323        let start = map.get_color(0.0);
324        assert_eq!(start.r, 0);
325
326        let end = map.get_color(1.0);
327        assert_eq!(end.r, 255);
328
329        let mid = map.get_color(0.5);
330        assert!(mid.r > 100 && mid.r < 200);
331    }
332
333    #[test]
334    fn test_builtin_schemes() {
335        let default = ColorMap::default_scheme();
336        assert_eq!(default.name, "Default");
337        assert!(!default.stops.is_empty());
338
339        let fire = ColorMap::fire_scheme();
340        assert_eq!(fire.name, "Fire");
341
342        let ocean = ColorMap::ocean_scheme();
343        assert_eq!(ocean.name, "Ocean");
344
345        let grayscale = ColorMap::grayscale_scheme();
346        assert_eq!(grayscale.name, "Grayscale");
347
348        let rainbow = ColorMap::rainbow_scheme();
349        assert_eq!(rainbow.name, "Rainbow");
350    }
351
352    #[test]
353    fn test_reversed() {
354        let mut map = ColorMap::new("RedToBlue");
355        map.add_stop(ColorStop::new(0.0, Color::new(255, 0, 0))); // Red at start
356        map.add_stop(ColorStop::new(0.5, Color::new(128, 128, 0))); // Yellow-ish mid
357        map.add_stop(ColorStop::new(1.0, Color::new(0, 0, 255))); // Blue at end
358
359        let reversed = map.reversed();
360        
361        // Check name
362        assert_eq!(reversed.name, "RedToBlue (Reversed)");
363        
364        // Check number of stops
365        assert_eq!(reversed.stops.len(), 3);
366        
367        // Check that positions are flipped
368        assert_eq!(reversed.stops[0].position, 0.0);
369        assert_eq!(reversed.stops[1].position, 0.5);
370        assert_eq!(reversed.stops[2].position, 1.0);
371        
372        // Check that colors are in reverse order
373        // Original: Red(0.0) -> Yellow(0.5) -> Blue(1.0)
374        // Reversed: Blue(0.0) -> Yellow(0.5) -> Red(1.0)
375        assert_eq!(reversed.stops[0].color.b, 255); // Blue at start
376        assert_eq!(reversed.stops[2].color.r, 255); // Red at end
377        
378        // Check that getting color works correctly
379        let reversed_start = reversed.get_color(0.0);
380        let original_end = map.get_color(1.0);
381        assert_eq!(reversed_start.r, original_end.r);
382        assert_eq!(reversed_start.g, original_end.g);
383        assert_eq!(reversed_start.b, original_end.b);
384    }
385}