sim-engine 0.4.0

A validated high-performance visualization engine for simulations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! Immutable straight-alpha texture materials for the retained 3D surface path.

use super::*;
use crate::mesh3d::{TextureAddressMode3d, TextureCoordinate2d, TextureUvTransform3d};
#[path = "mesh3d_texture_mips.rs"]
mod mips;
use mips::CpuMipChain;
pub use mips::TextureMipmaps3d;
#[path = "mesh3d_texture_options.rs"]
mod options;
pub use options::Texture3dOptions;
#[path = "mesh3d_texture_creation.rs"]
mod creation;
#[cfg(test)]
pub(super) use creation::{create_texture_with_options, crop_texture_tile};
#[path = "mesh3d_texture_updates.rs"]
mod updates;
pub use updates::{
    Texture3dUpdateBudget, Texture3dUpdateBudgetResource, Texture3dUpdateError,
    Texture3dUpdateReport,
};
#[cfg(test)]
pub(super) use updates::{update_scene_texture_region, update_texture_region};

#[cfg(test)]
#[path = "mesh3d_texture_red_tests.rs"]
mod red_tests;
#[cfg(test)]
#[path = "mesh3d_texture_tests.rs"]
mod tests;
#[cfg(test)]
pub(super) use tests::{assert_gpu_texture_contract, assert_gpu_textured_recovery};
#[cfg(test)]
#[path = "mesh3d_texture_lifecycle_tests.rs"]
mod lifecycle_tests;
#[cfg(test)]
pub(super) use lifecycle_tests::{
    assert_gpu_texture_lifecycle, assert_gpu_texture_lifecycle_recovery,
};
#[cfg(test)]
#[path = "mesh3d_dev5_tests.rs"]
mod dev5_tests;
#[cfg(test)]
pub(super) use dev5_tests::assert_dev5_contract;

/// Validation or allocation failure for a retained 3D texture/material.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Texture3dError {
    /// Image dimensions, retained bytes, allocation or device limits failed.
    Image(ImageError),
    /// The first texel with alpha other than 255 in row-major source order.
    NonOpaquePixel {
        /// Zero-based source texel index.
        texel: usize,
    },
    /// Tint must be normalized linear RGBA; the legacy constructor also requires alpha one.
    InvalidTint,
    /// Attaching a texture requires a surface and one UV per mesh vertex.
    MissingTextureCoordinates,
    /// Texture and mesh must belong to the renderer's current device identity.
    RendererMismatch,
    /// An atlas region does not fit the texture.
    InvalidRegion,
    /// Region-coordinate insets cannot isolate entries of a generated whole-atlas mip chain.
    MipmappedAtlasRegion,
}

impl fmt::Display for Texture3dError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Image(error) => write!(formatter, "3D texture: {error}"),
            Self::NonOpaquePixel { texel } => {
                write!(formatter, "3D texture texel {texel} is not opaque")
            }
            Self::InvalidTint => write!(
                formatter,
                "3D texture tint must be normalized; alpha requires the explicit with_alpha constructor"
            ),
            Self::MissingTextureCoordinates => {
                write!(formatter, "textured 3D surfaces require per-vertex UVs")
            }
            Self::RendererMismatch => {
                write!(formatter, "3D texture/mesh belongs to another renderer")
            }
            Self::InvalidRegion => write!(formatter, "3D texture atlas region is out of bounds"),
            Self::MipmappedAtlasRegion => write!(
                formatter,
                "crop an independent 3D tile before mip filtering; atlas UV insets do not isolate mip levels"
            ),
        }
    }
}
impl Error for Texture3dError {}

struct TextureStorage {
    renderer_identity: Arc<()>,
    chain: CpuMipChain,
    texture: wgpu::Texture,
    bindings: [wgpu::BindGroup; 4],
    preserve_alpha: bool,
    first_nonopaque_texel: Option<usize>,
}

