Skip to main content

crisol_plot_core/
transform.rs

1//! A data ↔ screen transform in plain numbers, with no egui types.
2
3use crisol_core::data::Bounds;
4
5use super::axis::Scale;
6
7/// A point in screen coordinates (points, origin at the top-left).
8#[derive(Clone, Copy, Debug, Default, PartialEq)]
9pub struct ScreenPoint {
10    /// Horizontal position.
11    pub x: f32,
12    /// Vertical position.
13    pub y: f32,
14}
15
16impl ScreenPoint {
17    /// The origin.
18    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
19
20    /// A point at `x`, `y`.
21    pub fn new(x: f32, y: f32) -> Self {
22        Self { x, y }
23    }
24
25    /// Whether both coordinates are finite.
26    pub fn is_finite(self) -> bool {
27        self.x.is_finite() && self.y.is_finite()
28    }
29
30    /// The Euclidean distance to `other`.
31    pub fn distance(self, other: Self) -> f32 {
32        ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
33    }
34
35    /// The squared Euclidean distance to `other`.
36    pub fn distance_sq(self, other: Self) -> f32 {
37        (self.x - other.x).powi(2) + (self.y - other.y).powi(2)
38    }
39
40    /// The squared length of the vector.
41    pub fn length_sq(self) -> f32 {
42        self.x * self.x + self.y * self.y
43    }
44
45    /// The dot product with `other`.
46    pub fn dot(self, other: Self) -> f32 {
47        self.x * other.x + self.y * other.y
48    }
49}
50
51impl std::ops::Sub for ScreenPoint {
52    type Output = Self;
53
54    fn sub(self, other: Self) -> Self {
55        Self::new(self.x - other.x, self.y - other.y)
56    }
57}
58
59impl std::ops::Mul<f32> for ScreenPoint {
60    type Output = Self;
61
62    fn mul(self, factor: f32) -> Self {
63        Self::new(self.x * factor, self.y * factor)
64    }
65}
66
67/// A rectangle in screen coordinates.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct ScreenRect {
70    /// The top-left corner.
71    pub min: ScreenPoint,
72    /// The bottom-right corner.
73    pub max: ScreenPoint,
74}
75
76impl ScreenRect {
77    /// A rectangle from two opposite corners in any order.
78    pub fn from_min_max(a: ScreenPoint, b: ScreenPoint) -> Self {
79        Self {
80            min: ScreenPoint::new(a.x.min(b.x), a.y.min(b.y)),
81            max: ScreenPoint::new(a.x.max(b.x), a.y.max(b.y)),
82        }
83    }
84
85    /// A rectangle from its top-left corner and size.
86    pub fn from_min_size(min: ScreenPoint, width: f32, height: f32) -> Self {
87        Self {
88            min,
89            max: ScreenPoint::new(min.x + width, min.y + height),
90        }
91    }
92
93    /// The left edge.
94    pub fn left(self) -> f32 {
95        self.min.x
96    }
97
98    /// The right edge.
99    pub fn right(self) -> f32 {
100        self.max.x
101    }
102
103    /// The top edge.
104    pub fn top(self) -> f32 {
105        self.min.y
106    }
107
108    /// The bottom edge.
109    pub fn bottom(self) -> f32 {
110        self.max.y
111    }
112
113    /// The width.
114    pub fn width(self) -> f32 {
115        self.max.x - self.min.x
116    }
117
118    /// The height.
119    pub fn height(self) -> f32 {
120        self.max.y - self.min.y
121    }
122
123    /// The center of the rectangle.
124    pub fn center(self) -> ScreenPoint {
125        ScreenPoint::new((self.min.x + self.max.x) * 0.5, (self.min.y + self.max.y) * 0.5)
126    }
127
128    /// Whether the rectangle has a positive area.
129    pub fn is_positive(self) -> bool {
130        self.width() > 0.0 && self.height() > 0.0
131    }
132
133    /// Whether `point` lies inside the rectangle (edges included).
134    pub fn contains(self, point: ScreenPoint) -> bool {
135        point.x >= self.min.x && point.x <= self.max.x && point.y >= self.min.y && point.y <= self.max.y
136    }
137
138    /// The rectangle grown by `amount` on every side.
139    pub fn expand(self, amount: f32) -> Self {
140        Self {
141            min: ScreenPoint::new(self.min.x - amount, self.min.y - amount),
142            max: ScreenPoint::new(self.max.x + amount, self.max.y + amount),
143        }
144    }
145}
146
147/// Which vertical axis a series is measured against.
148#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
149#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
150#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
151pub enum YAxis {
152    /// The primary axis on the left.
153    #[default]
154    Left,
155    /// The secondary axis on the right; it appears as soon as one series uses it.
156    Right,
157}
158
159/// Maps data to screen and back. Works in "scaled" space (log10 already applied), so
160/// zoom and pan are linear in what the user sees.
161#[derive(Clone, Copy, Debug)]
162pub struct Transform {
163    /// The data area on screen.
164    pub frame: ScreenRect,
165    /// Visible range in scaled units.
166    pub view: Bounds,
167    /// The horizontal scale.
168    pub x_scale: Scale,
169    /// The left vertical scale.
170    pub y_scale: Scale,
171    /// The right axis: its visible range in scaled units, and its scale.
172    pub y2: Option<SecondAxis>,
173}
174
175/// The visible range of the right y axis, in scaled units.
176#[derive(Clone, Copy, Debug, PartialEq)]
177pub struct SecondAxis {
178    /// Lower bound in scaled units.
179    pub min: f64,
180    /// Upper bound in scaled units.
181    pub max: f64,
182    /// The axis scale.
183    pub scale: Scale,
184}
185
186impl Transform {
187    /// The transform for series on `axis`: the right axis swaps in its range and scale.
188    pub fn for_axis(self, axis: YAxis) -> Self {
189        match (axis, self.y2) {
190            (YAxis::Right, Some(y2)) => Self {
191                view: Bounds {
192                    min_y: y2.min,
193                    max_y: y2.max,
194                    ..self.view
195                },
196                y_scale: y2.scale,
197                ..self
198            },
199            _ => self,
200        }
201    }
202
203    /// Map a data point to screen coordinates.
204    pub fn to_screen(self, point: [f64; 2]) -> ScreenPoint {
205        let x = self.x_scale.forward(point[0]);
206        let y = self.y_scale.forward(point[1]);
207        self.scaled_to_screen(x, y)
208    }
209
210    /// Map scaled coordinates to screen coordinates.
211    pub fn scaled_to_screen(&self, x: f64, y: f64) -> ScreenPoint {
212        let tx = (x - self.view.min_x) / self.view.width();
213        let ty = (y - self.view.min_y) / self.view.height();
214        ScreenPoint::new(
215            self.frame.left() + (tx * f64::from(self.frame.width())) as f32,
216            self.frame.bottom() - (ty * f64::from(self.frame.height())) as f32,
217        )
218    }
219
220    /// Map a screen position to scaled coordinates.
221    pub fn to_scaled(self, pos: ScreenPoint) -> [f64; 2] {
222        let tx = f64::from((pos.x - self.frame.left()) / self.frame.width());
223        let ty = f64::from((self.frame.bottom() - pos.y) / self.frame.height());
224        [
225            self.view.min_x + tx * self.view.width(),
226            self.view.min_y + ty * self.view.height(),
227        ]
228    }
229
230    /// Map a screen position to data coordinates.
231    pub fn to_data(self, pos: ScreenPoint) -> [f64; 2] {
232        let [x, y] = self.to_scaled(pos);
233        [self.x_scale.inverse(x), self.y_scale.inverse(y)]
234    }
235
236    /// Data units per screen point, in scaled space.
237    pub fn units_per_point(&self) -> [f64; 2] {
238        [
239            self.view.width() / f64::from(self.frame.width().max(1.0)),
240            self.view.height() / f64::from(self.frame.height().max(1.0)),
241        ]
242    }
243}