Skip to main content

xrack_runtime/
image_asset.rs

1use crate::{Image, ImageFormat, InvalidNineSlice, NineSlice};
2use std::{
3    fmt,
4    rc::Rc,
5    sync::{
6        Arc,
7        atomic::{AtomicU64, Ordering},
8    },
9};
10
11/// The image value accepted by layout, rendering, and playback.
12#[derive(Clone, Debug)]
13pub enum ImageAsset {
14    Embedded(Image),
15    Loaded(LoadedImage),
16    Animated(Rc<LoadedAnimation>),
17}
18
19impl PartialEq for ImageAsset {
20    fn eq(&self, other: &Self) -> bool {
21        match (self, other) {
22            (Self::Embedded(left), Self::Embedded(right)) => left == right,
23            (Self::Loaded(left), Self::Loaded(right)) => left == right,
24            (Self::Animated(left), Self::Animated(right)) => {
25                Rc::ptr_eq(left, right) || left == right
26            }
27            (Self::Embedded(Image::Animated(embedded)), Self::Animated(loaded))
28            | (Self::Animated(loaded), Self::Embedded(Image::Animated(embedded))) => {
29                embedded.matches_loaded(loaded)
30            }
31            (Self::Loaded(_), Self::Embedded(_)) | (Self::Embedded(_), Self::Loaded(_)) => {
32                let (Some(left), Some(right)) = (self.pixels(), other.pixels()) else {
33                    return false;
34                };
35                left.format == right.format
36                    && left.size == right.size
37                    && left.edges == right.edges
38                    && left.bytes == right.bytes
39            }
40            _ => false,
41        }
42    }
43}
44
45impl Eq for ImageAsset {}
46
47impl Default for ImageAsset {
48    fn default() -> Self {
49        Self::Embedded(Image::Empty)
50    }
51}
52
53impl From<Image> for ImageAsset {
54    fn from(image: Image) -> Self {
55        match image {
56            Image::Loaded(image) => Self::Loaded(image),
57            embedded => Self::Embedded(embedded),
58        }
59    }
60}
61
62#[derive(Clone)]
63pub struct LoadedImage {
64    source: Arc<LoadedImageSource>,
65    edges: Option<NineSlice>,
66}
67
68struct LoadedImageSource {
69    id: u64,
70    format: ImageFormat,
71    bytes: Vec<u8>,
72    size: [u32; 2],
73}
74
75impl LoadedImage {
76    #[expect(
77        clippy::expect_used,
78        reason = "loaded image IDs must stay unique even if the counter reaches its limit"
79    )]
80    pub fn new(format: ImageFormat, bytes: Vec<u8>, size: [u32; 2]) -> Self {
81        static NEXT_IMAGE: AtomicU64 = AtomicU64::new(1);
82        let id = NEXT_IMAGE
83            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
84            .expect("loaded image identity exhausted");
85        Self {
86            source: Arc::new(LoadedImageSource {
87                id,
88                format,
89                bytes,
90                size,
91            }),
92            edges: None,
93        }
94    }
95
96    pub fn size(&self) -> [u32; 2] {
97        self.source.size
98    }
99
100    pub(crate) fn with_nine_slice(mut self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
101        if !edges.fits(self.source.size) {
102            return Err(InvalidNineSlice);
103        }
104        self.edges = Some(edges);
105        Ok(self)
106    }
107
108    pub(crate) fn bytes(&self) -> &[u8] {
109        &self.source.bytes
110    }
111}
112
113impl PartialEq for LoadedImage {
114    fn eq(&self, other: &Self) -> bool {
115        self.edges == other.edges
116            && (Arc::ptr_eq(&self.source, &other.source)
117                || (self.source.size == other.source.size
118                    && self.source.format == other.source.format
119                    && self.source.bytes == other.source.bytes))
120    }
121}
122
123impl Eq for LoadedImage {}
124
125impl fmt::Debug for LoadedImage {
126    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
127        output
128            .debug_struct("LoadedImage")
129            .field("format", &self.source.format)
130            .field("size", &self.source.size)
131            .field("edges", &self.edges)
132            .finish()
133    }
134}
135
136#[derive(Debug, PartialEq, Eq)]
137pub struct LoadedAnimation {
138    pub(crate) size: [u32; 2],
139    pub(crate) frames: Vec<(u32, LoadedImage)>,
140    pub(crate) plays: u32,
141}
142
143impl LoadedAnimation {
144    pub fn new(size: [u32; 2], frames: Vec<(u32, Vec<u8>)>, plays: u32) -> Self {
145        Self {
146            size,
147            frames: frames
148                .into_iter()
149                .map(|(end, bytes)| (end, LoadedImage::new(ImageFormat::Png, bytes, size)))
150                .collect(),
151            plays,
152        }
153    }
154
155    #[doc(hidden)]
156    pub fn frames(&self) -> impl ExactSizeIterator<Item = (u32, &[u8])> {
157        self.frames.iter().map(|(end, frame)| (*end, frame.bytes()))
158    }
159}
160
161/// Identity for a cache entry. Loaded assets can outlive their original scene
162/// without making a later allocation at the same address hit an old texture.
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
164pub enum ImageIdentity {
165    Embedded(usize),
166    Loaded(u64),
167}
168
169pub struct ImagePixels<'a> {
170    pub identity: ImageIdentity,
171    pub format: ImageFormat,
172    pub bytes: &'a [u8],
173    pub size: [u32; 2],
174    pub edges: Option<NineSlice>,
175}
176
177impl ImageAsset {
178    pub fn size(&self) -> [u32; 2] {
179        match self {
180            Self::Embedded(image) => image.size(),
181            Self::Loaded(image) => image.source.size,
182            Self::Animated(animation) => animation.size,
183        }
184    }
185
186    pub fn frame_count(&self) -> usize {
187        match self {
188            Self::Embedded(image) => image.frame_count(),
189            Self::Loaded(_) => 1,
190            Self::Animated(animation) => animation.frames.len(),
191        }
192    }
193
194    pub fn frame(&self, index: usize) -> Self {
195        match self {
196            Self::Embedded(image) => image.clone().frame(index).into(),
197            Self::Loaded(_) => self.clone(),
198            Self::Animated(animation) => animation
199                .frames
200                .get(index)
201                .or_else(|| animation.frames.first())
202                .map_or_else(Self::default, |(_, image)| Self::Loaded(image.clone())),
203        }
204    }
205
206    pub fn with_nine_slice(self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
207        match self {
208            Self::Embedded(image) => image.with_nine_slice(edges).map(Self::Embedded),
209            Self::Loaded(image) => image.with_nine_slice(edges).map(Self::Loaded),
210            _ => Err(InvalidNineSlice),
211        }
212    }
213
214    pub fn pixels(&self) -> Option<ImagePixels<'_>> {
215        let (identity, format, bytes, size, edges) = match self {
216            Self::Embedded(Image::Embedded {
217                format,
218                bytes,
219                size,
220            }) => (
221                ImageIdentity::Embedded(bytes.as_ptr() as usize),
222                *format,
223                *bytes,
224                *size,
225                None,
226            ),
227            Self::Embedded(Image::NineSliced {
228                format,
229                bytes,
230                size,
231                edges,
232            }) => (
233                ImageIdentity::Embedded(bytes.as_ptr() as usize),
234                *format,
235                *bytes,
236                *size,
237                Some(*edges),
238            ),
239            Self::Loaded(image) => (
240                ImageIdentity::Loaded(image.source.id),
241                image.source.format,
242                image.bytes(),
243                image.source.size,
244                image.edges,
245            ),
246            _ => return None,
247        };
248        Some(ImagePixels {
249            identity,
250            format,
251            bytes,
252            size,
253            edges,
254        })
255    }
256}