Skip to main content

sim_engine/renderer/
mesh3d_texture_mips.rs

1//! Bounded mip chains for independently filtered textures.
2
3use super::{ImageBudget, ImageError, image};
4
5const MAX_LEVELS: usize = u32::BITS as usize;
6
7pub(super) fn validate_layout(
8    width: u32,
9    height: u32,
10    source_bytes: usize,
11    budget: ImageBudget,
12    limit: u32,
13    mode: TextureMipmaps3d,
14) -> Result<(), ImageError> {
15    MipLayout::new(width, height, source_bytes, budget, limit, mode).map(|_| ())
16}
17
18/// Optional mip generation for a retained 3D texture.
19///
20/// This policy applies to a complete, independently filtered image, not to
21/// individual cells of a packed atlas. Crop each tile into its own texture
22/// before generating mipmaps when neighboring cells must remain isolated.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24#[non_exhaustive]
25pub enum TextureMipmaps3d {
26    /// Keep the supplied image unchanged and sample only its original level.
27    #[default]
28    None,
29    /// Generate every level down to 1 x 1 with an area-weighted box filter.
30    ///
31    /// RGB is filtered in linear light with premultiplied alpha, then converted
32    /// back to straight sRGB RGBA8. Source pixels remain byte-exact. Generated
33    /// levels with alpha rounded to zero have zero RGB. This does not preserve
34    /// alpha-test coverage: thin masked features can disappear in distant mips.
35    Generate,
36}
37
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub(super) struct MipLevel {
40    pub(super) width: u32,
41    pub(super) height: u32,
42    pub(super) offset: usize,
43    pub(super) byte_count: usize,
44}
45
46#[derive(Debug)]
47pub(in crate::renderer::mesh3d) struct CpuMipChain {
48    pixels: Vec<u8>,
49    layout: MipLayout,
50    budget: ImageBudget,
51    mode: TextureMipmaps3d,
52}
53
54#[derive(Debug, Clone, Copy)]
55struct MipLayout {
56    levels: [MipLevel; MAX_LEVELS],
57    count: usize,
58    byte_count: usize,
59}
60
61impl CpuMipChain {
62    pub(super) fn new(
63        width: u32,
64        height: u32,
65        pixels: Vec<u8>,
66        budget: ImageBudget,
67        maximum_texture_dimension: u32,
68        mode: TextureMipmaps3d,
69    ) -> Result<Self, ImageError> {
70        let layout = MipLayout::new(
71            width,
72            height,
73            pixels.len(),
74            budget,
75            maximum_texture_dimension,
76            mode,
77        )?;
78        // Preflight includes every generated level before reserving storage.
79        // An over-capacity caller Vec must not bypass the retained byte limit.
80        let mut pixels = if pixels.capacity() > budget.max_bytes() {
81            let mut compact = allocate_pixels(layout.byte_count, budget)?;
82            compact.extend_from_slice(&pixels);
83            compact
84        } else {
85            let mut pixels = pixels;
86            let additional = layout.byte_count - pixels.len();
87            pixels
88                .try_reserve_exact(additional)
89                .map_err(|_| ImageError::AllocationFailed {
90                    requested_bytes: layout.byte_count,
91                })?;
92            validate_capacity(pixels.capacity(), budget)?;
93            pixels
94        };
95        pixels.resize(layout.byte_count, 0);
96        if layout.count > 1 {
97            let linear_channels = std::array::from_fn::<_, 256, _>(|channel| {
98                let encoded = channel as f64 / 255.0;
99                if encoded <= 0.04045 {
100                    encoded / 12.92
101                } else {
102                    ((encoded + 0.055) / 1.055).powf(2.4)
103                }
104            });
105            for level in 1..layout.count {
106                let source = layout.levels[level - 1];
107                let destination = layout.levels[level];
108                let (earlier, later) = pixels.split_at_mut(destination.offset);
109                downsample(
110                    &earlier[source.offset..source.offset + source.byte_count],
111                    source.width,
112                    source.height,
113                    &mut later[..destination.byte_count],
114                    destination.width,
115                    destination.height,
116                    &linear_channels,
117                );
118            }
119        }
120        Ok(Self {
121            pixels,
122            layout,
123            budget,
124            mode,
125        })
126    }
127
128    pub(super) fn size(&self) -> (u32, u32) {
129        (self.layout.levels[0].width, self.layout.levels[0].height)
130    }
131
132    pub(super) fn pixels(&self) -> &[u8] {
133        &self.pixels[..self.layout.levels[0].byte_count]
134    }
135
136    pub(super) fn level_pixels(&self, level: MipLevel) -> &[u8] {
137        &self.pixels[level.offset..level.offset + level.byte_count]
138    }
139
140    pub(super) fn levels(&self) -> &[MipLevel] {
141        &self.layout.levels[..self.layout.count]
142    }
143
144    pub(super) fn budget(&self) -> ImageBudget {
145        self.budget
146    }
147
148    pub(super) fn mode(&self) -> TextureMipmaps3d {
149        self.mode
150    }
151
152    pub(super) fn recovery_memory_bytes(&self) -> usize {
153        self.pixels.capacity()
154    }
155
156    pub(super) fn gpu_allocation_bytes(&self) -> usize {
157        self.layout.byte_count
158    }
159
160    pub(super) fn validate_device_limit(
161        &self,
162        maximum_texture_dimension: u32,
163    ) -> Result<(), ImageError> {
164        MipLayout::new(
165            self.size().0,
166            self.size().1,
167            self.pixels().len(),
168            self.budget,
169            maximum_texture_dimension,
170            self.mode,
171        )?;
172        Ok(())
173    }
174
175    pub(super) fn try_clone(&self) -> Result<Self, ImageError> {
176        let mut pixels = allocate_pixels(self.pixels.len(), self.budget)?;
177        pixels.extend_from_slice(&self.pixels);
178        Ok(Self {
179            pixels,
180            layout: self.layout,
181            budget: self.budget,
182            mode: self.mode,
183        })
184    }
185
186    pub(super) fn allocate_gpu(&self, device: &wgpu::Device) -> wgpu::Texture {
187        let (width, height) = self.size();
188        device.create_texture(&wgpu::TextureDescriptor {
189            label: Some("sim-engine retained 3D texture mip chain"),
190            size: wgpu::Extent3d {
191                width,
192                height,
193                depth_or_array_layers: 1,
194            },
195            mip_level_count: self.layout.count as u32,
196            sample_count: 1,
197            dimension: wgpu::TextureDimension::D2,
198            format: wgpu::TextureFormat::Rgba8UnormSrgb,
199            usage: wgpu::TextureUsages::TEXTURE_BINDING
200                | wgpu::TextureUsages::COPY_DST
201                | wgpu::TextureUsages::COPY_SRC,
202            view_formats: &[],
203        })
204    }
205
206    pub(super) fn upload_levels(
207        &self,
208        queue: &wgpu::Queue,
209        texture: &wgpu::Texture,
210        first_level: usize,
211    ) {
212        for (index, level) in self.levels().iter().copied().enumerate().skip(first_level) {
213            queue.write_texture(
214                wgpu::TexelCopyTextureInfo {
215                    texture,
216                    mip_level: index as u32,
217                    origin: wgpu::Origin3d::ZERO,
218                    aspect: wgpu::TextureAspect::All,
219                },
220                self.level_pixels(level),
221                wgpu::TexelCopyBufferLayout {
222                    offset: 0,
223                    bytes_per_row: Some(level.width * 4),
224                    rows_per_image: Some(level.height),
225                },
226                wgpu::Extent3d {
227                    width: level.width,
228                    height: level.height,
229                    depth_or_array_layers: 1,
230                },
231            );
232        }
233    }
234
235    pub(super) fn patch_base(&mut self, region: super::ImageTexelRect, packed: &[u8]) {
236        let width = self.size().0 as usize;
237        let row_bytes = region.width() as usize * 4;
238        for row in 0..region.height() as usize {
239            let offset = ((region.y() as usize + row) * width + region.x() as usize) * 4;
240            self.pixels[offset..offset + row_bytes]
241                .copy_from_slice(&packed[row * row_bytes..(row + 1) * row_bytes]);
242        }
243    }
244
245    pub(super) fn regenerate(&mut self) {
246        if self.layout.count <= 1 {
247            return;
248        }
249        let linear_channels = linear_channels();
250        for level in 1..self.layout.count {
251            let source = self.layout.levels[level - 1];
252            let destination = self.layout.levels[level];
253            let (earlier, later) = self.pixels.split_at_mut(destination.offset);
254            downsample(
255                &earlier[source.offset..source.offset + source.byte_count],
256                source.width,
257                source.height,
258                &mut later[..destination.byte_count],
259                destination.width,
260                destination.height,
261                &linear_channels,
262            );
263        }
264    }
265}
266
267impl MipLayout {
268    fn new(
269        width: u32,
270        height: u32,
271        source_byte_count: usize,
272        budget: ImageBudget,
273        maximum_texture_dimension: u32,
274        mode: TextureMipmaps3d,
275    ) -> Result<Self, ImageError> {
276        image::validate_image_shape(
277            width,
278            height,
279            source_byte_count,
280            budget,
281            maximum_texture_dimension,
282        )?;
283        let mut result = Self {
284            levels: [MipLevel::default(); MAX_LEVELS],
285            count: 0,
286            byte_count: 0,
287        };
288        let mut width = width;
289        let mut height = height;
290        loop {
291            let byte_count = (width as usize)
292                .checked_mul(height as usize)
293                .and_then(|texels| texels.checked_mul(4))
294                .ok_or(ImageError::DimensionsTooLarge)?;
295            let offset = result.byte_count;
296            result.byte_count = offset
297                .checked_add(byte_count)
298                .ok_or(ImageError::DimensionsTooLarge)?;
299            if result.byte_count > budget.max_bytes() {
300                return Err(ImageError::BudgetExceeded {
301                    limit: budget.max_bytes(),
302                    actual: result.byte_count,
303                });
304            }
305            result.levels[result.count] = MipLevel {
306                width,
307                height,
308                offset,
309                byte_count,
310            };
311            result.count += 1;
312            if mode == TextureMipmaps3d::None || (width == 1 && height == 1) {
313                return Ok(result);
314            }
315            width = (width / 2).max(1);
316            height = (height / 2).max(1);
317        }
318    }
319}
320
321fn allocate_pixels(byte_count: usize, budget: ImageBudget) -> Result<Vec<u8>, ImageError> {
322    let mut pixels = Vec::new();
323    pixels
324        .try_reserve_exact(byte_count)
325        .map_err(|_| ImageError::AllocationFailed {
326            requested_bytes: byte_count,
327        })?;
328    validate_capacity(pixels.capacity(), budget)?;
329    Ok(pixels)
330}
331
332fn validate_capacity(capacity: usize, budget: ImageBudget) -> Result<(), ImageError> {
333    if capacity > budget.max_bytes() {
334        Err(ImageError::BudgetExceeded {
335            limit: budget.max_bytes(),
336            actual: capacity,
337        })
338    } else {
339        Ok(())
340    }
341}
342
343#[allow(clippy::too_many_arguments)]
344fn downsample(
345    source: &[u8],
346    source_width: u32,
347    source_height: u32,
348    destination: &mut [u8],
349    width: u32,
350    height: u32,
351    linear_channels: &[f64; 256],
352) {
353    // Integer-halving dimensions still need the entire source extent. Using a
354    // fractional footprint includes the last row/column of odd-sized images.
355    let horizontal_ratio = f64::from(source_width) / f64::from(width);
356    let vertical_ratio = f64::from(source_height) / f64::from(height);
357    for y in 0..height {
358        let top = f64::from(y) * vertical_ratio;
359        let bottom = (f64::from(y) + 1.0) * vertical_ratio;
360        for x in 0..width {
361            let left = f64::from(x) * horizontal_ratio;
362            let right = (f64::from(x) + 1.0) * horizontal_ratio;
363            let mut channels = [0.0; 3];
364            let mut alpha_weight = 0.0;
365            let mut total_weight = 0.0;
366            for source_y in (top.floor() as u32)..(bottom.ceil() as u32).min(source_height) {
367                let vertical_weight =
368                    bottom.min(f64::from(source_y) + 1.0) - top.max(f64::from(source_y));
369                for source_x in (left.floor() as u32)..(right.ceil() as u32).min(source_width) {
370                    let horizontal_weight =
371                        right.min(f64::from(source_x) + 1.0) - left.max(f64::from(source_x));
372                    let weight = vertical_weight * horizontal_weight;
373                    let index = (source_y as usize * source_width as usize + source_x as usize) * 4;
374                    let alpha = f64::from(source[index + 3]) / 255.0;
375                    for channel in 0..3 {
376                        channels[channel] +=
377                            linear_channels[source[index + channel] as usize] * alpha * weight;
378                    }
379                    alpha_weight += alpha * weight;
380                    total_weight += weight;
381                }
382            }
383            let index = (y as usize * width as usize + x as usize) * 4;
384            let alpha = (alpha_weight / total_weight * 255.0).round() as u8;
385            if alpha == 0 {
386                destination[index..index + 4].fill(0);
387                continue;
388            }
389            for channel in 0..3 {
390                destination[index + channel] = linear_to_srgb8(channels[channel] / alpha_weight);
391            }
392            destination[index + 3] = alpha;
393        }
394    }
395}
396
397fn linear_to_srgb8(linear: f64) -> u8 {
398    let encoded = if linear <= 0.0031308 {
399        linear * 12.92
400    } else {
401        1.055 * linear.powf(1.0 / 2.4) - 0.055
402    };
403    (encoded.clamp(0.0, 1.0) * 255.0).round() as u8
404}
405
406fn linear_channels() -> [f64; 256] {
407    std::array::from_fn(|channel| {
408        let encoded = channel as f64 / 255.0;
409        if encoded <= 0.04045 {
410            encoded / 12.92
411        } else {
412            ((encoded + 0.055) / 1.055).powf(2.4)
413        }
414    })
415}
416
417#[cfg(test)]
418#[path = "mesh3d_texture_mips_tests.rs"]
419mod tests;