/// Cheap immutable snapshot of an independently filtered sRGB RGBA8 mip chain.
///
/// Clones share CPU recovery pixels and the GPU allocation. U/V has a top-left
/// origin; material addressing defaults to clamp. Mipmap generation is opt-in.
/// Region updates preserve old aliases through copy-on-write. Crop snapshots
/// are independent of later parent-atlas updates.
/// Legacy creation accepts alpha 255 only; explicit alpha creation preserves it.
/// Restoring returns a new device-owned handle and replays the alpha policy;
/// existing clones remain stale until explicitly rebound or scene-restored.
#[derive(Clone)]
pub struct Texture3d {
    storage: Arc<TextureStorage>,
}

impl Texture3d {
    /// Returns physical source texel dimensions.
    pub fn size(&self) -> (u32, u32) {
        self.storage.chain.size()
    }
    /// Returns immutable retained row-major, top-to-bottom sRGB RGBA8 texels.
    pub fn pixels(&self) -> &[u8] {
        self.storage.chain.pixels()
    }
    /// Returns complete committed mip count, including the source level.
    pub fn mip_level_count(&self) -> u32 {
        self.storage.chain.levels().len() as u32
    }
    /// Returns exact source/generated bytes of one committed level, or None.
    pub fn mip_level_pixels(&self, level: u32) -> Option<&[u8]> {
        self.storage
            .chain
            .levels()
            .get(level as usize)
            .map(|level| self.storage.chain.level_pixels(*level))
    }
    /// Returns dimensions of one committed level, or None.
    pub fn mip_level_size(&self, level: u32) -> Option<(u32, u32)> {
        self.storage
            .chain
            .levels()
            .get(level as usize)
            .map(|level| (level.width, level.height))
    }
    /// Returns mip policy, which survives restoration and region updates.
    pub fn mipmaps(&self) -> TextureMipmaps3d {
        self.storage.chain.mode()
    }
    /// Returns the alpha/mip policy retained with this immutable snapshot.
    pub fn options(&self) -> Texture3dOptions {
        Texture3dOptions::new()
            .with_mipmaps(self.mipmaps())
            .with_alpha_preservation(self.preserves_alpha())
    }
    /// Whether creation explicitly preserved arbitrary source alpha for mask/blend use.
    pub fn preserves_alpha(&self) -> bool {
        self.storage.preserve_alpha
    }
    /// Returns creation limits retained for restoration.
    pub fn budget(&self) -> ImageBudget {
        self.storage.chain.budget()
    }
    /// Returns shared CPU recovery-pixel capacity, excluding fixed handle metadata.
    pub fn recovery_memory_bytes(&self) -> usize {
        self.storage.chain.recovery_memory_bytes()
    }
    /// Returns nominal complete-chain GPU texel bytes, excluding driver metadata.
    pub fn gpu_allocation_bytes(&self) -> usize {
        self.storage.chain.gpu_allocation_bytes()
    }
    /// Maps top-left, top-right, bottom-right and bottom-left corners of an
    /// atlas region to its outer texel centers. Nearest sampling avoids adjacent
    /// cells under this mip-zero policy. For strict linear-filter isolation,
    /// provide host-owned extruded gutters around atlas cells: interpolation
    /// rounding can extend the filtering footprint slightly beyond a center.
    /// A one-texel extent maps both edges to its center.
    /// Generated multi-level textures reject this operation: crop an independent
    /// tile instead of filtering or repeating a packed whole-atlas mip chain.
    pub fn region_coordinates(
        &self,
        region: ImageTexelRect,
    ) -> Result<[TextureCoordinate2d; 4], Texture3dError> {
        if self.mip_level_count() > 1 {
            return Err(Texture3dError::MipmappedAtlasRegion);
        }
        let (width, height) = self.size();
        if !region.fits(width, height) {
            return Err(Texture3dError::InvalidRegion);
        }
        let left = (region.x() as f64 + 0.5) / f64::from(width);
        let right = (f64::from(region.x()) + f64::from(region.width()) - 0.5) / f64::from(width);
        let top = (region.y() as f64 + 0.5) / f64::from(height);
        let bottom = (f64::from(region.y()) + f64::from(region.height()) - 0.5) / f64::from(height);
        let make = |u: f64, v: f64| {
            TextureCoordinate2d::new(u as f32, v as f32).map_err(|_| Texture3dError::InvalidRegion)
        };
        Ok([
            make(left, top)?,
            make(right, top)?,
            make(right, bottom)?,
            make(left, bottom)?,
        ])
    }
    pub(super) fn identity_key(&self) -> usize {
        Arc::as_ptr(&self.storage) as usize
    }
    pub(super) fn belongs_to(&self, identity: &Arc<()>) -> bool {
        Arc::ptr_eq(identity, &self.storage.renderer_identity)
    }
    fn bind_group(
        &self,
        sampling: ImageSampling,
        address: TextureAddressMode3d,
    ) -> &wgpu::BindGroup {
        &self.storage.bindings[usize::from(address == TextureAddressMode3d::Repeat) * 2
            + usize::from(sampling == ImageSampling::Linear)]
    }
}

