Skip to main content

sim_logic/rendering/three_d/
texture.rs

1//! Immutable CPU texture snapshots and sampling descriptors, never GPU handles.
2
3use 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/// Shared immutable, top-left-origin sRGB RGBA8 pixels with straight alpha.
19///
20/// Construction requires an explicit source-capacity limit. Clones share CPU
21/// pixels; editing returns a new snapshot and never modifies existing aliases.
22/// Engine generates mipmaps and owns filtering, GPU uploads and recovery.
23#[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    /// Takes exactly `width * height * 4` tightly packed bytes without copying.
40    /// Dimensions must be positive, arithmetic must fit usize, and the Vec's
41    /// capacity must fit the inclusive limit. Small Arc metadata is not charged.
42    /// This validates CPU data only; device-specific limits are checked on upload.
43    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    /// Returns the positive image width in texels.
71    pub fn width(&self) -> u32 {
72        self.data.width
73    }
74
75    /// Returns the positive image height in texels.
76    pub fn height(&self) -> u32 {
77        self.data.height
78    }
79
80    /// Returns tightly packed immutable base-level sRGB RGBA8 bytes.
81    pub fn pixels(&self) -> &[u8] {
82        &self.data.pixels
83    }
84
85    /// Returns retained base-level pixel capacity, excluding fixed Arc metadata.
86    pub fn source_bytes(&self) -> usize {
87        self.data.pixels.capacity()
88    }
89
90    /// Reports shared snapshot identity, not equality of pixel contents.
91    pub fn shares_storage(&self, other: &Self) -> bool {
92        self.key() == other.key()
93    }
94
95    /// Reports whether this snapshot was patched directly from the given snapshot.
96    /// Equal pixel contents do not imply a revision relationship.
97    pub fn is_direct_revision_of(&self, previous: &Self) -> bool {
98        self.data.parent == Some(previous.key())
99    }
100
101    /// Copies a rectangular strided patch into a new complete CPU snapshot.
102    ///
103    /// `row_stride` is in bytes and must cover each patch row. The input length
104    /// must equal `(height - 1) * row_stride + width * 4`; final-row padding is
105    /// not supplied. The inclusive limit bounds this new pixel allocation;
106    /// callers retaining old snapshots also retain their separately charged
107    /// storage. Failure leaves all existing snapshots unchanged.
108    ///
109    /// Only the immediate parent's identity and dirty rectangle are retained,
110    /// not its pixels or an edit history. Desktop can patch that exact revision;
111    /// skipped or branched revisions safely fall back to a full replacement.
112    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    /// Returns the patch from the immediate parent, or None for a fresh image.
170    /// It is not a cumulative patch relative to arbitrary older snapshots.
171    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/// One shared CPU image with independent material sampling and tint.
184///
185/// Alpha is preserved; the mesh surface decides Opaque/Mask/Blend behavior.
186/// Repeating or mipmapped packed-atlas tiles must first be isolated into separate
187/// images. This descriptor neither shapes UVs nor generates mipmap pixels.
188#[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    /// Uses nearest filtering, mip zero, clamp addressing, identity UVs and white tint.
200    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    /// Returns the shared immutable pixel snapshot.
211    pub const fn asset(&self) -> &TextureAsset3d {
212        &self.asset
213    }
214    /// Returns nearest or linear image filtering.
215    pub const fn filter(&self) -> ImageFilter {
216        self.filter
217    }
218    /// Reports whether Engine generates a complete mip chain.
219    pub const fn mipmaps(&self) -> bool {
220        self.mipmaps
221    }
222    /// Returns complete-image addressing, never packed-atlas tile addressing.
223    pub const fn address_mode(&self) -> TextureAddressMode3d {
224        self.address
225    }
226    /// Returns continuous scale then offset before sampling.
227    pub const fn uv_transform(&self) -> TextureUvTransform3d {
228        self.transform
229    }
230    /// Returns normalized straight-linear multiplicative RGBA tint.
231    pub const fn tint(&self) -> Color {
232        self.tint
233    }
234    /// Selects nearest or linear filtering without changing shared pixels.
235    pub fn with_filter(mut self, filter: ImageFilter) -> Self {
236        self.filter = filter;
237        self
238    }
239    /// Requests a complete Engine-generated mip chain rather than mip zero only.
240    /// Ordinary mip averaging does not preserve Mask alpha-test coverage.
241    pub fn with_mipmaps(mut self, enabled: bool) -> Self {
242        self.mipmaps = enabled;
243        self
244    }
245    /// Selects clamp or hardware repetition of this complete independent image.
246    pub fn with_address_mode(mut self, address: TextureAddressMode3d) -> Self {
247        self.address = address;
248        self
249    }
250    /// Selects an Engine-validated affine UV transform, including signed scales.
251    pub fn with_uv_transform(mut self, transform: TextureUvTransform3d) -> Self {
252        self.transform = transform;
253        self
254    }
255    /// Replaces the pixel snapshot, preserving independent sampling and tint.
256    pub fn with_asset(mut self, asset: TextureAsset3d) -> Self {
257        self.asset = asset;
258        self
259    }
260    /// Selects normalized straight-linear RGBA tint, rejecting invalid channels.
261    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    /// Returns exact nominal RGBA8 mip texel bytes, excluding driver metadata.
269    /// This does not allocate or generate mip levels.
270    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/// Invalid CPU texture data or a failed bounded snapshot allocation.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum TextureVisualError {
287    /// Image dimensions must both be positive.
288    InvalidDimensions,
289    /// Pixel or mip-chain byte arithmetic cannot be represented by usize.
290    SizeOverflow,
291    /// Base-level input length does not exactly match RGBA8 dimensions.
292    PixelLength {
293        /// Required tightly packed byte length.
294        expected: usize,
295        /// Supplied byte length.
296        actual: usize,
297    },
298    /// Retained pixel capacity exceeds the explicit inclusive limit.
299    SourceLimit {
300        /// Required or allocated pixel capacity.
301        requested: usize,
302        /// Inclusive caller-provided capacity allowance.
303        limit: usize,
304    },
305    /// A patch rectangle lies outside the image.
306    RegionOutOfBounds,
307    /// Patch row stride or exact input byte length is invalid.
308    InvalidPatchLayout,
309    /// Tint channels are not finite and normalized in 0..=1.
310    InvalidTint,
311    /// A fallible CPU pixel reservation was rejected.
312    AllocationFailed {
313        /// Requested new pixel capacity in bytes.
314        requested_bytes: usize,
315    },
316    /// Process-local monotonic revision identities are exhausted.
317    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}