1use egui::{Color32, Pos2, Rect, Vec2};
4
5use super::axis::Transform;
6use super::math_text::to_unicode_math;
7use super::scene::Prim;
8
9#[derive(Clone, Debug, PartialEq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
13#[non_exhaustive]
14pub enum PlotAnnotation {
15 Text {
17 at: [f64; 2],
19 text: String,
21 size: f32,
23 color: Option<Color32>,
25 },
26 Arrow {
28 from: [f64; 2],
30 to: [f64; 2],
32 color: Option<Color32>,
34 },
35 SpanX {
37 x0: f64,
39 x1: f64,
41 color: Option<Color32>,
43 },
44 SpanY {
46 y0: f64,
48 y1: f64,
50 color: Option<Color32>,
52 },
53 Rect {
55 min: [f64; 2],
57 max: [f64; 2],
59 color: Option<Color32>,
61 fill: Option<Color32>,
63 draggable: bool,
65 },
66 Ellipse {
68 center: [f64; 2],
70 radius: [f64; 2],
72 color: Option<Color32>,
74 fill: Option<Color32>,
76 draggable: bool,
78 },
79 Polygon {
81 points: Vec<[f64; 2]>,
83 color: Option<Color32>,
85 fill: Option<Color32>,
87 draggable: bool,
89 },
90}
91
92impl PlotAnnotation {
93 pub fn text(at: [f64; 2], text: impl Into<String>) -> Self {
95 Self::Text {
96 at,
97 text: text.into(),
98 size: 12.0,
99 color: None,
100 }
101 }
102
103 pub fn arrow(from: [f64; 2], to: [f64; 2]) -> Self {
105 Self::Arrow { from, to, color: None }
106 }
107
108 pub fn rect(min: [f64; 2], max: [f64; 2]) -> Self {
110 Self::Rect {
111 min,
112 max,
113 color: None,
114 fill: Some(Color32::from_white_alpha(20)),
115 draggable: true,
116 }
117 }
118
119 pub fn ellipse(center: [f64; 2], radius: [f64; 2]) -> Self {
121 Self::Ellipse {
122 center,
123 radius,
124 color: None,
125 fill: Some(Color32::from_white_alpha(20)),
126 draggable: true,
127 }
128 }
129
130 pub fn polygon(points: impl IntoIterator<Item = [f64; 2]>) -> Self {
132 Self::Polygon {
133 points: points.into_iter().collect(),
134 color: None,
135 fill: Some(Color32::from_white_alpha(20)),
136 draggable: true,
137 }
138 }
139
140 fn color(&self, theme: &crisol_ui_kit::theme::Theme) -> Color32 {
142 match self {
143 Self::Text { color, .. }
144 | Self::Arrow { color, .. }
145 | Self::Rect { color, .. }
146 | Self::Ellipse { color, .. }
147 | Self::Polygon { color, .. } => color.unwrap_or(theme.link),
148 Self::SpanX { color, .. } | Self::SpanY { color, .. } => color.unwrap_or(theme.warning),
149 }
150 }
151}
152
153pub(super) fn paint(
155 out: &mut Vec<Prim>,
156 transform: &Transform,
157 annotations: &[PlotAnnotation],
158 theme: &crisol_ui_kit::theme::Theme,
159) {
160 let frame = transform.frame;
161 for annotation in annotations {
162 let color = annotation.color(theme);
163 match annotation {
164 PlotAnnotation::Text { at, text, size, .. } => {
165 let position = transform.to_screen(*at);
166 if position.is_finite() {
167 out.push(Prim::Text {
168 pos: position,
169 text: to_unicode_math(text),
170 size: *size,
171 color,
172 baseline: size * 0.8,
173 angle: 0.0,
174 });
175 }
176 }
177 PlotAnnotation::Arrow { from, to, .. } => {
178 let start = transform.to_screen(*from);
179 let end = transform.to_screen(*to);
180 if start.is_finite() && end.is_finite() {
181 out.push(Prim::Line {
182 points: vec![start, end],
183 width: 1.5,
184 color,
185 dash: super::scene::Dash::Solid,
186 });
187 let direction = (end - start).normalized();
188 let normal = Vec2::new(-direction.y, direction.x);
189 let tip = end;
190 let left = end - direction * 9.0 + normal * 4.0;
191 let right = end - direction * 9.0 - normal * 4.0;
192 out.push(Prim::Polygon {
193 points: vec![tip, left, right],
194 color,
195 });
196 }
197 }
198 PlotAnnotation::SpanX { x0, x1, .. } => {
199 let a = transform.to_screen([*x0, transform.view.min_y]);
200 let b = transform.to_screen([*x1, transform.view.max_y]);
201 let rect = Rect::from_two_pos(a, b).intersect(frame);
202 if rect.is_positive() {
203 out.push(Prim::Rect {
204 rect,
205 radius: 0.0,
206 fill: color.gamma_multiply(0.12),
207 stroke: Some((1.0, color.gamma_multiply(0.7))),
208 });
209 }
210 }
211 PlotAnnotation::SpanY { y0, y1, .. } => {
212 let a = transform.to_screen([transform.view.min_x, *y0]);
213 let b = transform.to_screen([transform.view.max_x, *y1]);
214 let rect = Rect::from_two_pos(a, b).intersect(frame);
215 if rect.is_positive() {
216 out.push(Prim::Rect {
217 rect,
218 radius: 0.0,
219 fill: color.gamma_multiply(0.12),
220 stroke: Some((1.0, color.gamma_multiply(0.7))),
221 });
222 }
223 }
224 PlotAnnotation::Rect { min, max, fill, .. } => {
225 let a = transform.to_screen(*min);
226 let b = transform.to_screen(*max);
227 let rect = Rect::from_two_pos(a, b).intersect(frame);
228 if rect.is_positive() {
229 out.push(Prim::Rect {
230 rect,
231 radius: 0.0,
232 fill: fill.unwrap_or(Color32::TRANSPARENT),
233 stroke: Some((1.5, color)),
234 });
235 }
236 }
237 PlotAnnotation::Ellipse {
238 center, radius, fill, ..
239 } => {
240 let center = transform.to_screen(*center);
241 let rx = (transform
242 .to_screen([f64::from(center.x) + radius[0], f64::from(center.y)])
243 .x
244 - center.x)
245 .abs();
246 let ry = (transform
247 .to_screen([f64::from(center.x), f64::from(center.y) + radius[1]])
248 .y
249 - center.y)
250 .abs();
251 if center.is_finite() && rx > 0.5 && ry > 0.5 {
252 let points: Vec<Pos2> = (0..48)
253 .map(|index| {
254 let angle = index as f32 / 48.0 * std::f32::consts::TAU;
255 Pos2::new(center.x + rx * angle.cos(), center.y + ry * angle.sin())
256 })
257 .collect();
258 out.push(Prim::Polygon {
259 points: points.clone(),
260 color: fill.unwrap_or(Color32::TRANSPARENT),
261 });
262 for pair in points.windows(2) {
263 out.push(Prim::Line {
264 points: pair.to_vec(),
265 width: 1.5,
266 color,
267 dash: super::scene::Dash::Solid,
268 });
269 }
270 }
271 }
272 PlotAnnotation::Polygon { points, fill, .. } => {
273 let points: Vec<Pos2> = points
274 .iter()
275 .map(|point| transform.to_screen(*point))
276 .filter(|point| point.is_finite())
277 .collect();
278 if points.len() >= 3 {
279 out.push(Prim::Polygon {
280 points: points.clone(),
281 color: fill.unwrap_or(Color32::TRANSPARENT),
282 });
283 for index in 0..points.len() {
284 out.push(Prim::Line {
285 points: vec![points[index], points[(index + 1) % points.len()]],
286 width: 1.5,
287 color,
288 dash: super::scene::Dash::Solid,
289 });
290 }
291 }
292 }
293 }
294 }
295}
296
297pub fn region_size(min: [f64; 2], max: [f64; 2]) -> [f64; 2] {
299 [(max[0] - min[0]).abs(), (max[1] - min[1]).abs()]
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::plot::{Bounds, Scale};
306 use egui::{Rect, pos2};
307
308 fn transform() -> Transform {
309 Transform {
310 frame: Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)),
311 view: Bounds::from_corners([0.0, 0.0], [10.0, 10.0]),
312 x_scale: Scale::Linear,
313 y_scale: Scale::Linear,
314 y2: None,
315 }
316 }
317
318 #[test]
319 fn annotations_become_prims() {
320 let theme = crisol_ui_kit::theme::Theme::dark();
321 let mut prims = Vec::new();
322 let annotations = vec![
323 PlotAnnotation::text([1.0, 1.0], r"$\alpha$"),
324 PlotAnnotation::arrow([1.0, 1.0], [5.0, 5.0]),
325 PlotAnnotation::rect([2.0, 2.0], [4.0, 4.0]),
326 PlotAnnotation::ellipse([5.0, 5.0], [1.0, 2.0]),
327 PlotAnnotation::polygon([[1.0, 2.0], [3.0, 2.0], [2.0, 4.0]]),
328 ];
329 paint(&mut prims, &transform(), &annotations, &theme);
330 assert!(prims.len() > 5);
331 assert!(prims.iter().any(|prim| matches!(prim, Prim::Text { .. })));
332 }
333
334 #[test]
335 fn regions_have_serializable_geometry() {
336 assert_eq!(region_size([0.0, 0.0], [2.0, 3.0]), [2.0, 3.0]);
337 }
338}