/// Cheap immutable unlit material sharing one texture and filter state.
///
/// Sampled straight-linear RGBA multiplies vertex color, this tint and the
/// object's surface tint. Surface style selects alpha coverage, depth-write
/// behavior and projected sidedness. No lighting is implied.
#[derive(Clone)]
pub struct TextureMaterial3d {
    texture: Texture3d,
    sampling: ImageSampling,
    tint: Color,
    uv_transform: TextureUvTransform3d,
    address_mode: TextureAddressMode3d,
    require_opaque_texture: bool,
}

impl TextureMaterial3d {
    /// Creates a legacy opaque material; tint must be normalized with alpha one,
    /// and every source texel must have alpha 255, even for alpha-capable textures.
    pub fn new(
        texture: &Texture3d,
        sampling: ImageSampling,
        tint: Color,
    ) -> Result<Self, Texture3dError> {
        if !tint.is_normalized() || tint.alpha() != 1.0 {
            return Err(Texture3dError::InvalidTint);
        }
        if let Some(texel) = texture.storage.first_nonopaque_texel {
            return Err(Texture3dError::NonOpaquePixel { texel });
        }
        let mut material = Self::with_alpha(texture, sampling, tint)?;
        material.require_opaque_texture = true;
        Ok(material)
    }
    /// Creates a material preserving normalized straight-linear tint and texture alpha.
    /// Coverage/depth behavior is chosen by each object's surface style.
    pub fn with_alpha(
        texture: &Texture3d,
        sampling: ImageSampling,
        tint: Color,
    ) -> Result<Self, Texture3dError> {
        if !tint.is_normalized() {
            return Err(Texture3dError::InvalidTint);
        }
        Ok(Self {
            texture: texture.clone(),
            sampling,
            tint,
            uv_transform: TextureUvTransform3d::IDENTITY,
            address_mode: TextureAddressMode3d::Clamp,
            require_opaque_texture: false,
        })
    }
    /// Applies validated continuous UV scale then offset, before hardware addressing.
    pub fn with_uv_transform(mut self, transform: TextureUvTransform3d) -> Self {
        self.uv_transform = transform;
        self
    }
    /// Selects addressing of the whole texture; Repeat requires an isolated image for tile safety.
    pub fn with_address_mode(mut self, mode: TextureAddressMode3d) -> Self {
        self.address_mode = mode;
        self
    }
    /// Rebinds a new texture snapshot while preserving tint, filtering, UV and alpha policy.
    /// Legacy opaque materials reject a new snapshot containing nonopaque texels.
    pub fn with_texture(&self, texture: &Texture3d) -> Result<Self, Texture3dError> {
        if self.require_opaque_texture
            && let Some(texel) = texture.storage.first_nonopaque_texel
        {
            return Err(Texture3dError::NonOpaquePixel { texel });
        }
        Ok(self.with_restored_texture(texture))
    }
    /// Returns continuous pre-addressing coordinate transformation.
    pub const fn uv_transform(&self) -> TextureUvTransform3d {
        self.uv_transform
    }
    /// Returns complete-image clamp/repeat addressing.
    pub const fn address_mode(&self) -> TextureAddressMode3d {
        self.address_mode
    }
    /// Returns the shared immutable texture handle.
    pub const fn texture(&self) -> &Texture3d {
        &self.texture
    }
    /// Returns nearest or linear filtering. Generated chains use nearest-mip or
    /// trilinear sampling respectively, with derivative-selected LOD. Alpha-aware
    /// mip generation does not make straight-RGBA bilinear filtering fringe-free.
    pub const fn sampling(&self) -> ImageSampling {
        self.sampling
    }
    /// Returns the normalized multiplicative straight-linear RGBA tint.
    pub const fn tint(&self) -> Color {
        self.tint
    }
    pub(super) fn bind_group(&self) -> &wgpu::BindGroup {
        self.texture.bind_group(self.sampling, self.address_mode)
    }
    pub(super) fn with_restored_texture(&self, texture: &Texture3d) -> Self {
        Self {
            texture: texture.clone(),
            sampling: self.sampling,
            tint: self.tint,
            uv_transform: self.uv_transform,
            address_mode: self.address_mode,
            require_opaque_texture: self.require_opaque_texture,
        }
    }
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(super) struct MeshUvGpu {
    pub(super) coordinate: [f32; 2],
}

impl MeshUvGpu {
    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![5 => Float32x2];
    pub(super) const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<Self>() as u64,
        step_mode: wgpu::VertexStepMode::Vertex,
        attributes: &Self::ATTRIBUTES,
    };
}

