1mod analysis;
31mod animation;
32mod annotations;
33mod axis;
34mod builder;
35mod chart_config;
36mod colormap;
37mod config;
38mod dataset;
39mod decimate;
40mod direction;
41mod export;
42mod extra;
43mod families;
44mod filter;
45mod fit;
46#[cfg(feature = "gpu")]
47mod gpu;
48#[cfg(feature = "gpu")]
49mod gpu_line;
50mod grid;
51mod history;
52mod interact;
53mod layout;
54mod legend;
55mod math_text;
56mod measure;
57mod overlay;
58mod paint;
59mod pdf;
60mod pipeline;
61mod scene;
62mod series;
63mod series_bounds;
64mod series_charts;
65mod smooth;
66mod snap;
67mod special;
68mod three;
69mod transform;
70mod transforms;
71mod types;
72mod widgets;
73pub use analysis::{
74 Complex, Model, ModelFit, Peak, Statistics, derivative, fft, find_peaks, fit_model, integral, remove_baseline,
75 resample, rolling_baseline, savgol, savgol_derivative, spectrum,
76};
77pub use animation::{AnimationEasing, LegendAnimation, LegendHoverConfig};
78pub use annotations::{PlotAnnotation, region_size};
79pub use axis::{Bounds, Scale};
80use axis::{SecondAxis, Transform};
81pub use chart_config::{DirectionArrowConfig, GaugeConfig, HeatmapConfig, PieConfig, RadarConfig, WaterfallConfig};
82pub use colormap::Colormap;
83pub use config::{AxisConfig, Minor, PlotColors, PlotConfig, Renderer, SeriesStyle, TitleAlign};
84use crisol_ui_kit::Icons;
85use crisol_ui_kit::components::IconComponent;
86pub use dataset::{DatasetPlot, DatasetPlotKind};
87use egui::{Color32, Id, Pos2, Rect, Sense, Ui, vec2};
88pub use export::{ExportOptions, ExportPreset};
89pub use families::{box_plot, contour, hexbin, histogram, histogram_density, polar, show_colorbar, smith, violin};
90pub use filter::{FilterKind, FilterSettings};
91pub use fit::{Fit, FitKind};
92#[cfg(feature = "gpu")]
93pub use gpu::set_output_format;
94pub use grid::PlotGrid;
95pub use history::ViewHistory;
96pub use math_text::to_unicode_math;
97pub use measure::{
98 CurveAreaSummary, DistanceSummary, Extremum, MeasurementAreaStyle, MeasurementConfig, MeasurementMode,
99 PlotMeasurement, SeriesMeasurement, curve_area_summary, region_measurements,
100};
101pub use pipeline::{Pipeline, PipelineSeries};
102use scene::Measure;
103pub use series::{LineStyle, Marker, Series, Smoothing, YAxis, points_in};
104pub use three::{
105 Bounds3D, Camera3D, Plot3D, Plot3DConfig, Plot3DHover, Plot3DResponse, Plot3DState, Plot3DTool, Projection,
106 Series3D, Series3DStyle, Surface, Surface3DConfig,
107};
108pub use transforms::{TransformKind, TransformSettings};
109use types::Drag;
110pub use types::{ChartMode, ExportFormat, LegendPosition, PlotHover, PlotResponse, PlotTool};
111
112mod state;
113
114pub use state::PlotState;
115
116#[derive(Clone)]
141pub struct Plot<'a> {
142 id: Id,
143 series: Vec<Series<'a>>,
144 config: PlotConfig,
145 width: Option<f32>,
146 height: Option<f32>,
147 x_window: Option<f64>,
148 include: Bounds,
149 settings_button: bool,
150 export_button: bool,
151}
152
153impl<'a> Plot<'a> {
154 pub(super) fn visible<'s>(&'s self, state: &'s PlotState) -> impl Iterator<Item = &'s Series<'a>> {
155 self.series.iter().filter(|series| !state.is_hidden(&series.name))
156 }
157
158 pub fn chart_mode(&self) -> ChartMode {
161 let mut mode = ChartMode::Cartesian;
162 for series in &self.series {
163 match series.kind {
164 series::Kind::Pie { .. } => return ChartMode::Pie,
165 series::Kind::Radar if mode == ChartMode::Cartesian => mode = ChartMode::Radar,
166 series::Kind::Gauge { .. } if mode == ChartMode::Cartesian => mode = ChartMode::Gauge,
167 _ => {}
168 }
169 }
170 mode
171 }
172
173 pub(super) fn draws_direction(&self, index: usize) -> bool {
175 self.config
176 .series_style(&self.series[index].name)
177 .and_then(|style| style.direction_arrow)
178 .unwrap_or(self.config.direction.enabled)
179 }
180
181 fn axis_of(&self, series: &Series<'_>) -> YAxis {
183 self.config
184 .series_style(&series.name)
185 .and_then(|style| style.y_axis)
186 .unwrap_or(series.axis)
187 }
188
189 fn has_y2(&self) -> bool {
192 self.series.iter().any(|series| self.axis_of(series) == YAxis::Right)
193 }
194
195 fn materialize_lod(&mut self, state: &PlotState) {
199 let view = state.view();
200 for series in &mut self.series {
201 let Some((pyramid, budget)) = &series.lod else {
202 continue;
203 };
204 let points = match view {
205 Some(bounds) => pyramid.polyline_in_x(bounds.min_x, bounds.max_x, *budget),
206 None => pyramid.polyline(0..pyramid.row_count(), *budget),
207 };
208 if let Ok(points) = points {
209 series.data = std::borrow::Cow::Owned(points);
210 }
211 }
212 }
213
214 fn refresh_extents(&self, state: &mut PlotState) {
217 let mut extents = Vec::with_capacity(self.series.len());
218 for series in &self.series {
219 let y_scale = match self.axis_of(series) {
220 YAxis::Left => self.config.y.scale,
221 YAxis::Right => self.config.y2.scale,
222 };
223 let key = series.fingerprint(self.config.x.scale, y_scale);
224 let bounds = state
225 .extents
226 .iter()
227 .find(|(cached, _)| *cached == key)
228 .map_or_else(|| series.bounds(self.config.x.scale, y_scale), |(_, bounds)| *bounds);
229 extents.push((key, bounds));
230 }
231 state.extents = extents;
232 }
233
234 fn second_axis(&self, state: &PlotState) -> Option<SecondAxis> {
235 if !self.has_y2() {
236 return None;
237 }
238 let [min, max] = state.y2_view.unwrap_or_else(|| self.auto_y2(state));
239 Some(SecondAxis {
240 min,
241 max,
242 scale: self.config.y2.scale,
243 })
244 }
245}
246
247impl Plot<'_> {
248 pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
250 if state.pipeline.is_active() {
251 let series = state.pipeline.process(&self.series);
252 if !series.is_empty() {
253 let processed = Plot {
254 id: self.id,
255 series,
256 config: self.config,
257 width: self.width,
258 height: self.height,
259 x_window: self.x_window,
260 include: self.include,
261 settings_button: self.settings_button,
262 export_button: self.export_button,
263 };
264 return processed.show_inner(ui, icons, state);
265 }
266 }
267 self.show_inner(ui, icons, state)
268 }
269
270 fn show_inner(mut self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
271 self.materialize_lod(state);
272 if !state.measurement_customized {
273 state.measurement = self.config.measurement;
274 }
275 let available = ui.available_size();
276 let width = self.width.unwrap_or(available.x).max(120.0);
277 let height = self
278 .height
279 .unwrap_or(if available.y.is_finite() && available.y < 4000.0 {
280 available.y
281 } else {
282 320.0
283 })
284 .max(120.0);
285 let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click_and_drag());
286 let measure = Measure {
287 ctx: ui.ctx().clone(),
288 pixels_per_point: ui.ctx().pixels_per_point(),
289 };
290 self.refresh_extents(state);
291 let view = state.view.unwrap_or_else(|| self.auto_bounds(state));
292 let y2 = self.second_axis(state);
293 let mode = self.chart_mode();
294 let layout = overlay::layout(&measure, &self.config, rect, view, y2, mode);
295 let transform = Transform {
296 frame: layout.frame,
297 view,
298 x_scale: self.config.x.scale,
299 y_scale: self.config.y.scale,
300 y2,
301 };
302
303 let mut selection_changed = false;
304 let pointer = response.hover_pos().filter(|pos| layout.frame.contains(*pos));
305 if mode == ChartMode::Cartesian {
306 self.interact(ui, &response, &transform, state, pointer, &mut selection_changed);
307 } else if pointer.is_some() {
308 ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
309 }
310 let view = state.view.unwrap_or(view);
312 let y2 = y2.map(|axis| match state.y2_view {
313 Some([min, max]) => SecondAxis { min, max, ..axis },
314 None => axis,
315 });
316 let transform = Transform { view, y2, ..transform };
317
318 let now = ui.input(|input| input.time);
321 let legend = if let Some(legend) = legend::layout(&measure, &self, layout.frame, state, true) {
322 Some(widgets::legend(ui, &self, &legend, layout.frame, state))
323 } else {
324 state.set_legend_hover(None, now);
325 None
326 };
327 let motion = crisol_ui_kit::theme::motion_enabled(ui.ctx());
328 let theme = crisol_ui_kit::theme::current(ui.ctx());
329 let colors = overlay::Colors::resolve(&self.config, ui.visuals());
330 let mut scene = overlay::build_scene(
331 &measure,
332 &self,
333 &layout,
334 &transform,
335 state,
336 &colors,
337 &theme,
338 false,
339 mode,
340 now,
341 motion,
342 {
343 #[cfg(feature = "gpu")]
344 {
345 self.config.renderer == Renderer::Gpu
346 }
347 #[cfg(not(feature = "gpu"))]
348 {
349 false
350 }
351 },
352 );
353 let drawn = std::mem::take(&mut scene.drawn);
355 annotations::paint(&mut scene.data, &transform, &state.annotations, &theme);
356 state.label_rects = measure::paint(&mut scene, &measure, &transform, &self, state, &theme);
357 let painter = ui.painter_at(rect);
358 #[cfg(feature = "gpu")]
359 let gpu = self.config.renderer == Renderer::Gpu;
360 #[cfg(feature = "gpu")]
361 if gpu {
362 let lines = gpu::collect(&self, &transform, state, &theme);
363 gpu::paint_lines(ui, layout.frame, &lines, self.id);
364 let triangles = gpu::scene_triangles(&mut scene);
365 gpu::paint_triangles(ui, layout.frame, &triangles, self.id);
366 }
367 scene::paint(&painter, &painter.with_clip_rect(layout.frame), scene);
368 if let (Some(Drag::Box { start, select }), Some(current)) = (state.drag, response.interact_pointer_pos()) {
369 let fill = colors.selection.gamma_multiply(if select { 0.12 } else { 0.06 });
370 painter.with_clip_rect(layout.frame).rect(
371 Rect::from_two_pos(start, current).intersect(layout.frame),
372 0.0,
373 fill,
374 egui::Stroke::new(1.0, colors.selection),
375 egui::StrokeKind::Inside,
376 );
377 }
378 if let (Some(Drag::Measure { start, distance }), Some(current)) = (state.drag, response.interact_pointer_pos())
379 {
380 let clipped = painter.with_clip_rect(layout.frame);
381 if distance || state.measurement.mode == MeasurementMode::CurveSegment {
382 clipped.line_segment([start, current], egui::Stroke::new(1.0, colors.selection));
383 } else {
384 clipped.rect(
385 Rect::from_two_pos(start, current).intersect(layout.frame),
386 0.0,
387 colors.selection.gamma_multiply(0.06),
388 egui::Stroke::new(1.0, colors.selection),
389 egui::StrokeKind::Inside,
390 );
391 }
392 }
393
394 let toolbar = widgets::toolbar(ui, icons, &self, layout.frame, &transform, state);
395 let blocked = |pos: Pos2| {
396 legend.is_some_and(|rect| rect.contains(pos)) || toolbar.rect.is_some_and(|rect| rect.contains(pos))
397 };
398 if state.drag.is_none() && toolbar.rect.zip(pointer).is_some_and(|(rect, pos)| rect.contains(pos)) {
399 ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
401 }
402 let hovered = pointer
403 .filter(|pos| !blocked(*pos) && state.drag.is_none())
404 .and_then(|pointer| {
405 (mode == ChartMode::Cartesian)
406 .then(|| self.hover(ui, &transform, state, pointer, &theme, &drawn))
407 .flatten()
408 });
409
410 let clicked = if response.clicked() && state.drag.is_none() {
411 hovered.clone()
412 } else {
413 None
414 };
415 if response.clicked() && state.tool == PlotTool::Select && hovered.is_none() && state.selection.is_some() {
416 state.selection = None;
417 selection_changed = true;
418 }
419
420 let (x_scale, y_scale) = (self.config.x.scale, self.config.y.scale);
421 let data_view = Bounds::from_corners(
422 [x_scale.inverse(view.min_x), y_scale.inverse(view.min_y)],
423 [x_scale.inverse(view.max_x), y_scale.inverse(view.max_y)],
424 );
425 PlotResponse {
426 response,
427 pointer: pointer.map(|pos| transform.to_data(pos)),
428 hovered,
429 clicked,
430 selection_changed,
431 view: data_view,
432 y2_view: y2.map(|axis| [axis.scale.inverse(axis.min), axis.scale.inverse(axis.max)]),
433 frame: transform.frame,
434 settings_requested: toolbar.settings,
435 export_requested: toolbar.export,
436 transform,
437 }
438 }
439}
440
441fn palette(theme: &crisol_ui_kit::theme::Theme, index: usize) -> Color32 {
443 let colors = [
444 theme.link,
445 theme.warning,
446 theme.success,
447 theme.danger,
448 theme.done,
449 Color32::from_rgb(0x1f, 0xb5, 0xb5),
450 Color32::from_rgb(0xd9, 0x5d, 0xb4),
451 Color32::from_rgb(0x8c, 0x8c, 0x3c),
452 ];
453 colors[index % colors.len()]
454}
455
456impl IconComponent for Plot<'_> {
457 type Output = PlotResponse;
458
459 fn show(self, ui: &mut Ui, icons: &mut Icons) -> PlotResponse {
460 let id = self.id;
461 let mut state = ui
462 .ctx()
463 .data_mut(|data| data.get_temp::<PlotState>(id).unwrap_or_default());
464 let response = Plot::show(self, ui, icons, &mut state);
465 ui.ctx().data_mut(|data| data.insert_temp(id, state));
466 response
467 }
468}
469
470#[cfg(test)]
471mod tests;