Skip to main content

crisol_plot/plot/three/
series.rs

1//! 3D series: lines, scatter clouds, vertical bars, and regular surfaces.
2
3use std::borrow::Cow;
4
5use egui::Color32;
6
7use super::super::axis::Scale;
8use super::super::series::{LineStyle, Marker};
9use super::types::Bounds3D;
10
11/// A regular surface: `x` columns, `y` rows, and row-major `z` values.
12#[derive(Clone, Debug, PartialEq)]
13pub struct Surface<'a> {
14    /// Column coordinates, left to right.
15    pub x: Cow<'a, [f64]>,
16    /// Row coordinates, back to front.
17    pub y: Cow<'a, [f64]>,
18    /// Height at `y * x.len() + x`, row-major.
19    pub z: Cow<'a, [f64]>,
20}
21
22impl Surface<'_> {
23    pub(super) fn columns(&self) -> usize {
24        self.x.len()
25    }
26
27    pub(super) fn rows(&self) -> usize {
28        self.y.len()
29    }
30
31    pub(super) fn point(&self, index: usize) -> Option<[f64; 3]> {
32        let columns = self.x.len();
33        if columns == 0 {
34            return None;
35        }
36        let column = index % columns;
37        let row = index / columns;
38        Some([*self.x.get(column)?, *self.y.get(row)?, *self.z.get(index)?])
39    }
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub(super) enum Kind3D {
44    Line,
45    Scatter,
46    Bars,
47    Surface,
48}
49
50/// One named 3D data set. Build it with [`Series3D::line`], [`Series3D::scatter`],
51/// [`Series3D::bars`], [`Series3D::surface`], or [`Series3D::surface_fn`], then add it
52/// to a [`super::Plot3D`].
53#[derive(Clone, Debug)]
54pub struct Series3D<'a> {
55    pub(super) name: String,
56    pub(super) data: Cow<'a, [[f64; 3]]>,
57    pub(super) surface: Option<Surface<'a>>,
58    pub(super) kind: Kind3D,
59    pub(super) color: Option<Color32>,
60    pub(super) legend: bool,
61    pub(super) width: f32,
62    pub(super) line_style: LineStyle,
63    pub(super) marker: Option<Marker>,
64    pub(super) radius: f32,
65    pub(super) bar_width: Option<f64>,
66    pub(super) base: f64,
67}
68
69impl<'a> Series3D<'a> {
70    fn new(name: impl Into<String>, data: Cow<'a, [[f64; 3]]>, kind: Kind3D) -> Self {
71        Self {
72            name: name.into(),
73            data,
74            surface: None,
75            kind,
76            color: None,
77            legend: true,
78            width: 1.6,
79            line_style: LineStyle::Solid,
80            marker: None,
81            radius: 3.0,
82            bar_width: None,
83            base: 0.0,
84        }
85    }
86
87    /// A polyline through `[x, y, z]` points, in order.
88    pub fn line(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
89        Self::new(name, data.into(), Kind3D::Line)
90    }
91
92    /// Unconnected 3D markers.
93    pub fn scatter(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
94        Self::new(name, data.into(), Kind3D::Scatter)
95    }
96
97    /// Vertical bars from the z base (0 by default) to each `[x, y, z]` point.
98    pub fn bars(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
99        Self::new(name, data.into(), Kind3D::Bars)
100    }
101
102    /// A surface over the grid `x × y` with row-major `z`.
103    ///
104    /// ```
105    /// # use crisol_plot::plot::{Plot3D, Plot3DState, Series3D};
106    /// # let ctx = egui::Context::default();
107    /// # let mut icons = crisol_plot::Icons::new();
108    /// let x = vec![-1.0, 0.0, 1.0];
109    /// let y = vec![-1.0, 0.0, 1.0];
110    /// let z = vec![0.0, 1.0, 0.0, 1.0, 2.0, 1.0, 0.0, 1.0, 0.0];
111    /// let mut state = Plot3DState::default();
112    /// # let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
113    /// Plot3D::new("terrain")
114    ///     .series(Series3D::surface("terrain", x.clone(), y.clone(), z.clone()))
115    ///     .show(ui, &mut icons, &mut state);
116    /// # });
117    /// # output.textures_delta.clear();
118    /// ```
119    pub fn surface(
120        name: impl Into<String>,
121        x: impl Into<Cow<'a, [f64]>>,
122        y: impl Into<Cow<'a, [f64]>>,
123        z: impl Into<Cow<'a, [f64]>>,
124    ) -> Self {
125        let surface = Surface {
126            x: x.into(),
127            y: y.into(),
128            z: z.into(),
129        };
130        let mut series = Self::new(name, Cow::Owned(Vec::new()), Kind3D::Surface);
131        series.surface = Some(surface);
132        series
133    }
134
135    /// A surface sampled `columns × rows` times over two ranges.
136    pub fn surface_fn(
137        name: impl Into<String>,
138        x_range: std::ops::RangeInclusive<f64>,
139        y_range: std::ops::RangeInclusive<f64>,
140        samples: [usize; 2],
141        f: impl Fn(f64, f64) -> f64,
142    ) -> Series3D<'static> {
143        // Bound the sample grid: a tiny request for a 10^9 x 10^9 surface used to
144        // reserve petabytes before the first point was evaluated.
145        const MAX_SAMPLES: usize = 4_096;
146        const MAX_POINTS: usize = 4_000_000;
147        let columns = samples[0].clamp(2, MAX_SAMPLES);
148        let rows = samples[1].clamp(2, MAX_POINTS / columns);
149        let (x0, x1) = (*x_range.start(), *x_range.end());
150        let (y0, y1) = (*y_range.start(), *y_range.end());
151        let x: Vec<f64> = (0..columns)
152            .map(|index| x0 + (x1 - x0) * index as f64 / (columns - 1) as f64)
153            .collect();
154        let y: Vec<f64> = (0..rows)
155            .map(|index| y0 + (y1 - y0) * index as f64 / (rows - 1) as f64)
156            .collect();
157        let mut z = Vec::with_capacity(columns * rows);
158        for &y_value in &y {
159            for &x_value in &x {
160                z.push(f(x_value, y_value));
161            }
162        }
163        Series3D::surface(name, x, y, z)
164    }
165
166    /// Explicit color; the theme palette is used in order otherwise.
167    pub fn color(mut self, color: Color32) -> Self {
168        self.color = Some(color);
169        self
170    }
171
172    /// Line width in points.
173    pub fn width(mut self, width: f32) -> Self {
174        self.width = width.max(0.5);
175        self
176    }
177
178    /// Solid, dashed, or dotted lines.
179    pub fn style(mut self, style: LineStyle) -> Self {
180        self.line_style = style;
181        self
182    }
183
184    /// A marker on every line vertex, or the scatter marker.
185    pub fn marker(mut self, marker: Marker) -> Self {
186        self.marker = Some(marker);
187        self
188    }
189
190    /// Marker radius in points.
191    pub fn radius(mut self, radius: f32) -> Self {
192        self.radius = radius.max(1.0);
193        self
194    }
195
196    /// Bar footprint in data units; the smallest x/y gap × 0.7 when `None`.
197    pub fn bar_width(mut self, width: f64) -> Self {
198        self.bar_width = Some(width);
199        self
200    }
201
202    /// Where bars start (default 0).
203    pub fn base(mut self, base: f64) -> Self {
204        self.base = base;
205        self
206    }
207
208    /// Leave the series out of the legend.
209    pub fn hide_from_legend(mut self) -> Self {
210        self.legend = false;
211        self
212    }
213
214    /// The series name (also the legend label).
215    pub fn name(&self) -> &str {
216        &self.name
217    }
218
219    /// The points, for line, scatter, and bar series (empty for surfaces).
220    pub fn data(&self) -> &[[f64; 3]] {
221        &self.data
222    }
223
224    /// The surface grid, when this is a surface series.
225    pub fn surface_grid(&self) -> Option<&Surface<'a>> {
226        self.surface.as_ref()
227    }
228
229    /// One data point by index: a grid vertex for surfaces.
230    pub fn point(&self, index: usize) -> Option<[f64; 3]> {
231        match &self.surface {
232            Some(surface) => surface.point(index),
233            None => self.data.get(index).copied(),
234        }
235    }
236
237    /// How many points the series has, including surface vertices.
238    pub fn len(&self) -> usize {
239        match &self.surface {
240            Some(surface) => surface.z.len(),
241            None => self.data.len(),
242        }
243    }
244
245    /// Whether the series has no points.
246    pub fn is_empty(&self) -> bool {
247        self.len() == 0
248    }
249
250    pub(super) fn has_direction(&self) -> bool {
251        self.kind == Kind3D::Line
252    }
253
254    pub(super) fn bar_width_value(&self) -> f64 {
255        self.bar_width
256            .filter(|width| width.is_finite() && *width > 0.0)
257            .unwrap_or_else(|| self.min_spacing() * 0.7)
258    }
259
260    /// The smallest positive x or y step (1 when there is none).
261    pub(super) fn min_spacing(&self) -> f64 {
262        let points: Vec<[f64; 3]> = match &self.surface {
263            Some(surface) => surface
264                .z
265                .iter()
266                .enumerate()
267                .filter_map(|(index, _)| surface.point(index))
268                .collect(),
269            None => self.data.iter().copied().collect(),
270        };
271        let x = smallest_step(points.iter().map(|point| point[0]));
272        let y = smallest_step(points.iter().map(|point| point[1]));
273        x.min(y)
274    }
275
276    /// Data extent in scaled space (log axes ignore values ≤ 0).
277    pub(super) fn bounds(&self, x_scale: Scale, y_scale: Scale, z_scale: Scale) -> Bounds3D {
278        let mut bounds = Bounds3D::NOTHING;
279        if let Some(surface) = &self.surface {
280            for index in 0..surface.z.len() {
281                if let Some(point) = surface.point(index) {
282                    bounds.extend([
283                        x_scale.forward(point[0]),
284                        y_scale.forward(point[1]),
285                        z_scale.forward(point[2]),
286                    ]);
287                }
288            }
289            return bounds;
290        }
291        for point in self.data.iter() {
292            bounds.extend([
293                x_scale.forward(point[0]),
294                y_scale.forward(point[1]),
295                z_scale.forward(point[2]),
296            ]);
297        }
298        if self.kind == Kind3D::Bars && bounds.is_valid() {
299            let half = self.bar_width_value() * 0.5;
300            bounds.extend([bounds.min_x - half, bounds.min_y - half, z_scale.forward(self.base)]);
301            bounds.extend([bounds.max_x + half, bounds.max_y + half, z_scale.forward(self.base)]);
302        }
303        bounds
304    }
305
306    /// A cheap key for [`Self::bounds`]: buffer addresses and lengths, the kind, the
307    /// scales, and sampled values.
308    pub(super) fn fingerprint(&self, x_scale: Scale, y_scale: Scale, z_scale: Scale) -> u64 {
309        use std::hash::{Hash, Hasher};
310        let mut hasher = std::collections::hash_map::DefaultHasher::new();
311        (self.data.as_ptr() as usize, self.data.len()).hash(&mut hasher);
312        if let Some(surface) = &self.surface {
313            for values in [&surface.x, &surface.y, &surface.z] {
314                (values.as_ptr() as usize, values.len()).hash(&mut hasher);
315                let step = (values.len() / 8).max(1);
316                for value in values.iter().step_by(step) {
317                    value.to_bits().hash(&mut hasher);
318                }
319            }
320        }
321        self.kind.hash(&mut hasher);
322        (x_scale, y_scale, z_scale).hash(&mut hasher);
323        let step = (self.data.len() / 16).max(1);
324        for point in self.data.iter().step_by(step).chain(self.data.last()) {
325            for value in point {
326                value.to_bits().hash(&mut hasher);
327            }
328        }
329        hasher.finish()
330    }
331}
332
333fn smallest_step(values: impl Iterator<Item = f64>) -> f64 {
334    let mut values: Vec<f64> = values.filter(|value| value.is_finite()).collect();
335    values.sort_by(f64::total_cmp);
336    let mut step = f64::INFINITY;
337    for pair in values.windows(2) {
338        let delta = pair[1] - pair[0];
339        if delta > 0.0 {
340            step = step.min(delta);
341        }
342    }
343    if step.is_finite() { step } else { 1.0 }
344}