dream_soft_render/
texture.rs1use std::collections::HashMap;
4use std::fmt;
5use std::hash::{BuildHasherDefault, Hasher};
6use std::io;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::Error;
10
11#[cfg(feature = "egui")]
12mod egui_textures;
13
14#[cfg(feature = "egui")]
15pub(crate) use egui_textures::TextureDeltaStats;
16
17pub const MAX_TEXTURE_BYTES: usize = 8 * 1024 * 1024;
20
21pub(crate) const MAX_TEXTURE_SIDE: usize = 65_536;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct TextureId(pub(crate) u64);
34
35static NEXT_TEXTURE_ID: AtomicU64 = AtomicU64::new(0);
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub(crate) enum TextureKey {
42 #[cfg(feature = "egui")]
43 Egui(egui::TextureId),
44 Native(TextureId),
45}
46
47impl TextureId {
48 pub(crate) fn issue() -> Option<Self> {
54 issue_from(&NEXT_TEXTURE_ID).map(Self)
55 }
56}
57
58impl fmt::Display for TextureId {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 write!(f, "#{}", self.0)
61 }
62}
63
64fn issue_from(counter: &AtomicU64) -> Option<u64> {
65 #[allow(deprecated)]
67 counter
68 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
69 next.checked_add(1)
70 })
71 .ok()
72}
73
74pub(crate) static EMPTY_TEXTURE: TextureImage = TextureImage {
76 width: 0,
77 height: 0,
78 pixels: Vec::new(),
79};
80
81#[derive(Default)]
85struct TextureKeyHasher(u64);
86
87impl Hasher for TextureKeyHasher {
88 fn finish(&self) -> u64 {
89 self.0
90 }
91
92 fn write(&mut self, bytes: &[u8]) {
93 for &byte in bytes {
94 self.write_u64(u64::from(byte));
95 }
96 }
97
98 fn write_u64(&mut self, value: u64) {
99 self.0 = (self.0.rotate_left(5) ^ value).wrapping_mul(0x517c_c1b7_2722_0a95);
100 }
101
102 fn write_usize(&mut self, value: usize) {
103 self.write_u64(value as u64);
104 }
105}
106
107#[derive(Debug, Default)]
108pub(crate) struct TextureStore {
109 textures: HashMap<TextureKey, TextureImage, BuildHasherDefault<TextureKeyHasher>>,
110 bytes_used: usize,
111}
112
113impl TextureStore {
114 pub(crate) fn insert_native(
115 &mut self,
116 id: TextureId,
117 width: usize,
118 height: usize,
119 pixels: &[u8],
120 ) -> Result<(), Error> {
121 if width == 0 || height == 0 || width > MAX_TEXTURE_SIDE || height > MAX_TEXTURE_SIDE {
122 return Err(Error::TextureSize { width, height });
123 }
124 let expected = rgba8_byte_len(width, height).ok_or(Error::TextureSize { width, height })?;
125 check_pixel_data_length(expected, pixels)?;
126 let requested = self.bytes_used.saturating_add(expected);
127 if requested > MAX_TEXTURE_BYTES {
128 return Err(Error::TextureBudget {
129 requested,
130 budget: MAX_TEXTURE_BYTES,
131 });
132 }
133 self.textures.insert(
134 TextureKey::Native(id),
135 TextureImage {
136 width,
137 height,
138 pixels: pixels.to_vec(),
139 },
140 );
141 self.bytes_used = requested;
142 Ok(())
143 }
144
145 pub(crate) fn update_native(
146 &mut self,
147 id: TextureId,
148 pos: [usize; 2],
149 size: [usize; 2],
150 pixels: &[u8],
151 ) -> Result<(), Error> {
152 let [width, height] = size;
153 let expected = rgba8_byte_len(width, height).ok_or(Error::TextureUpdateOutOfBounds(id))?;
154 check_pixel_data_length(expected, pixels)?;
155 let texture = self
156 .textures
157 .get_mut(&TextureKey::Native(id))
158 .ok_or(Error::UnknownTexture(id))?;
159 texture
160 .validate_update_bounds(pos, width, height)
161 .map_err(|_| Error::TextureUpdateOutOfBounds(id))?;
162 let row_bytes = width * 4;
163 for (row, source) in pixels
164 .chunks_exact(row_bytes.max(1))
165 .enumerate()
166 .take(height)
167 {
168 let destination = ((pos[1] + row) * texture.width + pos[0]) * 4;
169 texture.pixels[destination..destination + row_bytes].copy_from_slice(source);
170 }
171 Ok(())
172 }
173
174 pub(crate) fn free_native(&mut self, id: TextureId) -> Result<(), Error> {
175 if self.textures.contains_key(&TextureKey::Native(id)) {
176 self.free(TextureKey::Native(id));
177 Ok(())
178 } else {
179 Err(Error::UnknownTexture(id))
180 }
181 }
182
183 fn free(&mut self, id: TextureKey) {
184 if let Some(texture) = self.textures.remove(&id) {
185 self.bytes_used = self
186 .bytes_used
187 .checked_sub(texture.pixels.len())
188 .expect("texture byte accounting underflow");
189 }
190 }
191
192 pub(crate) fn get(&self, id: TextureKey) -> Option<&TextureImage> {
193 self.textures.get(&id)
194 }
195
196 #[cfg(feature = "egui")]
197 pub(crate) fn len(&self) -> usize {
198 self.textures.len()
199 }
200
201 #[cfg(feature = "egui")]
202 pub(crate) fn bytes_used(&self) -> usize {
203 self.bytes_used
204 }
205}
206
207#[derive(Debug, Clone, Eq, PartialEq)]
208pub(crate) struct TextureImage {
209 pub(crate) width: usize,
210 pub(crate) height: usize,
211 pub(crate) pixels: Vec<u8>,
212}
213
214impl TextureImage {
215 fn validate_update_bounds(
216 &self,
217 pos: [usize; 2],
218 width: usize,
219 height: usize,
220 ) -> io::Result<()> {
221 let x_end = pos[0]
222 .checked_add(width)
223 .ok_or_else(|| io::Error::other("partial texture x range overflow"))?;
224 let y_end = pos[1]
225 .checked_add(height)
226 .ok_or_else(|| io::Error::other("partial texture y range overflow"))?;
227 if x_end > self.width || y_end > self.height {
228 return Err(io::Error::other(
229 "partial texture update exceeds texture bounds",
230 ));
231 }
232 Ok(())
233 }
234}
235
236fn rgba8_byte_len(width: usize, height: usize) -> Option<usize> {
237 width.checked_mul(height)?.checked_mul(4)
238}
239
240fn check_pixel_data_length(expected: usize, pixels: &[u8]) -> Result<(), Error> {
241 if pixels.len() == expected {
242 Ok(())
243 } else {
244 Err(Error::PixelDataLength {
245 expected,
246 actual: pixels.len(),
247 })
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn texture_id_issuance_stops_instead_of_wrapping() {
257 let counter = AtomicU64::new(u64::MAX - 2);
258 assert_eq!(issue_from(&counter), Some(u64::MAX - 2));
259 assert_eq!(issue_from(&counter), Some(u64::MAX - 1));
260 assert_eq!(issue_from(&counter), None);
261 assert_eq!(issue_from(&counter), None);
262 }
263}