ombre: Add support for FL32 images

731333fa97f060c1f6777169d257ea9ad9de53bf
Alexis Sellier committed ago 1 parent 6dc4b297
ombre/src/gfx/image.rs +4 -1
1 -
//! Image encoding and decoding.
1 +
//! RGBA image encoding and decoding.
2 +
#![warn(missing_docs)]
3 +
pub mod float;
4 +
2 5
use std::io;
3 6
use std::sync::Arc;
4 7
5 8
use super::{pixels, Color as _, Point2D, Rect, Rgba8, Size};
6 9
use crate::{
ombre/src/gfx/image/float.rs added +212 -0
1 +
//! FL32 image encoding and decoding.
2 +
#![warn(missing_docs)]
3 +
use std::io;
4 +
use std::sync::Arc;
5 +
6 +
use crate::{
7 +
    bytes::encoding::{Decode, Encode},
8 +
    bytes::{ReadBytes, WriteBytes},
9 +
    gfx::{Rgba, Rgba8},
10 +
    math::{Local, Point2D, Size},
11 +
};
12 +
13 +
/// File extension for FL32 images.
14 +
pub const FILE_EXTENSION: &str = "fl32";
15 +
/// File header magic number (corresponds to "FL32" in little-endian).
16 +
pub const MAGIC: u32 = 842222662;
17 +
18 +
/// Uniquely identifies an [`Image`].
19 +
pub type ImageId = u64;
20 +
21 +
/// An FL32 floating-point image.
22 +
/// Can be created from an `.fl32` file buffer using the `TryFrom` instance.
23 +
///
24 +
/// .-------------.
25 +
/// |   MAGIC     | 842222662 (4 bytes) (Little Endian)
26 +
/// +-------------+
27 +
/// |   LINES     |           (4 bytes) (Little Endian)
28 +
/// +-------------+
29 +
/// |   STRIDE    |           (4 bytes) (Little Endian)
30 +
/// +-------------+
31 +
/// |   CHANNELS  |           (4 bytes) (Little Endian)
32 +
/// +-------------+
33 +
/// |    DATA     |           (LINES * STRIDE * CHANNELS * 4 bytes)
34 +
/// |    ....     |           (f32 format) (Little Endian)
35 +
/// |    ....     |
36 +
/// '-------------'
37 +
///
38 +
#[derive(Clone)]
39 +
pub struct Image {
40 +
    /// Image size in pixels.
41 +
    pub size: Size<u32>,
42 +
    /// Number of channels, eg. `4` for RGBA.
43 +
    pub channels: u32,
44 +
    /// Image pixel buffer.
45 +
    pub pixels: Arc<[f32]>,
46 +
}
47 +
48 +
impl std::fmt::Debug for Image {
49 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 +
        f.debug_struct("Image")
51 +
            .field("size", &self.size)
52 +
            .field("channels", &self.channels)
53 +
            .finish_non_exhaustive()
54 +
    }
55 +
}
56 +
57 +
impl Eq for Image {}
58 +
59 +
impl PartialEq for Image {
60 +
    fn eq(&self, other: &Self) -> bool {
61 +
        (Arc::ptr_eq(&self.pixels, &other.pixels)
62 +
            && self.size == other.size
63 +
            && self.channels == other.channels)
64 +
            || self.pixels == other.pixels
65 +
    }
66 +
}
67 +
68 +
impl Image {
69 +
    /// Create a new image from pixels and dimensions.
70 +
    pub fn new(pixels: impl Into<Arc<[f32]>>, size: impl Into<Size<u32>>, channels: u32) -> Self {
71 +
        let size = size.into();
72 +
        let pixels = pixels.into();
73 +
74 +
        assert_eq!(size.area() as usize * channels as usize, pixels.len());
75 +
        assert!(channels > 0);
76 +
77 +
        Self {
78 +
            size,
79 +
            channels,
80 +
            pixels,
81 +
        }
82 +
    }
83 +
84 +
    /// Get the image area rectangle.
85 +
    pub fn rect(&self) -> super::Rect<f32, Local> {
86 +
        super::Rect::origin(self.size)
87 +
    }
88 +
89 +
    /// Create a blank image of the given size.
90 +
    ///
91 +
    /// # Panics
92 +
    ///
93 +
    /// Panics if `channels` is zero.
94 +
    pub fn blank(size: impl Into<Size<u32>>, channels: u32) -> Self {
95 +
        let size = size.into();
96 +
        assert!(channels > 0);
97 +
98 +
        Self::new(
99 +
            vec![0.0; size.area() as usize * channels as usize],
100 +
            size,
101 +
            channels,
102 +
        )
103 +
    }
104 +
105 +
    /// Get the pixel values at the given position in the image.
106 +
    pub fn sample(&self, point: Point2D<u32>) -> Option<&[f32]> {
107 +
        let offset = (self.size.w * point.y + point.x) as usize * self.channels as usize;
108 +
        self.pixels.get(offset..offset + self.channels as usize)
109 +
    }
110 +
111 +
    /// Return the image identifier of this image.
112 +
    /// This is the address in memory of the pixels.
113 +
    pub fn id(&self) -> ImageId {
114 +
        self.pixels.as_ptr() as ImageId
115 +
    }
116 +
117 +
    /// Attempts to convert this float image into an RGBA8 image.
118 +
    /// Only works if the image has exactly 4 channels and all values are between 0.0 and 1.0.
119 +
    pub fn to_rgba(&self) -> Option<super::Image> {
120 +
        if self.channels != 4 {
121 +
            return None;
122 +
        }
123 +
        let pixels: Vec<Rgba8> = self
124 +
            .pixels
125 +
            .chunks_exact(4)
126 +
            .map(|chunk| {
127 +
                if chunk.iter().any(|&v| !(0.0..=1.0).contains(&v)) {
128 +
                    return None;
129 +
                }
130 +
                Some(Rgba8::from(Rgba::new(
131 +
                    chunk[0], chunk[1], chunk[2], chunk[3],
132 +
                )))
133 +
            })
134 +
            .collect::<Option<Vec<_>>>()?;
135 +
136 +
        Some(super::Image::new(pixels, self.size))
137 +
    }
138 +
}
139 +
140 +
impl Decode for Image {
141 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
142 +
        let magic = reader.read_u32_le()?;
143 +
        if magic != MAGIC {
144 +
            return Err(io::ErrorKind::InvalidData.into());
145 +
        }
146 +
        let lines = reader.read_u32_le()?;
147 +
        let stride = reader.read_u32_le()?;
148 +
        let channels = reader.read_u32_le()?;
149 +
150 +
        if lines == 0 || stride == 0 || channels == 0 {
151 +
            return Err(io::ErrorKind::InvalidData.into());
152 +
        }
153 +
        let size = Size::new(stride, lines);
154 +
        let n = size.area() as usize * channels as usize;
155 +
        let mut pixels = Vec::with_capacity(n);
156 +
157 +
        while pixels.len() < n {
158 +
            let value = reader.read_f32_le()?;
159 +
            pixels.push(value);
160 +
        }
161 +
        Ok(Self::new(pixels, size, channels))
162 +
    }