pub(super) struct MeshTextureRenderer {
    pub(super) layout: wgpu::BindGroupLayout,
    pub(super) retained_pipeline: SurfacePipelines,
    pub(super) clipped_pipeline: SurfacePipelines,
    pub(super) colored_retained_pipeline: SurfacePipelines,
    pub(super) colored_clipped_pipeline: SurfacePipelines,
}

impl MeshTextureRenderer {
    pub(super) fn new(
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        camera_layout: &wgpu::BindGroupLayout,
    ) -> Self {
        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("sim-engine 3D texture layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("sim-engine textured 3D surfaces"),
            source: wgpu::ShaderSource::Wgsl(lighting::shader_source(include_str!(
                "mesh3d_texture.wgsl"
            ))),
        });
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("sim-engine textured 3D pipeline layout"),
            bind_group_layouts: &[Some(camera_layout), Some(&layout)],
            immediate_size: 0,
        });
        let pipeline = |clipped: bool, colored: bool| {
            create_surface_pipelines(
                device,
                format,
                &pipeline_layout,
                &shader,
                SurfaceLayout {
                    clipped,
                    colored,
                    textured: true,
                },
            )
        };
        Self {
            retained_pipeline: pipeline(false, false),
            clipped_pipeline: pipeline(true, false),
            colored_retained_pipeline: pipeline(false, true),
            colored_clipped_pipeline: pipeline(true, true),
            layout,
        }
    }
}

impl WgpuRenderer {
    /// Creates immutable opaque sRGB RGBA8 texels with shared nearest/linear bindings.
    /// Image/device limits and every alpha byte are validated before GPU creation.
    pub fn create_texture3d_rgba8(
        &self,
        width: u32,
        height: u32,
        pixels: Vec<u8>,
        budget: ImageBudget,
    ) -> Result<Texture3d, Texture3dError> {
        create_texture(
            &self.device,
            &self.queue,
            &self.renderer_identity,
            &self.mesh3d_renderer.textures.layout,
            width,
            height,
            pixels,
            budget,
        )
    }

    /// Creates sRGB RGBA8 texels with explicitly preserved straight alpha.
    /// Mask/blend materials sample alpha; Opaque surfaces deliberately ignore it.
    pub fn create_texture3d_rgba8_with_alpha(
        &self,
        width: u32,
        height: u32,
        pixels: Vec<u8>,
        budget: ImageBudget,
    ) -> Result<Texture3d, Texture3dError> {
        create_texture_with_alpha(
            &self.device,
            &self.queue,
            &self.renderer_identity,
            &self.mesh3d_renderer.textures.layout,
            width,
            height,
            pixels,
            budget,
        )
    }

