1use super::{ImageBudget, ImageError, image};
4
5const MAX_LEVELS: usize = u32::BITS as usize;
6
7mod regions;
8pub(super) use regions::{MipRegion, MipRegionPlan};
9
10pub(super) fn validate_layout(
11 width: u32,
12 height: u32,
13 source_bytes: usize,
14 budget: ImageBudget,
15 limit: u32,
16 mode: TextureMipmaps3d,
17) -> Result<(), ImageError> {
18 MipLayout::new(width, height, source_bytes, budget, limit, mode).map(|_| ())
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27#[non_exhaustive]
28pub enum TextureMipmaps3d {
29 #[default]
31 None,
32 Generate,
39}
40
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42pub(super) struct MipLevel {
43 pub(super) width: u32,
44 pub(super) height: u32,
45 pub(super) offset: usize,
46 pub(super) byte_count: usize,
47}
48
49#[derive(Debug)]
50pub(in crate::renderer::mesh3d) struct CpuMipChain {
51 pixels: Vec<u8>,
52 layout: MipLayout,
53 budget: ImageBudget,
54 mode: TextureMipmaps3d,
55}
56
57#[derive(Debug, Clone, Copy)]
58struct MipLayout {
59 levels: [MipLevel; MAX_LEVELS],
60 count: usize,
61 byte_count: usize,
62}
63
64impl CpuMipChain {
65 pub(super) fn new(
66 width: u32,
67 height: u32,
68 pixels: Vec<u8>,
69 budget: ImageBudget,
70 maximum_texture_dimension: u32,
71 mode: TextureMipmaps3d,
72 ) -> Result<Self, ImageError> {
73 let layout = MipLayout::new(
74 width,
75 height,
76 pixels.len(),
77 budget,
78 maximum_texture_dimension,
79 mode,
80 )?;
81 let mut pixels = if pixels.capacity() > budget.max_bytes() {
84 let mut compact = allocate_pixels(layout.byte_count, budget)?;
85 compact.extend_from_slice(&pixels);
86 compact
87 } else {
88 let mut pixels = pixels;
89 let additional = layout.byte_count - pixels.len();
90 pixels
91 .try_reserve_exact(additional)
92 .map_err(|_| ImageError::AllocationFailed {
93 requested_bytes: layout.byte_count,
94 })?;
95 validate_capacity(pixels.capacity(), budget)?;
96 pixels
97 };
98 pixels.resize(layout.byte_count, 0);
99 if layout.count > 1 {
100 let linear_channels = std::array::from_fn::<_, 256, _>(|channel| {
101 let encoded = channel as f64 / 255.0;
102 if encoded <= 0.04045 {
103 encoded / 12.92
104 } else {
105 ((encoded + 0.055) / 1.055).powf(2.4)
106 }
107 });
108 for level in 1..layout.count {
109 let source = layout.levels[level - 1];
110 let destination = layout.levels[level];
111 let (earlier, later) = pixels.split_at_mut(destination.offset);
112 downsample(
113 &earlier[source.offset..source.offset + source.byte_count],
114 source.width,
115 source.height,
116 &mut later[..destination.byte_count],
117 destination.width,
118 destination.height,
119 &linear_channels,
120 );
121 }
122 }
123 Ok(Self {
124 pixels,
125 layout,
126 budget,
127 mode,
128 })
129 }
130
131 pub(super) fn size(&self) -> (u32, u32) {
132 (self.layout.levels[0].width, self.layout.levels[0].height)
133 }
134
135 pub(super) fn pixels(&self) -> &[u8] {
136 &self.pixels[..self.layout.levels[0].byte_count]
137 }
138
139 pub(super) fn level_pixels(&self, level: MipLevel) -> &[u8] {
140 &self.pixels[level.offset..level.offset + level.byte_count]
141 }
142
143 pub(super) fn levels(&self) -> &[MipLevel] {
144 &self.layout.levels[..self.layout.count]
145 }
146
147 pub(super) fn budget(&self) -> ImageBudget {
148 self.budget
149 }
150
151 pub(super) fn mode(&self) -> TextureMipmaps3d {
152 self.mode
153 }
154
155 pub(super) fn recovery_memory_bytes(&self) -> usize {
156 self.pixels.capacity()
157 }
158
159 pub(super) fn gpu_allocation_bytes(&self) -> usize {
160 self.layout.byte_count
161 }
162
163 pub(super) fn validate_device_limit(
164 &self,
165 maximum_texture_dimension: u32,
166 ) -> Result<(), ImageError> {
167 MipLayout::new(
168 self.size().0,
169 self.size().1,
170 self.pixels().len(),
171 self.budget,
172 maximum_texture_dimension,
173 self.mode,
174 )?;
175 Ok(())
176 }
177
178 pub(super) fn try_clone(&self) -> Result<Self, ImageError> {
179 let mut pixels = allocate_pixels(self.pixels.len(), self.budget)?;
180 pixels.extend_from_slice(&self.pixels);
181 Ok(Self {
182 pixels,
183 layout: self.layout,
184 budget: self.budget,
185 mode: self.mode,
186 })
187 }
188
189 pub(super) fn allocate_gpu(&self, device: &wgpu::Device) -> wgpu::Texture {
190 let (width, height) = self.size();
191 device.create_texture(&wgpu::TextureDescriptor {
192 label: Some("sim-engine retained 3D texture mip chain"),
193 size: wgpu::Extent3d {
194 width,
195 height,
196 depth_or_array_layers: 1,
197 },
198 mip_level_count: self.layout.count as u32,
199 sample_count: 1,
200 dimension: wgpu::TextureDimension::D2,
201 format: wgpu::TextureFormat::Rgba8UnormSrgb,
202 usage: wgpu::TextureUsages::TEXTURE_BINDING
203 | wgpu::TextureUsages::COPY_DST
204 | wgpu::TextureUsages::COPY_SRC,
205 view_formats: &[],
206 })
207 }
208
209 pub(super) fn upload_levels(
210 &self,
211 queue: &wgpu::Queue,
212 texture: &wgpu::Texture,
213 first_level: usize,
214 ) {
215 for (index, level) in self.levels().iter().copied().enumerate().skip(first_level) {
216 queue.write_texture(
217 wgpu::TexelCopyTextureInfo {
218 texture,
219 mip_level: index as u32,
220 origin: wgpu::Origin3d::ZERO,
221 aspect: wgpu::TextureAspect::All,
222 },
223 self.level_pixels(level),
224 wgpu::TexelCopyBufferLayout {
225 offset: 0,
226 bytes_per_row: Some(level.width * 4),
227 rows_per_image: Some(level.height),
228 },
229 wgpu::Extent3d {
230 width: level.width,
231 height: level.height,
232 depth_or_array_layers: 1,
233 },
234 );
235 }
236 }
237
238 pub(super) fn patch_base(&mut self, region: super::ImageTexelRect, packed: &[u8]) {
239 let width = self.size().0 as usize;
240 let row_bytes = region.width() as usize * 4;
241 for row in 0..region.height() as usize {
242 let offset = ((region.y() as usize + row) * width + region.x() as usize) * 4;
243 self.pixels[offset..offset + row_bytes]
244 .copy_from_slice(&packed[row * row_bytes..(row + 1) * row_bytes]);
245 }
246 }
247
248 pub(super) fn region_update_plan(
249 &self,
250 region: super::ImageTexelRect,
251 ) -> Result<MipRegionPlan, ImageError> {
252 MipRegionPlan::new(self.levels(), region)
253 }
254
255 pub(super) fn regenerate_regions(&mut self, plan: &MipRegionPlan) {
257 debug_assert_eq!(plan.size(), self.size());
258 debug_assert_eq!(plan.regions().len(), self.levels().len());
259 let base = plan.regions()[0];
260 if base.x == 0 && base.y == 0 && (base.width, base.height) == self.size() {
261 self.regenerate();
265 return;
266 }
267 if self.layout.count <= 1 {
268 return;
269 }
270 let linear_channels = linear_channels();
271 for level in 1..self.layout.count {
272 let source = self.layout.levels[level - 1];
273 let destination = self.layout.levels[level];
274 let (earlier, later) = self.pixels.split_at_mut(destination.offset);
275 downsample_region(
276 &earlier[source.offset..source.offset + source.byte_count],
277 source.width,
278 source.height,
279 &mut later[..destination.byte_count],
280 destination.width,
281 destination.height,
282 &linear_channels,
283 plan.regions()[level],
284 );
285 }
286 }
287
288 pub(super) fn regenerate(&mut self) {
289 if self.layout.count <= 1 {
290 return;
291 }
292 let linear_channels = linear_channels();
293 for level in 1..self.layout.count {
294 let source = self.layout.levels[level - 1];
295 let destination = self.layout.levels[level];
296 let (earlier, later) = self.pixels.split_at_mut(destination.offset);
297 downsample(
298 &earlier[source.offset..source.offset + source.byte_count],
299 source.width,
300 source.height,
301 &mut later[..destination.byte_count],
302 destination.width,
303 destination.height,
304 &linear_channels,
305 );
306 }
307 }
308}
309
310impl MipLayout {
311 fn new(
312 width: u32,
313 height: u32,
314 source_byte_count: usize,
315 budget: ImageBudget,
316 maximum_texture_dimension: u32,
317 mode: TextureMipmaps3d,
318 ) -> Result<Self, ImageError> {
319 image::validate_image_shape(
320 width,
321 height,
322 source_byte_count,
323 budget,
324 maximum_texture_dimension,
325 )?;
326 let mut result = Self {
327 levels: [MipLevel::default(); MAX_LEVELS],
328 count: 0,
329 byte_count: 0,
330 };
331 let mut width = width;
332 let mut height = height;
333 loop {
334 let byte_count = (width as usize)
335 .checked_mul(height as usize)
336 .and_then(|texels| texels.checked_mul(4))
337 .ok_or(ImageError::DimensionsTooLarge)?;
338 let offset = result.byte_count;
339 result.byte_count = offset
340 .checked_add(byte_count)
341 .ok_or(ImageError::DimensionsTooLarge)?;
342 if result.byte_count > budget.max_bytes() {
343 return Err(ImageError::BudgetExceeded {
344 limit: budget.max_bytes(),
345 actual: result.byte_count,
346 });
347 }
348 result.levels[result.count] = MipLevel {
349 width,
350 height,
351 offset,
352 byte_count,
353 };
354 result.count += 1;
355 if mode == TextureMipmaps3d::None || (width == 1 && height == 1) {
356 return Ok(result);
357 }
358 width = (width / 2).max(1);
359 height = (height / 2).max(1);
360 }
361 }
362}
363
364fn allocate_pixels(byte_count: usize, budget: ImageBudget) -> Result<Vec<u8>, ImageError> {
365 let mut pixels = Vec::new();
366 pixels
367 .try_reserve_exact(byte_count)
368 .map_err(|_| ImageError::AllocationFailed {
369 requested_bytes: byte_count,
370 })?;
371 validate_capacity(pixels.capacity(), budget)?;
372 Ok(pixels)
373}
374
375fn validate_capacity(capacity: usize, budget: ImageBudget) -> Result<(), ImageError> {
376 if capacity > budget.max_bytes() {
377 Err(ImageError::BudgetExceeded {
378 limit: budget.max_bytes(),
379 actual: capacity,
380 })
381 } else {
382 Ok(())
383 }
384}
385
386#[allow(clippy::too_many_arguments)]
387fn downsample(
388 source: &[u8],
389 source_width: u32,
390 source_height: u32,
391 destination: &mut [u8],
392 width: u32,
393 height: u32,
394 linear_channels: &[f64; 256],
395) {
396 let horizontal_ratio = f64::from(source_width) / f64::from(width);
399 let vertical_ratio = f64::from(source_height) / f64::from(height);
400 for y in 0..height {
401 let top = f64::from(y) * vertical_ratio;
402 let bottom = (f64::from(y) + 1.0) * vertical_ratio;
403 for x in 0..width {
404 let left = f64::from(x) * horizontal_ratio;
405 let right = (f64::from(x) + 1.0) * horizontal_ratio;
406 let mut channels = [0.0; 3];
407 let mut alpha_weight = 0.0;
408 let mut total_weight = 0.0;
409 for source_y in (top.floor() as u32)..(bottom.ceil() as u32).min(source_height) {
410 let vertical_weight =
411 bottom.min(f64::from(source_y) + 1.0) - top.max(f64::from(source_y));
412 for source_x in (left.floor() as u32)..(right.ceil() as u32).min(source_width) {
413 let horizontal_weight =
414 right.min(f64::from(source_x) + 1.0) - left.max(f64::from(source_x));
415 let weight = vertical_weight * horizontal_weight;
416 let index = (source_y as usize * source_width as usize + source_x as usize) * 4;
417 let alpha = f64::from(source[index + 3]) / 255.0;
418 for channel in 0..3 {
419 channels[channel] +=
420 linear_channels[source[index + channel] as usize] * alpha * weight;
421 }
422 alpha_weight += alpha * weight;
423 total_weight += weight;
424 }
425 }
426 let index = (y as usize * width as usize + x as usize) * 4;
427 let alpha = (alpha_weight / total_weight * 255.0).round() as u8;
428 if alpha == 0 {
429 destination[index..index + 4].fill(0);
430 continue;
431 }
432 for channel in 0..3 {
433 destination[index + channel] = linear_to_srgb8(channels[channel] / alpha_weight);
434 }
435 destination[index + 3] = alpha;
436 }
437 }
438}
439
440#[allow(clippy::too_many_arguments)]
444fn downsample_region(
445 source: &[u8],
446 source_width: u32,
447 source_height: u32,
448 destination: &mut [u8],
449 width: u32,
450 height: u32,
451 linear_channels: &[f64; 256],
452 region: MipRegion,
453) {
454 let horizontal_ratio = f64::from(source_width) / f64::from(width);
457 let vertical_ratio = f64::from(source_height) / f64::from(height);
458 for y in region.y..region.y + region.height {
459 let top = f64::from(y) * vertical_ratio;
460 let bottom = (f64::from(y) + 1.0) * vertical_ratio;
461 for x in region.x..region.x + region.width {
462 let left = f64::from(x) * horizontal_ratio;
463 let right = (f64::from(x) + 1.0) * horizontal_ratio;
464 let mut channels = [0.0; 3];
465 let mut alpha_weight = 0.0;
466 let mut total_weight = 0.0;
467 for source_y in (top.floor() as u32)..(bottom.ceil() as u32).min(source_height) {
468 let vertical_weight =
469 bottom.min(f64::from(source_y) + 1.0) - top.max(f64::from(source_y));
470 for source_x in (left.floor() as u32)..(right.ceil() as u32).min(source_width) {
471 let horizontal_weight =
472 right.min(f64::from(source_x) + 1.0) - left.max(f64::from(source_x));
473 let weight = vertical_weight * horizontal_weight;
474 let index = (source_y as usize * source_width as usize + source_x as usize) * 4;
475 let alpha = f64::from(source[index + 3]) / 255.0;
476 for channel in 0..3 {
477 channels[channel] +=
478 linear_channels[source[index + channel] as usize] * alpha * weight;
479 }
480 alpha_weight += alpha * weight;
481 total_weight += weight;
482 }
483 }
484 let index = (y as usize * width as usize + x as usize) * 4;
485 let alpha = (alpha_weight / total_weight * 255.0).round() as u8;
486 if alpha == 0 {
487 destination[index..index + 4].fill(0);
488 continue;
489 }
490 for channel in 0..3 {
491 destination[index + channel] = linear_to_srgb8(channels[channel] / alpha_weight);
492 }
493 destination[index + 3] = alpha;
494 }
495 }
496}
497
498fn linear_to_srgb8(linear: f64) -> u8 {
499 let encoded = if linear <= 0.0031308 {
500 linear * 12.92
501 } else {
502 1.055 * linear.powf(1.0 / 2.4) - 0.055
503 };
504 (encoded.clamp(0.0, 1.0) * 255.0).round() as u8
505}
506
507fn linear_channels() -> [f64; 256] {
508 std::array::from_fn(|channel| {
509 let encoded = channel as f64 / 255.0;
510 if encoded <= 0.04045 {
511 encoded / 12.92
512 } else {
513 ((encoded + 0.055) / 1.055).powf(2.4)
514 }
515 })
516}
517
518#[cfg(test)]
519mod tests;