163 +
}
164 +
165 +
impl Encode for Image {
166 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
167 +
        let mut n = 0;
168 +
169 +
        // Write header.
170 +
        n += writer.write_u32_le(MAGIC)?;
171 +
        n += writer.write_u32_le(self.size.h)?; // Lines
172 +
        n += writer.write_u32_le(self.size.w)?; // Stride
173 +
        n += writer.write_u32_le(self.channels)?; // Channels
174 +
175 +
        // Write pixel data.
176 +
        for p in self.pixels.iter().copied() {
177 +
            n += writer.write_f32_le(p)?;
178 +
        }
179 +
        Ok(n)
180 +
    }
181 +
}
182 +
183 +
impl TryFrom<&[u8]> for Image {
184 +
    type Error = io::Error;
185 +
186 +
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
187 +
        let mut cursor = io::Cursor::new(bytes);
188 +
        let image = Image::decode(&mut cursor)?;
189 +
190 +
        Ok(image)
191 +
    }
192 +
}
193 +
194 +
#[cfg(test)]
195 +
#[allow(clippy::unwrap_used)]
196 +
mod tests {
197 +
    use super::*;
198 +
    use crate::bytes::encoding::{deserialize, serialize};
199 +
200 +
    #[test]
201 +
    fn test_fl32_image_roundtrip() {
202 +
        let original = Image::new(vec![0.0, 0.5, 1.0, 0.0], Size::<u32>::new(2, 1), 2);
203 +
204 +
        let encoded = serialize(&original).unwrap();
205 +
        let decoded: Image = deserialize(&encoded).unwrap();
206 +
207 +
        assert_eq!(original, decoded);
208 +
        assert_eq!(original.size, decoded.size);
209 +
        assert_eq!(original.channels, decoded.channels);
210 +
        assert_eq!(original.pixels.len(), decoded.pixels.len());
211 +
    }
212 +
}