From 2d3da6014bdcded6187361182d8db14e897f88f3 Mon Sep 17 00:00:00 2001 From: Caleb Fletcher Date: Tue, 2 Apr 2024 21:27:09 +1100 Subject: [PATCH] Expose DecodedImage in the public API (#65) * Expose DecodedImage in the public API * Add `DecodedImage::from_raw` constructor --- galileo/src/control/event_processor.rs | 4 +-- galileo/src/decoded_image.rs | 38 ++++++++++++++++++++++---- galileo/src/lib.rs | 2 +- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/galileo/src/control/event_processor.rs b/galileo/src/control/event_processor.rs index 8684836..594de53 100644 --- a/galileo/src/control/event_processor.rs +++ b/galileo/src/control/event_processor.rs @@ -198,9 +198,7 @@ impl EventProcessor { None } RawUserEvent::TouchMove(touch) => { - let Some(touch_info) = self.touches.iter().find(|t| t.id == touch.touch_id) else { - return None; - }; + let touch_info = self.touches.iter().find(|t| t.id == touch.touch_id)?; let position = touch.position; let mut events = vec![]; diff --git a/galileo/src/decoded_image.rs b/galileo/src/decoded_image.rs index 5b47c2e..d889c12 100644 --- a/galileo/src/decoded_image.rs +++ b/galileo/src/decoded_image.rs @@ -1,15 +1,22 @@ +//! This module contains utilities for loading images to be rendered on the map. + #[cfg(not(target_arch = "wasm32"))] use crate::error::GalileoError; -#[cfg(not(target_arch = "wasm32"))] -use std::ops::Deref; +/// An image that has been loaded into memory. #[derive(Debug, Clone)] pub struct DecodedImage { - pub bytes: Vec, - pub dimensions: (u32, u32), + /// Raw bytes of the image, in RGBA order. + pub(crate) bytes: Vec, + /// Width and height of the image. + pub(crate) dimensions: (u32, u32), } impl DecodedImage { + /// Decode an image from a byte slice. + /// + /// Attempts to guess the format of the image from the data. Non-RGBA images + /// will be converted to RGBA. #[cfg(not(target_arch = "wasm32"))] pub fn new(bytes: &[u8]) -> Result { use image::GenericImageView; @@ -18,8 +25,29 @@ impl DecodedImage { let dimensions = decoded.dimensions(); Ok(Self { - bytes: Vec::from(bytes.deref()), + bytes: bytes.into_vec(), dimensions, }) } + + /// Create a DecodedImage from a buffer of raw RGBA pixels. + #[cfg(not(target_arch = "wasm32"))] + pub fn from_raw( + bytes: impl Into>, + width: u32, + height: u32, + ) -> Result { + let bytes = bytes.into(); + + if bytes.len() != 4 * width as usize * height as usize { + return Err(GalileoError::Generic( + "invalid image dimensions for buffer size".into(), + )); + } + + Ok(Self { + bytes, + dimensions: (width, height), + }) + } } diff --git a/galileo/src/lib.rs b/galileo/src/lib.rs index a62ecaf..d9cf594 100644 --- a/galileo/src/lib.rs +++ b/galileo/src/lib.rs @@ -71,7 +71,7 @@ pub(crate) mod async_runtime; mod color; pub mod control; -pub(crate) mod decoded_image; +pub mod decoded_image; pub mod error; pub mod layer; mod lod;