Skip to main content

egui_pop_viewport/
loupe.rs

1//! The loupe: the pixels under the pointer, magnified, in a square that
2//! follows it.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! It shows **displayed pixels**: the viewport's own tile textures,
8//! after the display transform, drawn again through a magnifying
9//! mapping and clipped to the loupe. On the GPU path the half-float
10//! tiles are sampled in a second paint callback (the same shader, its
11//! own uniforms), with no read back to the CPU; on the CPU path the
12//! tiles' egui textures (nearest filtering) are drawn again. Each
13//! displayed pixel (an image pixel from 100 % up, a screen pixel below)
14//! becomes a square of `magnification` points, crisp, with an optional
15//! grid, a marker around the centre pixel and a readout of its values:
16//! as displayed (RGB, 0 to 255, and Lab) or as the source gave them
17//! (the scene values).
18//!
19//! The loupe sits beside the pointer, above and to the right, and flips
20//! at the viewport's edges. It is turned on by the application (a tool
21//! option: [`ViewportState::loupe_mut`](crate::ViewportState::loupe_mut))
22//! or by a key ([`Loupe::key`]); the viewport signals each toggle
23//! ([`Signal::Loupe`](crate::Signal::Loupe)).
24
25use egui::{Key, Pos2, Rect, Vec2, pos2, vec2};
26
27use crate::display::Stage;
28use crate::source::Readout;
29use crate::view::Mapping;
30
31/// The smallest magnification.
32pub const MIN_MAGNIFICATION: u32 = 4;
33/// The largest magnification.
34pub const MAX_MAGNIFICATION: u32 = 16;
35
36/// What the loupe's readout shows.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub enum Values {
39    /// No readout.
40    Off,
41    /// The values as displayed: RGB (0 to 255) and Lab, through the
42    /// display transform.
43    #[default]
44    Display,
45    /// The values the source gave (scene-referred, as named by it).
46    Scene,
47}
48
49impl Values {
50    pub fn name(self) -> &'static str {
51        match self {
52            Values::Off => "off",
53            Values::Display => "display",
54            Values::Scene => "scene",
55        }
56    }
57}
58
59/// A viewport's loupe settings.
60#[derive(Clone, Copy, Debug, PartialEq)]
61pub struct Loupe {
62    /// Shown while the pointer is over the viewport.
63    pub on: bool,
64    /// The side of one displayed pixel in the loupe, in points: 4 to 16.
65    pub magnification: u32,
66    /// The side of the loupe's picture, in points.
67    pub side: f32,
68    /// Lines between the displayed pixels.
69    pub grid: bool,
70    /// A square around the centre pixel (the one under the pointer).
71    pub marker: bool,
72    pub values: Values,
73    /// The key that turns it on and off while the viewport is hovered or
74    /// focused (`None`: no key; the application toggles `on`).
75    pub key: Option<Key>,
76    /// The space between the pointer and the loupe, in points.
77    pub offset: f32,
78}
79
80impl Default for Loupe {
81    fn default() -> Self {
82        Loupe {
83            on: false,
84            magnification: 8,
85            side: 144.0,
86            grid: true,
87            marker: true,
88            values: Values::Display,
89            key: None,
90            offset: 24.0,
91        }
92    }
93}
94
95impl Loupe {
96    /// The magnification, within 4 to 16.
97    pub fn magnification(&self) -> u32 {
98        self.magnification
99            .clamp(MIN_MAGNIFICATION, MAX_MAGNIFICATION)
100    }
101}
102
103/// Where a loupe of `size` goes for a pointer: `offset` points above and
104/// to the right of it, flipped to the left at the right edge of
105/// `bounds` and below at its top, and kept inside when it does not fit
106/// either way.
107pub fn place(pointer: Pos2, size: Vec2, bounds: Rect, offset: f32) -> Rect {
108    let mut x = pointer.x + offset;
109    if x + size.x > bounds.right() {
110        x = pointer.x - offset - size.x;
111    }
112    let mut y = pointer.y - offset - size.y;
113    if y < bounds.top() {
114        y = pointer.y + offset;
115    }
116    let x = x.clamp(bounds.left(), (bounds.right() - size.x).max(bounds.left()));
117    let y = y.clamp(bounds.top(), (bounds.bottom() - size.y).max(bounds.top()));
118    Rect::from_min_size(pos2(x, y), size)
119}
120
121/// How the loupe magnifies: what is at window physical pixel `p` lands
122/// at `at + (p - center) × scale`.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct Sampling {
125    /// The centre of the displayed pixel under the pointer, in window
126    /// physical pixels.
127    pub center: [f64; 2],
128    /// The side of a displayed pixel on screen, in physical pixels: the
129    /// zoom from 100 % up (an image pixel), else 1 (a screen pixel).
130    pub texel: f64,
131    /// The side of a displayed pixel in the loupe, in physical pixels: a
132    /// whole number.
133    pub block: f64,
134    /// The loupe's centre, in window physical pixels, placed so that its
135    /// blocks fall on whole pixels.
136    pub at: [f64; 2],
137    /// The image pixel under the pointer, when over the image.
138    pub pixel: Option<[i64; 2]>,
139}
140
141impl Sampling {
142    /// The sampling for a pointer (points) over a mapping, at a
143    /// magnification, the loupe centred near `loupe_center` (points).
144    pub fn new(m: &Mapping, pointer: Pos2, magnification: u32, loupe_center: Pos2) -> Sampling {
145        let ppp = f64::from(m.ppp);
146        let p = [f64::from(pointer.x) * ppp, f64::from(pointer.y) * ppp];
147        let screen = [p[0].floor() + 0.5, p[1].floor() + 0.5];
148        let pixel = m.pixel_at(pointer);
149        let (center, texel) = if m.zoom >= 1.0 {
150            let i = m.px_to_image(screen);
151            let c = m.image_to_px([i[0].floor() + 0.5, i[1].floor() + 0.5]);
152            (c, m.zoom)
153        } else {
154            (screen, 1.0)
155        };
156        let block = (f64::from(magnification) * ppp).round().max(1.0);
157        let raw = [
158            f64::from(loupe_center.x) * ppp,
159            f64::from(loupe_center.y) * ppp,
160        ];
161        let snap = |v: f64| (v - block / 2.0).round() + block / 2.0;
162        Sampling {
163            center,
164            texel,
165            block,
166            at: [snap(raw[0]), snap(raw[1])],
167            pixel,
168        }
169    }
170
171    /// Loupe pixels per screen pixel.
172    pub fn scale(&self) -> f64 {
173        self.block / self.texel
174    }
175
176    /// A window physical position, magnified into the loupe.
177    pub fn map(&self, p: [f64; 2]) -> [f64; 2] {
178        let s = self.scale();
179        [
180            self.at[0] + (p[0] - self.center[0]) * s,
181            self.at[1] + (p[1] - self.center[1]) * s,
182        ]
183    }
184
185    /// A rectangle in window physical pixels (`[x0, y0, x1, y1]`),
186    /// magnified into the loupe.
187    pub fn map_rect(&self, r: [f64; 4]) -> [f64; 4] {
188        let a = self.map([r[0], r[1]]);
189        let b = self.map([r[2], r[3]]);
190        [a[0], a[1], b[0], b[1]]
191    }
192
193    /// The centre pixel's square in the loupe, in physical pixels.
194    pub fn center_block(&self) -> [f64; 4] {
195        let h = self.block / 2.0;
196        [
197            self.at[0] - h,
198            self.at[1] - h,
199            self.at[0] + h,
200            self.at[1] + h,
201        ]
202    }
203
204    /// The grid's lines across a loupe rectangle (physical pixels): the
205    /// positions of the vertical lines, then of the horizontal ones.
206    pub fn grid_lines(&self, r: [f64; 4]) -> (Vec<f64>, Vec<f64>) {
207        let lines = |from: f64, to: f64, at: f64| {
208            let first = ((from - (at - self.block / 2.0)) / self.block).ceil();
209            let mut v = Vec::new();
210            let mut k = first;
211            loop {
212                let x = at - self.block / 2.0 + k * self.block;
213                if x > to || v.len() > 512 {
214                    break;
215                }
216                v.push(x);
217                k += 1.0;
218            }
219            v
220        };
221        (lines(r[0], r[2], self.at[0]), lines(r[1], r[3], self.at[1]))
222    }
223}
224
225/// A scene colour (the source's `R`, `G` and `B`, when it names them) as
226/// displayed: through the display stage, in 8 bits.
227pub fn displayed(readout: &Readout, stage: &Stage) -> Option<[u8; 3]> {
228    let get = |name: &str| {
229        readout
230            .values
231            .iter()
232            .find(|(n, _)| n == name)
233            .map(|(_, v)| *v)
234    };
235    Some(stage.encode_8bit([get("R")?, get("G")?, get("B")?]))
236}
237
238/// CIE L*a*b* (D65) of an 8-bit sRGB colour.
239pub fn lab_from_srgb8(rgb: [u8; 3]) -> [f32; 3] {
240    let lin = |v: u8| {
241        let c = f32::from(v) / 255.0;
242        if c <= 0.040_45 {
243            c / 12.92
244        } else {
245            ((c + 0.055) / 1.055).powf(2.4)
246        }
247    };
248    let [r, g, b] = rgb.map(lin);
249    let x = 0.412_456_4 * r + 0.357_576_1 * g + 0.180_437_5 * b;
250    let y = 0.212_672_9 * r + 0.715_152_2 * g + 0.072_175 * b;
251    let z = 0.019_333_9 * r + 0.119_192 * g + 0.950_304_1 * b;
252    let f = |t: f32| {
253        let d = 6.0_f32 / 29.0;
254        if t > d * d * d {
255            t.cbrt()
256        } else {
257            t / (3.0 * d * d) + 4.0 / 29.0
258        }
259    };
260    let (fx, fy, fz) = (f(x / 0.950_47), f(y), f(z / 1.088_83));
261    [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
262}
263
264/// The readout's lines for a pixel: its coordinates and the mode, then
265/// its values as asked (`none` when the source gave nothing usable).
266///
267/// Display shows an `RGB` and a `Lab` line; Scene shows one line per
268/// value the source named. The readout may be for another pixel: it
269/// lags the pointer while the source answers. Its values are shown all
270/// the same (the loupe dims them, see [`stale`]) rather than dropped,
271/// and the position line always follows `pixel`. Off the image (`pixel`
272/// is `None`) there is a single `none` line.
273pub fn readout_lines(
274    pixel: Option<[i64; 2]>,
275    readout: Option<&Readout>,
276    values: Values,
277    stage: Option<&Stage>,
278    labels: [&str; 3],
279) -> Vec<String> {
280    let [display, scene, none] = labels;
281    let mut out = Vec::new();
282    let mode = match values {
283        Values::Off => return out,
284        Values::Display => display,
285        Values::Scene => scene,
286    };
287    match pixel {
288        Some(p) => out.push(format!("{}, {}  {mode}", p[0], p[1])),
289        None => {
290            out.push(none.to_string());
291            return out;
292        }
293    }
294    match (values, readout) {
295        (Values::Display, Some(r)) => match stage.and_then(|s| displayed(r, s)) {
296            Some(rgb) => {
297                let lab = lab_from_srgb8(rgb);
298                out.push(format!("RGB {} {} {}", rgb[0], rgb[1], rgb[2]));
299                // Rounded first, so a grey reads 0, never -0.
300                let [l, a, b] = lab.map(|v| if v.abs() < 0.5 { 0.0 } else { v.round() });
301                out.push(format!("Lab {l:.0} {a:.0} {b:.0}"));
302            }
303            None => out.push(none.to_string()),
304        },
305        (Values::Scene, Some(r)) if !r.values.is_empty() => {
306            for (name, v) in &r.values {
307                out.push(format!("{name} {v:.3}"));
308            }
309        }
310        _ => out.push(none.to_string()),
311    }
312    out
313}
314
315/// Whether the readout's values shown for `pixel` are another pixel's:
316/// the pointer moved on and the source has not answered yet.
317pub fn stale(pixel: Option<[i64; 2]>, readout: Option<&Readout>) -> bool {
318    pixel.is_some() && readout.is_some_and(|r| Some(r.pixel) != pixel)
319}
320
321/// The widest text each line of the readout can hold, one per line:
322/// what the loupe's readout block is measured from, so that its size
323/// stays the same while the values change, lag or go away.
324///
325/// Display has three lines (the position, `RGB` and `Lab`); Scene has
326/// the position and one line per name in `names` (the values the source
327/// gave last, one line while it has given none). Each line is the
328/// longer of its widest values and the `none` label; the readout is
329/// laid out in a monospace font, so the longer is the wider.
330pub fn readout_templates(values: Values, labels: [&str; 3], names: &[String]) -> Vec<String> {
331    let [display, scene, none] = labels;
332    let widest = |t: String| {
333        if none.chars().count() > t.chars().count() {
334            none.to_string()
335        } else {
336            t
337        }
338    };
339    let mode = match values {
340        Values::Off => return Vec::new(),
341        Values::Display => display,
342        Values::Scene => scene,
343    };
344    let mut out = vec![widest(format!("-00000, -00000  {mode}"))];
345    match values {
346        Values::Display => {
347            out.push(widest("RGB 255 255 255".into()));
348            out.push("Lab 100 -128 -128".into());
349        }
350        _ if names.is_empty() => out.push(widest("X -0000.000".into())),
351        _ => out.extend(names.iter().map(|n| widest(format!("{n} -0000.000")))),
352    }
353    out
354}
355
356/// What the loupe showed in the last frame (for tests and the debug
357/// bridge).
358#[derive(Clone, Debug, PartialEq)]
359pub struct LoupeFrame {
360    /// The whole loupe, in points.
361    pub rect: Rect,
362    /// Its picture, in points.
363    pub picture: Rect,
364    pub sampling: Sampling,
365    /// Tiles drawn again in it.
366    pub tiles: usize,
367    /// On the GPU path (else the CPU's textures).
368    pub gpu: bool,
369    /// The readout's lines (see [`readout_lines`]); empty when the
370    /// values are off.
371    pub lines: Vec<String>,
372    /// The lines after the first show the last readout, another pixel's
373    /// (the source has not answered for this one yet): they are dimmed.
374    pub stale: bool,
375}
376
377/// Points from physical pixels.
378pub(crate) fn to_points(r: [f64; 4], ppp: f32) -> Rect {
379    let s = f64::from(ppp);
380    Rect::from_min_max(
381        pos2((r[0] / s) as f32, (r[1] / s) as f32),
382        pos2((r[2] / s) as f32, (r[3] / s) as f32),
383    )
384}
385
386/// The picture's side and the loupe's padding, snapped to whole physical
387/// pixels.
388pub(crate) fn picture_size(l: &Loupe, ppp: f32) -> Vec2 {
389    let side = egui_pop_core::scale::snap_size(l.side.max(32.0), ppp);
390    vec2(side, side)
391}