crisol_plot/plot/measure/
curve.rs1use egui::{Pos2, Rect, pos2, vec2};
4
5use super::{DistanceSummary, MeasurementAreaStyle, PlotMeasurement};
6use crate::plot::scene::{Dash, Measure, Prim, Scene};
7use crate::plot::transform::Transform;
8use crate::plot::{Plot, PlotState};
9use crisol_ui_kit::theme::Theme;
10
11#[derive(Clone, Debug, PartialEq)]
13pub struct CurveAreaSummary {
14 pub series: String,
16 pub area: f64,
18 pub absolute_area: f64,
20 pub chord: DistanceSummary,
22 pub arc_length: f64,
24 pub max_deviation: f64,
26 pub max_deviation_at: [f64; 2],
28}
29
30pub fn curve_area_summary(
32 plot: &Plot<'_>,
33 state: &PlotState,
34 measurement: &PlotMeasurement,
35) -> Option<CurveAreaSummary> {
36 let PlotMeasurement::CurveArea {
37 series,
38 start,
39 end,
40 start_index,
41 end_index,
42 } = measurement
43 else {
44 return None;
45 };
46 let series = plot.visible(state).find(|candidate| candidate.name() == series)?;
47 let data = series.data();
48 if data.len() < 2 {
49 return None;
50 }
51 let max = data.len() - 1;
52 let (low, high) = if start_index <= end_index {
53 ((*start_index).min(max), (*end_index).min(max))
54 } else {
55 ((*end_index).min(max), (*start_index).min(max))
56 };
57 let mut points = data[low..=high]
58 .iter()
59 .copied()
60 .filter(|point| point[0].is_finite() && point[1].is_finite())
61 .collect::<Vec<_>>();
62 if points.len() < 2 {
63 return None;
64 }
65 points.sort_by(|a, b| a[0].total_cmp(&b[0]));
66 let (chord_start, chord_end) = if start[0] <= end[0] { (start, end) } else { (end, start) };
67 let chord = PlotMeasurement::distance(*chord_start, *chord_end).distance_summary()?;
68 let chord_dx = chord_end[0] - chord_start[0];
69 let chord_y = |x: f64| {
70 if chord_dx.abs() <= f64::EPSILON {
71 chord_start[1]
72 } else {
73 chord_start[1] + (x - chord_start[0]) * (chord_end[1] - chord_start[1]) / chord_dx
74 }
75 };
76 let mut area = 0.0;
77 let mut absolute_area = 0.0;
78 let mut arc_length = 0.0;
79 for pair in points.windows(2) {
80 let (a, b) = (pair[0], pair[1]);
81 let dx = b[0] - a[0];
82 let da = a[1] - chord_y(a[0]);
83 let db = b[1] - chord_y(b[0]);
84 let strip = dx * (da + db) * 0.5;
85 area += strip;
86 absolute_area += strip.abs();
87 arc_length += (dx * dx + (b[1] - a[1]).powi(2)).sqrt();
88 }
89 let mut max_deviation = 0.0;
90 let mut max_deviation_at = points[0];
91 for point in &points {
92 let deviation = (point[1] - chord_y(point[0])).abs();
93 if deviation > max_deviation {
94 max_deviation = deviation;
95 max_deviation_at = *point;
96 }
97 }
98 Some(CurveAreaSummary {
99 series: series.name().to_owned(),
100 area,
101 absolute_area,
102 chord,
103 arc_length,
104 max_deviation,
105 max_deviation_at,
106 })
107}
108
109#[allow(clippy::too_many_arguments)]
110pub(super) fn paint(
111 scene: &mut Scene,
112 measure: &Measure,
113 transform: &Transform,
114 plot: &Plot<'_>,
115 state: &PlotState,
116 theme: &Theme,
117 measurement: &PlotMeasurement,
118 offset: egui::Vec2,
119) -> Option<egui::Rect> {
120 let PlotMeasurement::CurveArea {
121 start_index, end_index, ..
122 } = measurement
123 else {
124 return None;
125 };
126 let summary = curve_area_summary(plot, state, measurement)?;
127 let chord_start_data = summary.chord.start;
128 let chord_end_data = summary.chord.end;
129 let chord_dx = chord_end_data[0] - chord_start_data[0];
130 let chord_at = |x: f64| {
131 if chord_dx.abs() <= f64::EPSILON {
132 chord_start_data[1]
133 } else {
134 chord_start_data[1] + (x - chord_start_data[0]) * (chord_end_data[1] - chord_start_data[1]) / chord_dx
135 }
136 };
137 let series = plot.visible(state).find(|series| series.name() == summary.series)?;
138 let data = series.data();
139 let max = data.len().saturating_sub(1);
140 let (low, high) = if start_index <= end_index {
141 ((*start_index).min(max), (*end_index).min(max))
142 } else {
143 ((*end_index).min(max), (*start_index).min(max))
144 };
145 let points = data[low..=high]
146 .iter()
147 .filter(|point| point[0].is_finite() && point[1].is_finite())
148 .map(|point| transform.to_screen(*point))
149 .collect::<Vec<_>>();
150 if points.len() < 2 {
151 return None;
152 }
153 let chord_start = transform.to_screen(summary.chord.start);
154 let chord_end = transform.to_screen(summary.chord.end);
155 let mut polygon = points.clone();
156 polygon.push(chord_end);
157 polygon.push(chord_start);
158 scene.data.push(Prim::Polygon {
159 points: polygon,
160 color: theme.link.gamma_multiply(0.16),
161 });
162 scene.data.push(Prim::Line {
163 points: points.clone(),
164 width: 2.0,
165 color: theme.link,
166 dash: Dash::Solid,
167 });
168 scene.data.push(Prim::Line {
169 points: vec![chord_start, chord_end],
170 width: 1.2,
171 color: theme.warning,
172 dash: Dash::Dashed(5.0, 4.0),
173 });
174 for point in [chord_start, chord_end, transform.to_screen(summary.max_deviation_at)] {
175 scene.data.push(Prim::Circle {
176 center: point,
177 radius: 2.5,
178 fill: theme.warning,
179 stroke: None,
180 });
181 }
182
183 if summary.max_deviation > f64::EPSILON {
186 let peak = summary.max_deviation_at;
187 let base = [peak[0], chord_at(peak[0])];
188 double_arrow(
189 scene,
190 transform.to_screen(base),
191 transform.to_screen(peak),
192 theme.warning,
193 );
194 }
195 if !state.measurement.show_labels {
196 return None;
197 }
198 let area = match state.measurement.area_style {
199 MeasurementAreaStyle::Signed => summary.area,
200 MeasurementAreaStyle::Absolute => summary.absolute_area,
201 };
202 let label = format!(
203 "{} area={} u² |area|={} u²",
204 summary.series,
205 number(area),
206 number(summary.absolute_area)
207 );
208 let chord = format!(
209 "Δx={} Δy={} peak height={} u",
210 number(summary.chord.dx),
211 number(summary.chord.dy),
212 number(summary.max_deviation)
213 );
214 let detail = format!(
215 "peak=({}, {}) chord={} slope={} {}° arc={}",
216 number(summary.max_deviation_at[0]),
217 number(summary.max_deviation_at[1]),
218 number(summary.chord.distance),
219 summary.chord.slope.map_or_else(|| "∞".to_owned(), number),
220 number(summary.chord.angle_deg),
221 number(summary.arc_length)
222 );
223 let at = label_anchor(&points).unwrap_or_else(|| transform.frame.left_top()) + vec2(6.0, 6.0) + offset;
224 Some(super::label_block(
225 scene,
226 measure,
227 at,
228 &[label, chord, detail],
229 theme.link,
230 theme,
231 ))
232}
233
234fn double_arrow(scene: &mut Scene, from: egui::Pos2, to: egui::Pos2, color: egui::Color32) {
235 let direction = to - from;
236 if direction.length_sq() <= 1.0e-6 {
237 return;
238 }
239 scene.data.push(Prim::Line {
240 points: vec![from, to],
241 width: 1.4,
242 color,
243 dash: Dash::Solid,
244 });
245 arrow_head(scene, from, direction.normalized(), color);
246 arrow_head(scene, to, -direction.normalized(), color);
247}
248
249fn arrow_head(scene: &mut Scene, tip: egui::Pos2, direction: egui::Vec2, color: egui::Color32) {
250 let base = tip - direction * 7.0;
251 let side = egui::vec2(-direction.y, direction.x) * 3.0;
252 scene.data.push(Prim::Polygon {
253 points: vec![tip, base + side, base - side],
254 color,
255 });
256}
257
258fn label_anchor(points: &[Pos2]) -> Option<Pos2> {
259 let (mut min, mut max) = (points[0], points[0]);
260 for point in points {
261 min.x = min.x.min(point.x);
262 min.y = min.y.min(point.y);
263 max.x = max.x.max(point.x);
264 max.y = max.y.max(point.y);
265 }
266 let rect = Rect::from_min_max(min, max);
267 Some(pos2(rect.left(), rect.top()))
268}
269
270fn number(value: f64) -> String {
271 super::number(value)
272}