Skip to main content

egui_pop_core/pointer/view/
model.rs

1//! The view model of a zoomable image: what part of the image is shown,
2//! at what zoom, and the one mapping between image and screen that
3//! drawing, hit testing and the gestures use. The image viewport
4//! (`egui_pop_viewport::view` re-exports it) and the library's comparison
5//! share it, so a gesture changes the same [`View`] in each.
6//!
7//! - **Zoom is physical**: [`View::zoom`] counts physical screen pixels
8//!   per image pixel, so 100 % is exactly `1.0` and means one image pixel
9//!   on one pixel of the window's surface, whatever the window's scale.
10//! - **Whole-pixel offsets**: [`Mapping`] snaps the image's origin to a
11//!   whole physical pixel, so at 100 %, at whole zooms (200 %, 300 %) and
12//!   at their inverses no column is repeated or skipped.
13//! - **The ladder**: [`zoom_in`] and [`zoom_out`] walk [`ZOOM_LADDER`];
14//!   the wheel ([`wheel_zoom`]) is continuous but stops at 100 % when it
15//!   crosses it, so exact pixels are always one notch away.
16
17use egui::{Pos2, Rect, Vec2, pos2};
18
19use super::WHEEL_RATE;
20
21/// The zoom steps of [`zoom_in`] and [`zoom_out`], in physical pixels
22/// per image pixel: whole ratios first (100 % is `1.0`).
23pub const ZOOM_LADDER: &[f64] = &[
24    1.0 / 16.0,
25    1.0 / 12.0,
26    1.0 / 8.0,
27    1.0 / 6.0,
28    1.0 / 4.0,
29    1.0 / 3.0,
30    1.0 / 2.0,
31    2.0 / 3.0,
32    1.0,
33    2.0,
34    3.0,
35    4.0,
36    8.0,
37    16.0,
38    32.0,
39];
40
41/// The smallest zoom (a very large image fitted in a small view).
42pub const MIN_ZOOM: f64 = 1.0 / 256.0;
43/// The largest zoom.
44pub const MAX_ZOOM: f64 = 64.0;
45
46/// How the zoom is chosen.
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub enum Zoom {
49    /// The whole image in the view, centred; follows the view's size.
50    Fit,
51    /// Physical screen pixels per image pixel (100 % is `1.0`).
52    Px(f64),
53}
54
55/// What is shown: a zoom and the image point at the centre of the view.
56/// The application owns it (a window, a document); the viewport changes
57/// it through gestures and says so with signals.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct View {
60    pub zoom: Zoom,
61    /// The image point at the centre of the view, in image pixels
62    /// (ignored while fitting).
63    pub center: [f64; 2],
64}
65
66impl Default for View {
67    fn default() -> Self {
68        View::fit()
69    }
70}
71
72impl View {
73    /// The whole image, centred.
74    pub fn fit() -> View {
75        View {
76            zoom: Zoom::Fit,
77            center: [0.0, 0.0],
78        }
79    }
80
81    /// 100 %: one image pixel per physical pixel, around `center`.
82    pub fn actual(center: [f64; 2]) -> View {
83        View {
84            zoom: Zoom::Px(1.0),
85            center,
86        }
87    }
88
89    /// A zoom (clamped to [`MIN_ZOOM`]..[`MAX_ZOOM`]) around `center`.
90    pub fn at(zoom: f64, center: [f64; 2]) -> View {
91        View {
92            zoom: Zoom::Px(zoom.clamp(MIN_ZOOM, MAX_ZOOM)),
93            center,
94        }
95    }
96
97    /// Whether the view follows the window (fit).
98    pub fn is_fit(&self) -> bool {
99        self.zoom == Zoom::Fit
100    }
101
102    /// The same view with fit resolved against a mapping (what is shown,
103    /// as explicit numbers).
104    pub fn resolved(&self, m: &Mapping) -> View {
105        View::at(m.zoom, m.center)
106    }
107}
108
109/// The zoom that shows a whole image in a view of `rect_px` physical
110/// pixels.
111pub fn fit_zoom(image: [f64; 2], rect_px: Vec2) -> f64 {
112    if image[0] <= 0.0 || image[1] <= 0.0 {
113        return 1.0;
114    }
115    (f64::from(rect_px.x) / image[0])
116        .min(f64::from(rect_px.y) / image[1])
117        .clamp(MIN_ZOOM, MAX_ZOOM)
118}
119
120const EPS: f64 = 1e-9;
121
122/// The next ladder step above `zoom` (or [`MAX_ZOOM`]'s step).
123pub fn zoom_in(zoom: f64) -> f64 {
124    ZOOM_LADDER
125        .iter()
126        .copied()
127        .find(|z| *z > zoom * (1.0 + EPS))
128        .unwrap_or(ZOOM_LADDER[ZOOM_LADDER.len() - 1].max(zoom))
129}
130
131/// The next ladder step below `zoom` (or the smallest step).
132pub fn zoom_out(zoom: f64) -> f64 {
133    ZOOM_LADDER
134        .iter()
135        .rev()
136        .copied()
137        .find(|z| *z < zoom * (1.0 - EPS))
138        .unwrap_or(ZOOM_LADDER[0].min(zoom))
139}
140
141/// The zoom after a wheel motion of `points` (positive zooms in): a
142/// continuous factor that stops at exactly 100 % when it crosses it.
143pub fn wheel_zoom(zoom: f64, points: f32) -> f64 {
144    let next = (zoom * (f64::from(points) * WHEEL_RATE).exp()).clamp(MIN_ZOOM, MAX_ZOOM);
145    let crosses = (zoom < 1.0 - EPS && next > 1.0) || (zoom > 1.0 + EPS && next < 1.0);
146    if crosses { 1.0 } else { next }
147}
148
149/// The mapping between image pixels, physical pixels and points for one
150/// frame of one viewport in one window. Build it with [`Mapping::new`];
151/// every conversion of the viewport (drawing, tiles, hit tests, the
152/// readout) goes through it.
153///
154/// Physical pixels are counted from the window's top left corner, as the
155/// GPU draws them; a physical pixel `n` covers `n..n+1` and its centre is
156/// `n + 0.5`.
157#[derive(Clone, Copy, Debug, PartialEq)]
158pub struct Mapping {
159    /// The viewport, in points.
160    pub rect: Rect,
161    /// Physical pixels per point of the window drawing it.
162    pub ppp: f32,
163    /// Physical pixels per image pixel (fit resolved).
164    pub zoom: f64,
165    /// Where image point `(0, 0)` lands, in physical pixels: whole
166    /// numbers.
167    pub origin: [f64; 2],
168    /// The image point at the centre of the view.
169    pub center: [f64; 2],
170    /// The image's size in pixels.
171    pub image: [f64; 2],
172    /// The viewport in physical pixels, rounded: `[x0, y0, x1, y1]`.
173    pub rect_px: [f64; 4],
174}
175
176impl Mapping {
177    /// The mapping of a view of an image (`image`, its size in pixels)
178    /// into `rect` (points) on a window with `ppp` physical pixels per
179    /// point.
180    pub fn new(view: &View, image: [f64; 2], rect: Rect, ppp: f32) -> Mapping {
181        let p = f64::from(ppp);
182        let rect_px = [
183            (f64::from(rect.min.x) * p).round(),
184            (f64::from(rect.min.y) * p).round(),
185            (f64::from(rect.max.x) * p).round(),
186            (f64::from(rect.max.y) * p).round(),
187        ];
188        let size = Vec2::new(
189            (rect_px[2] - rect_px[0]) as f32,
190            (rect_px[3] - rect_px[1]) as f32,
191        );
192        let (zoom, center) = match view.zoom {
193            Zoom::Fit => (fit_zoom(image, size), [image[0] / 2.0, image[1] / 2.0]),
194            Zoom::Px(z) => (z.clamp(MIN_ZOOM, MAX_ZOOM), view.center),
195        };
196        let mid = [
197            (rect_px[0] + rect_px[2]) / 2.0,
198            (rect_px[1] + rect_px[3]) / 2.0,
199        ];
200        let origin = [
201            (mid[0] - center[0] * zoom).round(),
202            (mid[1] - center[1] * zoom).round(),
203        ];
204        Mapping {
205            rect,
206            ppp,
207            zoom,
208            origin,
209            center,
210            image,
211            rect_px,
212        }
213    }
214
215    /// An image point in physical pixels.
216    pub fn image_to_px(&self, p: [f64; 2]) -> [f64; 2] {
217        [
218            self.origin[0] + p[0] * self.zoom,
219            self.origin[1] + p[1] * self.zoom,
220        ]
221    }
222
223    /// A physical position in image pixels.
224    pub fn px_to_image(&self, px: [f64; 2]) -> [f64; 2] {
225        [
226            (px[0] - self.origin[0]) / self.zoom,
227            (px[1] - self.origin[1]) / self.zoom,
228        ]
229    }
230
231    /// An image point on screen, in points.
232    pub fn image_to_screen(&self, p: [f64; 2]) -> Pos2 {
233        let px = self.image_to_px(p);
234        let s = f64::from(self.ppp);
235        pos2((px[0] / s) as f32, (px[1] / s) as f32)
236    }
237
238    /// A screen position (points) in image pixels, continuous.
239    pub fn screen_to_image(&self, pos: Pos2) -> [f64; 2] {
240        let s = f64::from(self.ppp);
241        self.px_to_image([f64::from(pos.x) * s, f64::from(pos.y) * s])
242    }
243
244    /// A rectangle of the image (`[x0, y0, x1, y1]`, image pixels) on
245    /// screen, in points.
246    pub fn image_rect_to_screen(&self, r: [f64; 4]) -> Rect {
247        Rect::from_min_max(
248            self.image_to_screen([r[0], r[1]]),
249            self.image_to_screen([r[2], r[3]]),
250        )
251    }
252
253    /// The image pixel drawn on the physical pixel under `pos` (points),
254    /// or `None` outside the image. This is the drawing's own rule: the
255    /// physical pixel's centre, mapped to the image, floored. The pixel
256    /// readout and the tests use it.
257    pub fn pixel_at(&self, pos: Pos2) -> Option<[i64; 2]> {
258        let s = f64::from(self.ppp);
259        let n = [
260            (f64::from(pos.x) * s).floor() + 0.5,
261            (f64::from(pos.y) * s).floor() + 0.5,
262        ];
263        let p = self.px_to_image(n);
264        let (x, y) = (p[0].floor(), p[1].floor());
265        (x >= 0.0 && y >= 0.0 && x < self.image[0] && y < self.image[1])
266            .then_some([x as i64, y as i64])
267    }
268
269    /// The part of the image in view, clipped to the image:
270    /// `[x0, y0, x1, y1]` in image pixels, or `None` when nothing of it is
271    /// visible.
272    pub fn visible(&self) -> Option<[f64; 4]> {
273        let a = self.px_to_image([self.rect_px[0], self.rect_px[1]]);
274        let b = self.px_to_image([self.rect_px[2], self.rect_px[3]]);
275        let r = [
276            a[0].max(0.0),
277            a[1].max(0.0),
278            b[0].min(self.image[0]),
279            b[1].min(self.image[1]),
280        ];
281        (r[2] > r[0] && r[3] > r[1]).then_some(r)
282    }
283
284    /// The view centred so that image point `at` stays under the screen
285    /// position `pos` at another zoom (zooming around the pointer).
286    pub fn zoom_around(&self, pos: Pos2, zoom: f64) -> View {
287        let zoom = zoom.clamp(MIN_ZOOM, MAX_ZOOM);
288        let s = f64::from(self.ppp);
289        let at = self.screen_to_image(pos);
290        let mid = [
291            (self.rect_px[0] + self.rect_px[2]) / 2.0,
292            (self.rect_px[1] + self.rect_px[3]) / 2.0,
293        ];
294        let offset = [f64::from(pos.x) * s - mid[0], f64::from(pos.y) * s - mid[1]];
295        View::at(zoom, [at[0] - offset[0] / zoom, at[1] - offset[1] / zoom])
296    }
297
298    /// The view moved by a drag of `delta` points (the image follows the
299    /// pointer).
300    pub fn panned(&self, delta: Vec2) -> View {
301        let s = f64::from(self.ppp);
302        View::at(
303            self.zoom,
304            [
305                self.center[0] - f64::from(delta.x) * s / self.zoom,
306                self.center[1] - f64::from(delta.y) * s / self.zoom,
307            ],
308        )
309    }
310}