sim_logic/rendering/three_d/
texture.rs1use std::{
4 error::Error,
5 fmt,
6 sync::{
7 Arc,
8 atomic::{AtomicU64, Ordering},
9 },
10};
11
12use sim_engine::{Color, TextureAddressMode3d, TextureUvTransform3d};
13
14use crate::screen::{ImageFilter, ImageRegion};
15
16static NEXT_TEXTURE_REVISION: AtomicU64 = AtomicU64::new(1);
17
18#[derive(Debug, Clone)]
24pub struct TextureAsset3d {
25 data: Arc<TextureData>,
26}
27
28#[derive(Debug)]
29struct TextureData {
30 width: u32,
31 height: u32,
32 pixels: Vec<u8>,
33 revision: u64,
34 parent: Option<u64>,
35 region: Option<ImageRegion>,
36}
37
38impl TextureAsset3d {
39 pub fn rgba8(
44 width: u32,
45 height: u32,
46 pixels: Vec<u8>,
47 max_source_bytes: usize,
48 ) -> Result<Self, TextureVisualError> {
49 let expected = pixel_bytes(width, height)?;
50 if pixels.len() != expected {
51 return Err(TextureVisualError::PixelLength {
52 expected,
53 actual: pixels.len(),
54 });
55 }
56 check_bytes(pixels.capacity(), max_source_bytes)?;
57 let revision = issue_revision()?;
58 Ok(Self {
59 data: Arc::new(TextureData {
60 width,
61 height,
62 pixels,
63 revision,
64 parent: None,
65 region: None,
66 }),
67 })
68 }
69
70 pub fn width(&self) -> u32 {
72 self.data.width
73 }
74
75 pub fn height(&self) -> u32 {
77 self.data.height
78 }
79
80 pub fn pixels(&self) -> &[u8] {
82 &self.data.pixels
83 }
84
85 pub fn source_bytes(&self) -> usize {
87 self.data.pixels.capacity()
88 }
89
90 pub fn shares_storage(&self, other: &Self) -> bool {
92 self.key() == other.key()
93 }
94
95 pub fn is_direct_revision_of(&self, previous: &Self) -> bool {
98 self.data.parent == Some(previous.key())
99 }
100
101 pub fn with_region_update(
113 &self,
114 region: ImageRegion,
115 row_stride: usize,
116 pixels: &[u8],
117 max_source_bytes: usize,
118 ) -> Result<Self, TextureVisualError> {
119 if region.x() + region.width() > self.width()
120 || region.y() + region.height() > self.height()
121 {
122 return Err(TextureVisualError::RegionOutOfBounds);
123 }
124 let row_bytes = pixel_bytes(region.width(), 1)?;
125 let required = (region.height() as usize - 1)
126 .checked_mul(row_stride)
127 .and_then(|bytes| bytes.checked_add(row_bytes))
128 .ok_or(TextureVisualError::SizeOverflow)?;
129 if row_stride < row_bytes || pixels.len() != required {
130 return Err(TextureVisualError::InvalidPatchLayout);
131 }
132 let size = self.pixels().len();
133 check_bytes(size, max_source_bytes)?;
134 let mut revised = Vec::new();
135 revised
136 .try_reserve_exact(size)
137 .map_err(|_| TextureVisualError::AllocationFailed {
138 requested_bytes: size,
139 })?;
140 check_bytes(revised.capacity(), max_source_bytes)?;
141 revised.extend_from_slice(self.pixels());
142 let destination_stride = pixel_bytes(self.width(), 1)?;
143 for row in 0..region.height() as usize {
144 let destination =
145 (region.y() as usize + row) * destination_stride + region.x() as usize * 4;
146 let source = row * row_stride;
147 revised[destination..destination + row_bytes]
148 .copy_from_slice(&pixels[source..source + row_bytes]);
149 }
150 Ok(Self {
151 data: Arc::new(TextureData {
152 width: self.width(),
153 height: self.height(),
154 pixels: revised,
155 revision: issue_revision()?,
156 parent: Some(self.key()),
157 region: Some(region),
158 }),
159 })
160 }
161
162 pub(crate) fn key(&self) -> u64 {
163 self.data.revision
164 }
165 #[cfg(feature = "desktop")]
166 pub(crate) fn parent_key(&self) -> Option<u64> {
167 self.data.parent
168 }
169 pub fn updated_region(&self) -> Option<ImageRegion> {
172 self.data.region
173 }
174}
175
176impl PartialEq for TextureAsset3d {
177 fn eq(&self, other: &Self) -> bool {
178 self.shares_storage(other)
179 }
180}
181impl Eq for TextureAsset3d {}
182
183#[derive(Debug, Clone, PartialEq)]
189pub struct TextureVisual3d {
190 asset: TextureAsset3d,
191 filter: ImageFilter,
192 mipmaps: bool,
193 address: TextureAddressMode3d,
194 transform: TextureUvTransform3d,
195 tint: Color,
196}
197
198impl TextureVisual3d {
199 pub fn new(asset: TextureAsset3d) -> Self {
201 Self {
202 asset,
203 filter: ImageFilter::Nearest,
204 mipmaps: false,
205 address: TextureAddressMode3d::Clamp,
206 transform: TextureUvTransform3d::IDENTITY,
207 tint: Color::WHITE,
208 }
209 }
210 pub const fn asset(&self) -> &TextureAsset3d {
212 &self.asset
213 }
214 pub const fn filter(&self) -> ImageFilter {
216 self.filter
217 }
218 pub const fn mipmaps(&self) -> bool {
220 self.mipmaps
221 }
222 pub const fn address_mode(&self) -> TextureAddressMode3d {
224 self.address
225 }
226 pub const fn uv_transform(&self) -> TextureUvTransform3d {
228 self.transform
229 }
230 pub const fn tint(&self) -> Color {
232 self.tint
233 }
234 pub fn with_filter(mut self, filter: ImageFilter) -> Self {
236 self.filter = filter;
237 self
238 }
239 pub fn with_mipmaps(mut self, enabled: bool) -> Self {
242 self.mipmaps = enabled;
243 self
244 }
245 pub fn with_address_mode(mut self, address: TextureAddressMode3d) -> Self {
247 self.address = address;
248 self
249 }
250 pub fn with_uv_transform(mut self, transform: TextureUvTransform3d) -> Self {
252 self.transform = transform;
253 self
254 }
255 pub fn with_asset(mut self, asset: TextureAsset3d) -> Self {
257 self.asset = asset;
258 self
259 }
260 pub fn with_tint(mut self, tint: Color) -> Result<Self, TextureVisualError> {
262 if !tint.is_normalized() {
263 return Err(TextureVisualError::InvalidTint);
264 }
265 self.tint = tint;
266 Ok(self)
267 }
268 pub fn texel_bytes(&self) -> Result<usize, TextureVisualError> {
271 let (mut width, mut height) = (self.asset.width(), self.asset.height());
272 let mut bytes = pixel_bytes(width, height)?;
273 while self.mipmaps && (width > 1 || height > 1) {
274 width = (width / 2).max(1);
275 height = (height / 2).max(1);
276 bytes = bytes
277 .checked_add(pixel_bytes(width, height)?)
278 .ok_or(TextureVisualError::SizeOverflow)?;
279 }
280 Ok(bytes)
281 }
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum TextureVisualError {
287 InvalidDimensions,
289 SizeOverflow,
291 PixelLength {
293 expected: usize,
295 actual: usize,
297 },
298 SourceLimit {
300 requested: usize,
302 limit: usize,
304 },
305 RegionOutOfBounds,
307 InvalidPatchLayout,
309 InvalidTint,
311 AllocationFailed {
313 requested_bytes: usize,
315 },
316 IdentityExhausted,
318}
319
320impl fmt::Display for TextureVisualError {
321 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
322 match self {
323 Self::InvalidDimensions => {
324 formatter.write_str("3D texture dimensions must be positive")
325 }
326 Self::SizeOverflow => formatter.write_str("3D texture byte count overflows usize"),
327 Self::PixelLength { expected, actual } => write!(
328 formatter,
329 "3D texture needs {expected} bytes, received {actual}"
330 ),
331 Self::SourceLimit { requested, limit } => write!(
332 formatter,
333 "3D texture capacity {requested} exceeds limit {limit}"
334 ),
335 Self::RegionOutOfBounds => {
336 formatter.write_str("3D texture patch lies outside source image")
337 }
338 Self::InvalidPatchLayout => {
339 formatter.write_str("3D texture patch stride or byte length is invalid")
340 }
341 Self::InvalidTint => formatter.write_str("3D texture tint must be normalized RGBA"),
342 Self::AllocationFailed { requested_bytes } => {
343 write!(formatter, "cannot reserve {requested_bytes} texture bytes")
344 }
345 Self::IdentityExhausted => {
346 formatter.write_str("3D texture revision identities exhausted")
347 }
348 }
349 }
350}
351impl Error for TextureVisualError {}
352
353fn pixel_bytes(width: u32, height: u32) -> Result<usize, TextureVisualError> {
354 if width == 0 || height == 0 {
355 return Err(TextureVisualError::InvalidDimensions);
356 }
357 (width as usize)
358 .checked_mul(height as usize)
359 .and_then(|value| value.checked_mul(4))
360 .ok_or(TextureVisualError::SizeOverflow)
361}
362
363fn check_bytes(requested: usize, limit: usize) -> Result<(), TextureVisualError> {
364 if requested > limit {
365 return Err(TextureVisualError::SourceLimit { requested, limit });
366 }
367 Ok(())
368}
369
370fn issue_revision() -> Result<u64, TextureVisualError> {
371 NEXT_TEXTURE_REVISION
372 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
373 value.checked_add(1)
374 })
375 .map_err(|_| TextureVisualError::IdentityExhausted)
376}