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    pub fn new(format: ImageFormat, bytes: Vec<u8>, size: [u32; 2]) -> Self {
77        static NEXT_IMAGE: AtomicU64 = AtomicU64::new(1);
78        let id = NEXT_IMAGE
79            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
80            .expect("loaded image identity exhausted");
81        Self {
82            source: Arc::new(LoadedImageSource {
83                id,
84                format,
85                bytes,
86                size,
87            }),
88            edges: None,
89        }
90    }
91
92    pub fn size(&self) -> [u32; 2] {
93        self.source.size
94    }
95
96    pub(crate) fn with_nine_slice(mut self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
97        if !edges.fits(self.source.size) {
98            return Err(InvalidNineSlice);
99        }
100        self.edges = Some(edges);
101        Ok(self)
102    }
103
104    pub(crate) fn bytes(&self) -> &[u8] {
105        &self.source.bytes
106    }
107}
108
109impl PartialEq for LoadedImage {
110    fn eq(&self, other: &Self) -> bool {
111        self.edges == other.edges
112            && (Arc::ptr_eq(&self.source, &other.source)
113                || (self.source.size == other.source.size
114                    && self.source.format == other.source.format
115                    && self.source.bytes == other.source.bytes))
116    }
117}
118
119impl Eq for LoadedImage {}
120
121impl fmt::Debug for LoadedImage {
122    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
123        output
124            .debug_struct("LoadedImage")
125            .field("format", &self.source.format)
126            .field("size", &self.source.size)
127            .field("edges", &self.edges)
128            .finish()
129    }
130}
131
132#[derive(Debug, PartialEq, Eq)]
133pub struct LoadedAnimation {
134    pub(crate) size: [u32; 2],
135    pub(crate) frames: Vec<(u32, LoadedImage)>,
136    pub(crate) plays: u32,
137}
138
139impl LoadedAnimation {
140    pub fn new(size: [u32; 2], frames: Vec<(u32, Vec<u8>)>, plays: u32) -> Self {
141        Self {
142            size,
143            frames: frames
144                .into_iter()
145                .map(|(end, bytes)| (end, LoadedImage::new(ImageFormat::Png, bytes, size)))
146                .collect(),
147            plays,
148        }
149    }
150
151    #[doc(hidden)]
152    pub fn frames(&self) -> impl ExactSizeIterator<Item = (u32, &[u8])> {
153        self.frames.iter().map(|(end, frame)| (*end, frame.bytes()))
154    }
155}
156
157/// Identity for a cache entry. Loaded assets can outlive their original scene
158/// without making a later allocation at the same address hit an old texture.
159#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
160pub enum ImageIdentity {
161    Embedded(usize),
162    Loaded(u64),
163}
164
165pub struct ImagePixels<'a> {
166    pub identity: ImageIdentity,
167    pub format: ImageFormat,
168    pub bytes: &'a [u8],
169    pub size: [u32; 2],
170    pub edges: Option<NineSlice>,
171}
172
173impl ImageAsset {
174    pub fn size(&self) -> [u32; 2] {
175        match self {
176            Self::Embedded(image) => image.size(),
177            Self::Loaded(image) => image.source.size,
178            Self::Animated(animation) => animation.size,
179        }
180    }
181
182    pub fn frame_count(&self) -> usize {
183        match self {
184            Self::Embedded(image) => image.frame_count(),
185            Self::Loaded(_) => 1,
186            Self::Animated(animation) => animation.frames.len(),
187        }
188    }
189
190    pub fn frame(&self, index: usize) -> Self {
191        match self {
192            Self::Embedded(image) => image.clone().frame(index).into(),
193            Self::Loaded(_) => self.clone(),
194            Self::Animated(animation) => animation
195                .frames
196                .get(index)
197                .or_else(|| animation.frames.first())
198                .map_or_else(Self::default, |(_, image)| Self::Loaded(image.clone())),
199        }
200    }
201
202    pub fn with_nine_slice(self, edges: NineSlice) -> Result<Self, InvalidNineSlice> {
203        match self {
204            Self::Embedded(image) => image.with_nine_slice(edges).map(Self::Embedded),
205            Self::Loaded(image) => image.with_nine_slice(edges).map(Self::Loaded),
206            _ => Err(InvalidNineSlice),
207        }
208    }
209
210    pub fn pixels(&self) -> Option<ImagePixels<'_>> {
211        let (identity, format, bytes, size, edges) = match self {
212            Self::Embedded(Image::Embedded {
213                format,
214                bytes,
215                size,
216            }) => (
217                ImageIdentity::Embedded(bytes.as_ptr() as usize),
218                *format,
219                *bytes,
220                *size,
221                None,
222            ),
223            Self::Embedded(Image::NineSliced {
224                format,
225                bytes,
226                size,
227                edges,
228            }) => (
229                ImageIdentity::Embedded(bytes.as_ptr() as usize),
230                *format,
231                *bytes,
232                *size,
233                Some(*edges),
234            ),
235            Self::Loaded(image) => (
236                ImageIdentity::Loaded(image.source.id),
237                image.source.format,
238                image.bytes(),
239                image.source.size,
240                image.edges,
241            ),
242            _ => return None,
243        };
244        Some(ImagePixels {
245            identity,
246            format,
247            bytes,
248            size,
249            edges,
250        })
251    }
252}