Skip to main content

sim_logic/assets/
image.rs

1//! Bounded, application-owned straight-alpha sRGB RGBA8 image storage.
2
3use std::{collections::TryReserveError, error::Error, fmt};
4
5use crate::identity::ApplicationId;
6
7/// Frozen limits for immutable CPU images registered before application startup.
8///
9/// Count and per-image dimensions are separate from total retained pixel Vec
10/// capacity. Registry metadata is bounded by image count and is not charged to
11/// the pixel budget. Zero limits are valid and can disable registration.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ImageAssetLimits {
14    max_images: usize,
15    max_width: u32,
16    max_height: u32,
17    max_pixel_bytes: usize,
18}
19
20impl ImageAssetLimits {
21    /// Creates exact count, texel-dimension, and retained-pixel-capacity limits.
22    ///
23    /// No storage is allocated, and every value, including zero, is accepted.
24    pub const fn new(
25        max_images: usize,
26        max_width: u32,
27        max_height: u32,
28        max_pixel_bytes: usize,
29    ) -> Self {
30        Self {
31            max_images,
32            max_width,
33            max_height,
34            max_pixel_bytes,
35        }
36    }
37
38    /// Returns the maximum number of distinct registered image entries.
39    pub const fn max_images(self) -> usize {
40        self.max_images
41    }
42
43    /// Returns the maximum width of one image, in texels.
44    pub const fn max_width(self) -> u32 {
45        self.max_width
46    }
47
48    /// Returns the maximum height of one image, in texels.
49    pub const fn max_height(self) -> u32 {
50        self.max_height
51    }
52
53    /// Returns the maximum sum of retained pixel Vec capacities, in bytes.
54    pub const fn max_pixel_bytes(self) -> usize {
55        self.max_pixel_bytes
56    }
57}
58
59impl Default for ImageAssetLimits {
60    /// Permits 64 images, each at most 4096 by 4096 texels, within 64 MiB.
61    fn default() -> Self {
62        Self::new(64, 4096, 4096, 64 * 1024 * 1024)
63    }
64}
65
66/// Opaque identity of one immutable image registered by an application.
67///
68/// Handles retain application provenance, registration identity, and validated
69/// dimensions. They survive World replacement within their issuing application.
70/// Registering equal pixels twice issues distinct handles. A handle is not a
71/// filename, a save-file identifier, or a GPU resource.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct ImageAssetId {
74    application: ApplicationId,
75    slot: usize,
76    width: u32,
77    height: u32,
78}
79
80impl ImageAssetId {
81    /// Returns the immutable image width in texels, which is always positive.
82    pub const fn width(self) -> u32 {
83        self.width
84    }
85
86    /// Returns the immutable image height in texels, which is always positive.
87    pub const fn height(self) -> u32 {
88        self.height
89    }
90}
91
92/// Read-only CPU pixels belonging to one registered application image.
93///
94/// Rows run top to bottom, texels within each row run left to right, and every
95/// texel contains straight-alpha sRGB RGBA8 channels. There is no row padding.
96/// Pixels stay owned by the application across World replacement; this type
97/// exposes no mutation, decoder, platform, or GPU operation.
98#[derive(Debug)]
99pub struct ImageAsset {
100    width: u32,
101    height: u32,
102    pixels: Vec<u8>,
103}
104
105impl ImageAsset {
106    /// Returns the positive image width in texels.
107    pub const fn width(&self) -> u32 {
108        self.width
109    }
110
111    /// Returns the positive image height in texels.
112    pub const fn height(&self) -> u32 {
113        self.height
114    }
115
116    /// Returns exactly width times height times four straight-alpha RGBA8 bytes.
117    pub fn pixels(&self) -> &[u8] {
118        &self.pixels
119    }
120}
121
122/// A rejected immutable-image registration, leaving prior entries unchanged.
123#[derive(Debug)]
124#[non_exhaustive]
125pub enum ImageAssetError {
126    /// Width or height was zero.
127    InvalidDimensions {
128        /// Rejected width in texels.
129        width: u32,
130        /// Rejected height in texels.
131        height: u32,
132    },
133    /// At least one dimension exceeded its configured maximum.
134    DimensionsExceeded {
135        /// Rejected width in texels.
136        width: u32,
137        /// Rejected height in texels.
138        height: u32,
139        /// Configured maximum width in texels.
140        max_width: u32,
141        /// Configured maximum height in texels.
142        max_height: u32,
143    },
144    /// Width times height times four cannot be represented as a byte length.
145    PixelByteCountOverflow {
146        /// Rejected width in texels.
147        width: u32,
148        /// Rejected height in texels.
149        height: u32,
150    },
151    /// The supplied slice did not contain exactly one RGBA8 value per texel.
152    PixelLengthMismatch {
153        /// Required byte length calculated from the validated dimensions.
154        expected: usize,
155        /// Supplied slice length in bytes.
156        actual: usize,
157    },
158    /// The registry already contains its configured maximum image count.
159    ImageLimitExceeded {
160        /// Configured maximum number of registered entries.
161        limit: usize,
162    },
163    /// New pixel storage would exceed the total retained-capacity budget.
164    PixelByteLimitExceeded {
165        /// Configured total retained-pixel-capacity limit in bytes.
166        limit: usize,
167        /// Pixel capacity already retained by successful registrations.
168        retained: usize,
169        /// Requested bytes, or actual Vec capacity if allocation reserved more.
170        incoming: usize,
171    },
172    /// Pixel or registry metadata allocation failed before publication.
173    AllocationFailed {
174        /// The fallible allocator's original error.
175        source: TryReserveError,
176    },
177}
178
179impl fmt::Display for ImageAssetError {
180    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
181        match self {
182            Self::InvalidDimensions { width, height } => write!(
183                formatter,
184                "image dimensions must be positive, got {width} by {height}"
185            ),
186            Self::DimensionsExceeded {
187                width,
188                height,
189                max_width,
190                max_height,
191            } => write!(
192                formatter,
193                "image dimensions {width} by {height} exceed limits {max_width} by {max_height}"
194            ),
195            Self::PixelByteCountOverflow { width, height } => write!(
196                formatter,
197                "RGBA8 byte length overflows for image dimensions {width} by {height}"
198            ),
199            Self::PixelLengthMismatch { expected, actual } => write!(
200                formatter,
201                "RGBA8 image requires exactly {expected} bytes, got {actual}"
202            ),
203            Self::ImageLimitExceeded { limit } => {
204                write!(
205                    formatter,
206                    "image registry reached its limit of {limit} entries"
207                )
208            }
209            Self::PixelByteLimitExceeded {
210                limit,
211                retained,
212                incoming,
213            } => write!(
214                formatter,
215                "image pixel capacity {retained} plus {incoming} bytes exceeds limit {limit}"
216            ),
217            Self::AllocationFailed { source } => {
218                write!(formatter, "image asset storage allocation failed: {source}")
219            }
220        }
221    }
222}
223
224impl Error for ImageAssetError {
225    fn source(&self) -> Option<&(dyn Error + 'static)> {
226        match self {
227            Self::AllocationFailed { source } => Some(source),
228            _ => None,
229        }
230    }
231}
232
233#[derive(Debug)]
234pub(crate) struct ImageAssetRegistry {
235    application: ApplicationId,
236    limits: ImageAssetLimits,
237    images: Vec<ImageAsset>,
238    pixel_bytes: usize,
239}
240
241impl ImageAssetRegistry {
242    pub(crate) const fn new(application: ApplicationId, limits: ImageAssetLimits) -> Self {
243        Self {
244            application,
245            limits,
246            images: Vec::new(),
247            pixel_bytes: 0,
248        }
249    }
250
251    pub(crate) fn register(
252        &mut self,
253        width: u32,
254        height: u32,
255        pixels: &[u8],
256    ) -> Result<ImageAssetId, ImageAssetError> {
257        if width == 0 || height == 0 {
258            return Err(ImageAssetError::InvalidDimensions { width, height });
259        }
260        if width > self.limits.max_width || height > self.limits.max_height {
261            return Err(ImageAssetError::DimensionsExceeded {
262                width,
263                height,
264                max_width: self.limits.max_width,
265                max_height: self.limits.max_height,
266            });
267        }
268        let pixel_length = usize::try_from(width)
269            .ok()
270            .zip(usize::try_from(height).ok())
271            .and_then(|(width, height)| width.checked_mul(height))
272            .and_then(|texels| texels.checked_mul(4))
273            .ok_or(ImageAssetError::PixelByteCountOverflow { width, height })?;
274        if pixels.len() != pixel_length {
275            return Err(ImageAssetError::PixelLengthMismatch {
276                expected: pixel_length,
277                actual: pixels.len(),
278            });
279        }
280        if self.images.len() >= self.limits.max_images {
281            return Err(ImageAssetError::ImageLimitExceeded {
282                limit: self.limits.max_images,
283            });
284        }
285        self.check_pixel_capacity(pixel_length)?;
286        let mut owned = Vec::new();
287        owned
288            .try_reserve_exact(pixel_length)
289            .map_err(|source| ImageAssetError::AllocationFailed { source })?;
290        // Vec's capacity is permitted to exceed the requested length. Charge
291        // the actual retained capacity before publishing the entry.
292        self.check_pixel_capacity(owned.capacity())?;
293        owned.extend_from_slice(pixels);
294        self.images
295            .try_reserve_exact(1)
296            .map_err(|source| ImageAssetError::AllocationFailed { source })?;
297        let id = ImageAssetId {
298            application: self.application,
299            slot: self.images.len(),
300            width,
301            height,
302        };
303        self.pixel_bytes += owned.capacity();
304        self.images.push(ImageAsset {
305            width,
306            height,
307            pixels: owned,
308        });
309        Ok(id)
310    }
311
312    pub(crate) fn get(&self, id: ImageAssetId) -> Option<&ImageAsset> {
313        if id.application != self.application {
314            return None;
315        }
316        self.images
317            .get(id.slot)
318            .filter(|image| image.width == id.width && image.height == id.height)
319    }
320
321    pub(crate) fn len(&self) -> usize {
322        self.images.len()
323    }
324
325    pub(crate) const fn pixel_bytes(&self) -> usize {
326        self.pixel_bytes
327    }
328
329    fn check_pixel_capacity(&self, incoming: usize) -> Result<(), ImageAssetError> {
330        if incoming > self.limits.max_pixel_bytes.saturating_sub(self.pixel_bytes) {
331            return Err(ImageAssetError::PixelByteLimitExceeded {
332                limit: self.limits.max_pixel_bytes,
333                retained: self.pixel_bytes,
334                incoming,
335            });
336        }
337        Ok(())
338    }
339}
340
341#[cfg(test)]
342#[path = "image_tests.rs"]
343mod tests;