    /// Restores exact retained pixels on the current device. Existing handles
    /// remain unchanged; atomic `restore_scene3d` restores shared textures once.
    pub fn restore_texture3d(&self, source: &Texture3d) -> Result<Texture3d, Texture3dError> {
        restore_texture(
            &self.device,
            &self.queue,
            &self.renderer_identity,
            &self.mesh3d_renderer.textures.layout,
            source,
        )
    }

    /// Associates a shared material with a new retained mesh handle without
    /// allocating/uploading topology. Existing clones and scene users keep
    /// their previous material; rebind selected IDs using `Scene3d::set_mesh`.
    pub fn with_mesh3d_material(
        &self,
        mesh: &RetainedMesh3d,
        material: &TextureMaterial3d,
    ) -> Result<RetainedMesh3d, Texture3dError> {
        attach_material(&self.renderer_identity, mesh, material)
    }
}

pub(super) fn restore_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    identity: &Arc<()>,
    layout: &wgpu::BindGroupLayout,
    source: &Texture3d,
) -> Result<Texture3d, Texture3dError> {
    source
        .storage
        .chain
        .validate_device_limit(device.limits().max_texture_dimension_2d)
        .map_err(Texture3dError::Image)?;
    let chain = source
        .storage
        .chain
        .try_clone()
        .map_err(Texture3dError::Image)?;
    Ok(upload_chain(
        device,
        queue,
        identity,
        layout,
        chain,
        source.preserves_alpha(),
    ))
}

pub(super) fn attach_material(
    identity: &Arc<()>,
    mesh: &RetainedMesh3d,
    material: &TextureMaterial3d,
) -> Result<RetainedMesh3d, Texture3dError> {
    if !Arc::ptr_eq(identity, &mesh.renderer_identity) || !material.texture.belongs_to(identity) {
        return Err(Texture3dError::RendererMismatch);
    }
    if mesh.source.texture_coordinates().len() != mesh.source.vertices().len()
        || mesh.source.triangle_count() == 0
        || mesh.texture_coordinate_buffer.is_none()
    {
        return Err(Texture3dError::MissingTextureCoordinates);
    }
    let mut result = mesh.clone();
    result.material = Some(material.clone());
    Ok(result)
}

