Skip to main content

embedded_graphics_readback/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3//! A pixel-readback capability for [`embedded-graphics`] draw targets.
4//!
5//! Compositing needs to know what is already on the target before it writes.
6//! Antialiased edges, translucent fills, blend modes and every other
7//! read-modify-write effect blend a foreground colour *into* a backdrop, and
8//! the backdrop is whatever the target currently holds. [`ReadbackTarget`] is
9//! the capability that says a target can answer that question, so rendering
10//! code can require it generically:
11//!
12//! ```
13//! use embedded_graphics_core::{draw_target::DrawTarget, primitives::Rectangle};
14//! use embedded_graphics_readback::ReadbackTarget;
15//!
16//! # fn blend_over<C>(fg: C, _bg: C, _coverage: u8) -> C { fg }
17//! /// Blend `fg` over one scanline run at the given per-pixel coverage.
18//! fn composite_run<D: ReadbackTarget>(
19//!     target: &mut D,
20//!     run: &Rectangle,
21//!     fg: D::Color,
22//!     coverage: &[u8],
23//!     scratch: &mut [D::Color],
24//! ) {
25//!     target.read_area(run, scratch);
26//!     for (px, &cov) in scratch.iter_mut().zip(coverage) {
27//!         *px = blend_over(fg, *px, cov);
28//!     }
29//!     let _ = target.fill_contiguous(run, scratch.iter().copied());
30//! }
31//! ```
32//!
33//! `ReadbackTarget: DrawTarget`, so a single bound supplies both halves of that
34//! loop and a single `Self::Color` names the pixel type throughout. The
35//! immutable read finishes before the mutable write begins, so one `&mut D`
36//! carries the whole operation — no staging buffer for the shape's bounding
37//! box, just a scratch run.
38//!
39//! It is a thin, dependency-light contract over [`embedded-graphics-core`]:
40//! [`read_pixel`](ReadbackTarget::read_pixel) is the one required method, and
41//! [`read_area`](ReadbackTarget::read_area) copies a region out row-major in
42//! one call — defaulting to a `read_pixel` loop, overridable with a block copy.
43//!
44//! # Layers
45//!
46//! Because the capability belongs to the *target*, a wrapper carries it forward
47//! by delegating both methods. [`adapters`] ships the three that matter —
48//! [`Shifted`](adapters::Shifted), [`Windowed`](adapters::Windowed) and
49//! [`Masked`](adapters::Masked) — so a pipeline keeps readback end to end:
50//!
51//! ```
52//! # use embedded_graphics_core::{
53//! #     Pixel, draw_target::DrawTarget, geometry::{OriginDimensions, Point, Size},
54//! #     pixelcolor::{Rgb565, RgbColor}, primitives::Rectangle,
55//! # };
56//! # use embedded_graphics_readback::ReadbackTarget;
57//! use embedded_graphics_readback::ReadbackTargetExt;
58//!
59//! # struct Fb([Rgb565; 64]);
60//! # impl Fb {
61//! #     fn index(p: Point) -> Option<usize> {
62//! #         ((0..8).contains(&p.x) && (0..8).contains(&p.y)).then(|| (p.y * 8 + p.x) as usize)
63//! #     }
64//! # }
65//! # impl OriginDimensions for Fb {
66//! #     fn size(&self) -> Size { Size::new(8, 8) }
67//! # }
68//! # impl DrawTarget for Fb {
69//! #     type Color = Rgb565;
70//! #     type Error = core::convert::Infallible;
71//! #     fn draw_iter<I>(&mut self, _: I) -> Result<(), Self::Error>
72//! #     where I: IntoIterator<Item = Pixel<Self::Color>> { Ok(()) }
73//! # }
74//! # impl ReadbackTarget for Fb {
75//! #     fn read_pixel(&self, p: Point) -> Option<Rgb565> {
76//! #         Fb::index(p).map(|i| self.0[i])
77//! #     }
78//! # }
79//! # let mut fb = Fb([Rgb565::BLACK; 64]);
80//! let mut layer = fb.shifted(Point::new(2, 2));
81//! let mut view = layer.masked(&Rectangle::new(Point::zero(), Size::new(4, 4)));
82//!
83//! composite_run(&mut view, /* ... */);
84//! # fn composite_run<D: ReadbackTarget>(_: &mut D) {}
85//! ```
86//!
87//! `embedded-graphics`' own [`DrawTargetExt`] adapters hold their parent in a
88//! private field with no accessor, so readback cannot be delegated through
89//! them — these are read-capable equivalents with the same write semantics.
90//!
91//! # Implementing it
92//!
93//! [`read_pixel`](ReadbackTarget::read_pixel) shares its signature with
94//! [`GetPixel::pixel`](embedded_graphics_core::image::GetPixel::pixel), so a
95//! target that already implements that trait delegates in one line. A reader
96//! that hands back a bare colour needs a bounds guard instead, since
97//! `read_pixel` answers `None` outside the bounding box:
98//!
99//! ```
100//! use embedded_graphics_core::{
101//!     draw_target::DrawTarget,
102//!     geometry::{Dimensions, Point},
103//!     image::GetPixel,
104//!     pixelcolor::Rgb565,
105//! };
106//! use embedded_graphics_readback::ReadbackTarget;
107//!
108//! # use embedded_graphics_core::{geometry::Size, primitives::Rectangle, Pixel};
109//! # struct Canvas;
110//! # impl Canvas {
111//! #     fn get_pixel(&self, _p: Point) -> Rgb565 { Rgb565::new(0, 0, 0) }
112//! # }
113//! # struct Fb;
114//! # struct Sim(Canvas);
115//! # impl Dimensions for Fb {
116//! #     fn bounding_box(&self) -> Rectangle { Rectangle::new(Point::zero(), Size::new(64, 64)) }
117//! # }
118//! # impl DrawTarget for Fb {
119//! #     type Color = Rgb565;
120//! #     type Error = core::convert::Infallible;
121//! #     fn draw_iter<I>(&mut self, _: I) -> Result<(), Self::Error>
122//! #     where I: IntoIterator<Item = Pixel<Self::Color>> { Ok(()) }
123//! # }
124//! # impl GetPixel for Fb {
125//! #     type Color = Rgb565;
126//! #     fn pixel(&self, _p: Point) -> Option<Rgb565> { None }
127//! # }
128//! # impl Dimensions for Sim {
129//! #     fn bounding_box(&self) -> Rectangle { Rectangle::new(Point::zero(), Size::new(64, 64)) }
130//! # }
131//! # impl DrawTarget for Sim {
132//! #     type Color = Rgb565;
133//! #     type Error = core::convert::Infallible;
134//! #     fn draw_iter<I>(&mut self, _: I) -> Result<(), Self::Error>
135//! #     where I: IntoIterator<Item = Pixel<Self::Color>> { Ok(()) }
136//! # }
137//! // Already a `GetPixel`: delegate.
138//! impl ReadbackTarget for Fb {
139//!     fn read_pixel(&self, point: Point) -> Option<Self::Color> {
140//!         GetPixel::pixel(self, point)
141//!     }
142//! }
143//!
144//! // Hands back a bare colour: guard on the bounding box.
145//! impl ReadbackTarget for Sim {
146//!     fn read_pixel(&self, point: Point) -> Option<Self::Color> {
147//!         self.bounding_box()
148//!             .contains(point)
149//!             .then(|| self.0.get_pixel(point))
150//!     }
151//! }
152//! ```
153//!
154//! # `embedded-graphics` framebuffers
155//!
156//! [`embedded_graphics::framebuffer::Framebuffer`] is supported out of the box
157//! under the `framebuffer` feature:
158//!
159//! ```toml
160//! embedded-graphics-readback = { version = "0.1", features = ["framebuffer"] }
161//! ```
162//!
163//! The impl covers every colour type and data order `embedded-graphics` makes
164//! drawable, and overrides [`read_area`](ReadbackTarget::read_area) to build
165//! the backing image once per region. Draw into a `Framebuffer`, hand it to any
166//! `ReadbackTarget` renderer, and flush it to the panel — which also makes it
167//! the shortest route to readback for a streaming driver.
168//!
169//! # Who implements it
170//!
171//! Framebuffers and canvases — anything holding pixels in RAM, where a read is
172//! a slice index — are the natural implementors, along with buffered display
173//! drivers that expose their buffer and simulators wrapped in a newtype.
174//! Streaming drivers hold no pixels, so they leave the trait unimplemented and
175//! callers keep the write-only path.
176//!
177//! [`embedded_graphics::framebuffer::Framebuffer`]:
178//!     https://docs.rs/embedded-graphics/latest/embedded_graphics/framebuffer/struct.Framebuffer.html
179//! [`DrawTargetExt`]:
180//!     https://docs.rs/embedded-graphics/latest/embedded_graphics/draw_target/trait.DrawTargetExt.html
181//!
182//! [`embedded-graphics`]: https://docs.rs/embedded-graphics
183//! [`embedded-graphics-core`]: https://docs.rs/embedded-graphics-core
184//! [`DrawTarget`]: embedded_graphics_core::draw_target::DrawTarget
185
186pub mod adapters;
187
188#[cfg(feature = "framebuffer")]
189#[cfg_attr(docsrs, doc(cfg(feature = "framebuffer")))]
190mod framebuffer;
191
192pub use adapters::ReadbackTargetExt;
193
194use embedded_graphics_core::{
195    draw_target::DrawTarget,
196    geometry::Point,
197    primitives::{PointsIter, Rectangle},
198};
199
200/// A [`DrawTarget`] that can read back the pixels it has drawn.
201///
202/// Implement this for targets that retain their pixels in memory (framebuffers,
203/// canvases, simulators). Streaming targets that forward straight to a bus
204/// cannot read back and should not implement it.
205///
206/// # Cost contract
207///
208/// Destination-aware renderers call [`read_area`](Self::read_area) **once per
209/// run on the hot path** — they assume a read is roughly the cost of a write.
210/// That holds for RAM-backed framebuffers, where a read is slice arithmetic;
211/// those are the intended targets. A panel whose only read primitive is a slow
212/// per-pixel bus command should not implement this trait merely because it can:
213/// the default [`read_area`](Self::read_area) turns every antialiased run into
214/// `width` bus round-trips. Implement it where reads are cheap, and override
215/// [`read_area`](Self::read_area) with a block copy whenever the target allows
216/// it.
217pub trait ReadbackTarget: DrawTarget {
218    /// The colour currently at `point`, or `None` if `point` lies outside the
219    /// target's [bounding box](embedded_graphics_core::geometry::Dimensions::bounding_box).
220    ///
221    /// Matches [`GetPixel::pixel`](embedded_graphics_core::image::GetPixel::pixel).
222    #[must_use]
223    fn read_pixel(&self, point: Point) -> Option<Self::Color>;
224
225    /// Read the pixels of `area` row-major into `out`, returning how many were
226    /// in bounds (and so written).
227    ///
228    /// The default reads pixel-by-pixel via [`read_pixel`](Self::read_pixel):
229    /// each in-bounds colour is written to the matching `out` slot and
230    /// out-of-bounds slots are left untouched. Iteration stops at whichever of
231    /// `area` or `out` is exhausted first. Override this when the target can
232    /// copy a whole region out of its framebuffer in one operation.
233    fn read_area(&self, area: &Rectangle, out: &mut [Self::Color]) -> usize {
234        read_area_by_pixel(self, area, out)
235    }
236}
237
238/// The per-pixel loop behind [`ReadbackTarget::read_area`]'s default; the
239/// [`adapters`] fall back to it where a region only partly overlaps a layer.
240pub(crate) fn read_area_by_pixel<T>(target: &T, area: &Rectangle, out: &mut [T::Color]) -> usize
241where
242    T: ReadbackTarget + ?Sized,
243{
244    let mut written = 0;
245    for (slot, point) in out.iter_mut().zip(area.points()) {
246        if let Some(color) = target.read_pixel(point) {
247            *slot = color;
248            written += 1;
249        }
250    }
251    written
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use embedded_graphics::prelude::*;
258    use embedded_graphics_core::{pixelcolor::Rgb565, primitives::Rectangle};
259
260    /// A tiny 4×4 RGB565 framebuffer for exercising the trait.
261    struct TestFb {
262        pixels: [Rgb565; 16],
263    }
264
265    impl TestFb {
266        fn new() -> Self {
267            Self {
268                pixels: [Rgb565::BLACK; 16],
269            }
270        }
271        fn index(p: Point) -> Option<usize> {
272            (0..4).contains(&p.x).then_some(())?;
273            (0..4).contains(&p.y).then_some(())?;
274            Some((p.y * 4 + p.x) as usize)
275        }
276    }
277
278    impl OriginDimensions for TestFb {
279        fn size(&self) -> Size {
280            Size::new(4, 4)
281        }
282    }
283
284    impl DrawTarget for TestFb {
285        type Color = Rgb565;
286        type Error = core::convert::Infallible;
287        fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
288        where
289            I: IntoIterator<Item = Pixel<Self::Color>>,
290        {
291            for Pixel(p, c) in pixels {
292                if let Some(i) = Self::index(p) {
293                    self.pixels[i] = c;
294                }
295            }
296            Ok(())
297        }
298    }
299
300    impl ReadbackTarget for TestFb {
301        fn read_pixel(&self, point: Point) -> Option<Self::Color> {
302            Self::index(point).map(|i| self.pixels[i])
303        }
304    }
305
306    #[test]
307    fn read_pixel_round_trips_a_write() {
308        let mut fb = TestFb::new();
309        Pixel(Point::new(1, 2), Rgb565::RED).draw(&mut fb).unwrap();
310        assert_eq!(fb.read_pixel(Point::new(1, 2)), Some(Rgb565::RED));
311        assert_eq!(fb.read_pixel(Point::new(0, 0)), Some(Rgb565::BLACK));
312    }
313
314    #[test]
315    fn read_pixel_out_of_bounds_is_none() {
316        let fb = TestFb::new();
317        assert_eq!(fb.read_pixel(Point::new(-1, 0)), None);
318        assert_eq!(fb.read_pixel(Point::new(4, 0)), None);
319        assert_eq!(fb.read_pixel(Point::new(0, 4)), None);
320    }
321
322    #[test]
323    fn read_area_default_fills_row_major() {
324        let mut fb = TestFb::new();
325        Pixel(Point::new(0, 0), Rgb565::RED).draw(&mut fb).unwrap();
326        Pixel(Point::new(1, 0), Rgb565::GREEN)
327            .draw(&mut fb)
328            .unwrap();
329        Pixel(Point::new(0, 1), Rgb565::BLUE).draw(&mut fb).unwrap();
330
331        let mut out = [Rgb565::WHITE; 4];
332        let n = fb.read_area(&Rectangle::new(Point::zero(), Size::new(2, 2)), &mut out);
333        assert_eq!(n, 4);
334        assert_eq!(
335            out,
336            [Rgb565::RED, Rgb565::GREEN, Rgb565::BLUE, Rgb565::BLACK]
337        );
338    }
339
340    #[test]
341    fn read_area_counts_only_in_bounds() {
342        let fb = TestFb::new();
343        // A region straddling the right edge: only the in-bounds column counts.
344        let mut out = [Rgb565::WHITE; 4];
345        let n = fb.read_area(&Rectangle::new(Point::new(3, 0), Size::new(2, 2)), &mut out);
346        assert_eq!(n, 2);
347    }
348}