pub(super) fn material_uv_parameters(material: Option<&TextureMaterial3d>) -> [f32; 4] {
    let transform = material.map_or(
        TextureUvTransform3d::IDENTITY,
        TextureMaterial3d::uv_transform,
    );
    [
        transform.scale().x(),
        transform.scale().y(),
        transform.offset().x(),
        transform.offset().y(),
    ]
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    identity: &Arc<()>,
    layout: &wgpu::BindGroupLayout,
    width: u32,
    height: u32,
    pixels: Vec<u8>,
    budget: ImageBudget,
) -> Result<Texture3d, Texture3dError> {
    create_texture_impl(
        device, queue, identity, layout, width, height, pixels, budget, false,
    )
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_texture_with_alpha(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    identity: &Arc<()>,
    layout: &wgpu::BindGroupLayout,
    width: u32,
    height: u32,
    pixels: Vec<u8>,
    budget: ImageBudget,
) -> Result<Texture3d, Texture3dError> {
    create_texture_impl(
        device, queue, identity, layout, width, height, pixels, budget, true,
    )
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_texture_impl(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    identity: &Arc<()>,
    layout: &wgpu::BindGroupLayout,
    width: u32,
    height: u32,
    pixels: Vec<u8>,
    budget: ImageBudget,
    preserve_alpha: bool,
) -> Result<Texture3d, Texture3dError> {
    image::validate_image_shape(
        width,
        height,
        pixels.len(),
        budget,
        device.limits().max_texture_dimension_2d,
    )
    .map_err(Texture3dError::Image)?;
    let first_nonopaque_texel = pixels.chunks_exact(4).position(|pixel| pixel[3] != 255);
    if !preserve_alpha && let Some(texel) = first_nonopaque_texel {
        return Err(Texture3dError::NonOpaquePixel { texel });
    }
    let chain = CpuMipChain::new(
        width,
        height,
        pixels,
        budget,
        device.limits().max_texture_dimension_2d,
        TextureMipmaps3d::None,
    )
    .map_err(Texture3dError::Image)?;
    Ok(upload_chain(
        device,
        queue,
        identity,
        layout,
        chain,
        preserve_alpha,
    ))
}

pub(super) fn upload_chain(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    identity: &Arc<()>,
    layout: &wgpu::BindGroupLayout,
    chain: CpuMipChain,
    preserve_alpha: bool,
) -> Texture3d {
    let texture = chain.allocate_gpu(device);
    let bindings = create_bindings(device, layout, &texture, chain.levels().len());
    chain.upload_levels(queue, &texture, 0);
    submit_pending_uploads(queue);
    let first_nonopaque_texel = chain
        .pixels()
        .chunks_exact(4)
        .position(|pixel| pixel[3] != 255);
    Texture3d {
        storage: Arc::new(TextureStorage {
            renderer_identity: Arc::clone(identity),
            chain,
            texture,
            bindings,
            preserve_alpha,
            first_nonopaque_texel,
        }),
    }
}

fn create_bindings(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    texture: &wgpu::Texture,
    levels: usize,
) -> [wgpu::BindGroup; 4] {
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    std::array::from_fn(|index| {
        let address = if index >= 2 {
            wgpu::AddressMode::Repeat
        } else {
            wgpu::AddressMode::ClampToEdge
        };
        let linear = index % 2 == 1;
        let filter = if linear {
            wgpu::FilterMode::Linear
        } else {
            wgpu::FilterMode::Nearest
        };
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("sim-engine 3D texture sampler"),
            address_mode_u: address,
            address_mode_v: address,
            mag_filter: filter,
            min_filter: filter,
            mipmap_filter: if linear {
                wgpu::MipmapFilterMode::Linear
            } else {
                wgpu::MipmapFilterMode::Nearest
            },
            lod_min_clamp: 0.0,
            lod_max_clamp: (levels - 1) as f32,
            ..Default::default()
        });
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sim-engine 3D texture binding"),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        })
    })
}

pub(super) struct PreparedTextureRestore {
    pub(super) key: usize,
    pub(super) source: Texture3d,
    pub(super) chain: Option<CpuMipChain>,
}

pub(super) fn prepare_scene_restoration(
    device: &wgpu::Device,
    identity: &Arc<()>,
    scene: &Scene3d,
) -> Result<Vec<PreparedTextureRestore>, Mesh3dResourceError> {
    let mut prepared = Vec::new();
    prepared
        .try_reserve_exact(scene.object_count())
        .map_err(|_| Mesh3dResourceError::HostAllocationFailed {
            requested_bytes: scene
                .object_count()
                .saturating_mul(std::mem::size_of::<PreparedTextureRestore>())
                as u64,
        })?;
    for instance in scene.instances() {
        if let Some(material) = instance.mesh.material()
            && !material.texture().belongs_to(identity)
        {
            prepared.push(PreparedTextureRestore {
                key: material.texture().identity_key(),
                source: material.texture().clone(),
                chain: None,
            });
        }
    }
    prepared.sort_unstable_by_key(|texture| texture.key);
    prepared.dedup_by_key(|texture| texture.key);
    for texture in &mut prepared {
        let source = &texture.source;
        image::validate_image_shape(
            source.size().0,
            source.size().1,
            source.pixels().len(),
            source.budget(),
            device.limits().max_texture_dimension_2d,
        )
        .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?;
        source
            .storage
            .chain
            .validate_device_limit(device.limits().max_texture_dimension_2d)
            .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?;
        texture.chain = Some(
            source
                .storage
                .chain
                .try_clone()
                .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?,
        );
    }
    Ok(prepared)
}