Skip to main content

sim_engine/renderer/
mesh3d_texture.rs

1//! Immutable opaque texture materials for the retained 3D surface path.
2
3use super::*;
4use crate::mesh3d::TextureCoordinate2d;
5
6#[cfg(test)]
7#[path = "mesh3d_texture_red_tests.rs"]
8mod red_tests;
9#[cfg(test)]
10#[path = "mesh3d_texture_tests.rs"]
11mod tests;
12#[cfg(test)]
13pub(super) use tests::{assert_gpu_texture_contract, assert_gpu_textured_recovery};
14
15/// Validation or allocation failure for an opaque retained 3D texture/material.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Texture3dError {
18    /// Image dimensions, retained bytes, allocation or device limits failed.
19    Image(ImageError),
20    /// The first texel with alpha other than 255 in row-major source order.
21    NonOpaquePixel {
22        /// Zero-based source texel index.
23        texel: usize,
24    },
25    /// A material tint must be normalized linear RGBA with alpha exactly one.
26    InvalidTint,
27    /// Attaching a texture requires a surface and one UV per mesh vertex.
28    MissingTextureCoordinates,
29    /// Texture and mesh must belong to the renderer's current device identity.
30    RendererMismatch,
31    /// An atlas region does not fit the texture.
32    InvalidRegion,
33}
34
35impl fmt::Display for Texture3dError {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Image(error) => write!(formatter, "3D texture: {error}"),
39            Self::NonOpaquePixel { texel } => {
40                write!(formatter, "3D texture texel {texel} is not opaque")
41            }
42            Self::InvalidTint => write!(formatter, "3D texture tint must be normalized and opaque"),
43            Self::MissingTextureCoordinates => {
44                write!(formatter, "textured 3D surfaces require per-vertex UVs")
45            }
46            Self::RendererMismatch => {
47                write!(formatter, "3D texture/mesh belongs to another renderer")
48            }
49            Self::InvalidRegion => write!(formatter, "3D texture atlas region is out of bounds"),
50        }
51    }
52}
53impl Error for Texture3dError {}
54
55struct TextureStorage {
56    renderer_identity: Arc<()>,
57    image: Image2d,
58    nearest: wgpu::BindGroup,
59    linear: wgpu::BindGroup,
60}
61
62/// Cheap shared handle for immutable opaque, single-level sRGB RGBA8 texels.
63///
64/// Clones share CPU recovery pixels and the GPU allocation. U/V has a top-left
65/// origin; addressing clamps to the image boundary, with no mipmap generation.
66/// Only alpha 255 is accepted. Restoring returns a new device-owned handle;
67/// existing clones remain stale until explicitly rebound or scene-restored.
68#[derive(Clone)]
69pub struct Texture3d {
70    storage: Arc<TextureStorage>,
71}
72
73impl Texture3d {
74    /// Returns physical source texel dimensions.
75    pub fn size(&self) -> (u32, u32) {
76        self.storage.image.size()
77    }
78    /// Returns immutable retained row-major, top-to-bottom sRGB RGBA8 texels.
79    pub fn pixels(&self) -> &[u8] {
80        self.storage.image.pixels()
81    }
82    /// Returns creation limits retained for restoration.
83    pub fn budget(&self) -> ImageBudget {
84        self.storage.image.budget()
85    }
86    /// Returns shared CPU recovery-pixel capacity, excluding fixed handle metadata.
87    pub fn recovery_memory_bytes(&self) -> usize {
88        self.storage.image.recovery_memory_bytes()
89    }
90    /// Returns nominal single-level GPU texel bytes, excluding driver metadata.
91    pub fn gpu_allocation_bytes(&self) -> usize {
92        self.storage.image.gpu_allocation_bytes()
93    }
94    /// Maps top-left, top-right, bottom-right and bottom-left corners of an
95    /// atlas region to its outer texel centers. Nearest sampling avoids adjacent
96    /// cells under this mip-zero policy. For strict linear-filter isolation,
97    /// provide host-owned extruded gutters around atlas cells: interpolation
98    /// rounding can extend the filtering footprint slightly beyond a center.
99    /// A one-texel extent maps both edges to its center.
100    pub fn region_coordinates(
101        &self,
102        region: ImageTexelRect,
103    ) -> Result<[TextureCoordinate2d; 4], Texture3dError> {
104        let (width, height) = self.size();
105        if !region.fits(width, height) {
106            return Err(Texture3dError::InvalidRegion);
107        }
108        let left = (region.x() as f64 + 0.5) / f64::from(width);
109        let right = (f64::from(region.x()) + f64::from(region.width()) - 0.5) / f64::from(width);
110        let top = (region.y() as f64 + 0.5) / f64::from(height);
111        let bottom = (f64::from(region.y()) + f64::from(region.height()) - 0.5) / f64::from(height);
112        let make = |u: f64, v: f64| {
113            TextureCoordinate2d::new(u as f32, v as f32).map_err(|_| Texture3dError::InvalidRegion)
114        };
115        Ok([
116            make(left, top)?,
117            make(right, top)?,
118            make(right, bottom)?,
119            make(left, bottom)?,
120        ])
121    }
122    pub(super) fn identity_key(&self) -> usize {
123        Arc::as_ptr(&self.storage) as usize
124    }
125    pub(super) fn belongs_to(&self, identity: &Arc<()>) -> bool {
126        Arc::ptr_eq(identity, &self.storage.renderer_identity)
127    }
128    fn bind_group(&self, sampling: ImageSampling) -> &wgpu::BindGroup {
129        match sampling {
130            ImageSampling::Nearest => &self.storage.nearest,
131            ImageSampling::Linear => &self.storage.linear,
132        }
133    }
134}
135
136/// Cheap immutable unlit material sharing one opaque texture and filter state.
137///
138/// Sampled linear RGB is multiplied by this normalized opaque tint and the
139/// object's `SurfaceStyle3d` color. Depth writes/tests and no-culling winding
140/// semantics are identical to ordinary opaque surfaces. Transparency, lighting
141/// and alpha-cutout are intentionally separate capabilities.
142#[derive(Clone)]
143pub struct TextureMaterial3d {
144    texture: Texture3d,
145    sampling: ImageSampling,
146    tint: Color,
147}
148
149impl TextureMaterial3d {
150    /// Creates an immutable material; tint is normalized and fully opaque.
151    pub fn new(
152        texture: &Texture3d,
153        sampling: ImageSampling,
154        tint: Color,
155    ) -> Result<Self, Texture3dError> {
156        if !tint.is_normalized() || tint.alpha() != 1.0 {
157            return Err(Texture3dError::InvalidTint);
158        }
159        Ok(Self {
160            texture: texture.clone(),
161            sampling,
162            tint,
163        })
164    }
165    /// Returns the shared immutable texture handle.
166    pub const fn texture(&self) -> &Texture3d {
167        &self.texture
168    }
169    /// Returns nearest or linear mip-zero sampling.
170    pub const fn sampling(&self) -> ImageSampling {
171        self.sampling
172    }
173    /// Returns multiplicative opaque linear-RGBA tint.
174    pub const fn tint(&self) -> Color {
175        self.tint
176    }
177    pub(super) fn bind_group(&self) -> &wgpu::BindGroup {
178        self.texture.bind_group(self.sampling)
179    }
180    pub(super) fn with_restored_texture(&self, texture: &Texture3d) -> Self {
181        Self {
182            texture: texture.clone(),
183            sampling: self.sampling,
184            tint: self.tint,
185        }
186    }
187}
188
189#[repr(C)]
190#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
191pub(super) struct MeshUvGpu {
192    pub(super) coordinate: [f32; 2],
193}
194
195impl MeshUvGpu {
196    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![5 => Float32x2];
197    pub(super) const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
198        array_stride: std::mem::size_of::<Self>() as u64,
199        step_mode: wgpu::VertexStepMode::Vertex,
200        attributes: &Self::ATTRIBUTES,
201    };
202}
203
204pub(super) struct MeshTextureRenderer {
205    pub(super) layout: wgpu::BindGroupLayout,
206    pub(super) retained_pipeline: wgpu::RenderPipeline,
207    pub(super) clipped_pipeline: wgpu::RenderPipeline,
208}
209
210impl MeshTextureRenderer {
211    pub(super) fn new(
212        device: &wgpu::Device,
213        format: wgpu::TextureFormat,
214        camera_layout: &wgpu::BindGroupLayout,
215    ) -> Self {
216        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
217            label: Some("sim-engine 3D texture layout"),
218            entries: &[
219                wgpu::BindGroupLayoutEntry {
220                    binding: 0,
221                    visibility: wgpu::ShaderStages::FRAGMENT,
222                    ty: wgpu::BindingType::Texture {
223                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
224                        view_dimension: wgpu::TextureViewDimension::D2,
225                        multisampled: false,
226                    },
227                    count: None,
228                },
229                wgpu::BindGroupLayoutEntry {
230                    binding: 1,
231                    visibility: wgpu::ShaderStages::FRAGMENT,
232                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
233                    count: None,
234                },
235            ],
236        });
237        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
238            label: Some("sim-engine textured 3D surfaces"),
239            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("mesh3d_texture.wgsl"))),
240        });
241        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
242            label: Some("sim-engine textured 3D pipeline layout"),
243            bind_group_layouts: &[Some(camera_layout), Some(&layout)],
244            immediate_size: 0,
245        });
246        let pipeline = |clipped: bool| {
247            let buffers = if clipped {
248                vec![
249                    Some(SurfaceClipVertex::TEXTURED_LAYOUT),
250                    Some(MeshInstanceGpu::LAYOUT),
251                ]
252            } else {
253                vec![
254                    Some(MeshVertexGpu::LAYOUT),
255                    Some(MeshUvGpu::LAYOUT),
256                    Some(MeshInstanceGpu::LAYOUT),
257                ]
258            };
259            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
260                label: Some("sim-engine opaque textured 3D pipeline"),
261                layout: Some(&pipeline_layout),
262                vertex: wgpu::VertexState {
263                    module: &shader,
264                    entry_point: Some(if clipped {
265                        "clipped_vs_main"
266                    } else {
267                        "retained_vs_main"
268                    }),
269                    compilation_options: wgpu::PipelineCompilationOptions::default(),
270                    buffers: &buffers,
271                },
272                primitive: wgpu::PrimitiveState {
273                    topology: wgpu::PrimitiveTopology::TriangleList,
274                    ..Default::default()
275                },
276                depth_stencil: Some(wgpu::DepthStencilState {
277                    format: DEPTH_FORMAT,
278                    depth_write_enabled: Some(true),
279                    depth_compare: Some(wgpu::CompareFunction::Less),
280                    stencil: wgpu::StencilState::default(),
281                    bias: wgpu::DepthBiasState::default(),
282                }),
283                multisample: wgpu::MultisampleState::default(),
284                fragment: Some(wgpu::FragmentState {
285                    module: &shader,
286                    entry_point: Some("fs_main"),
287                    compilation_options: wgpu::PipelineCompilationOptions::default(),
288                    targets: &[Some(wgpu::ColorTargetState {
289                        format,
290                        blend: None,
291                        write_mask: wgpu::ColorWrites::ALL,
292                    })],
293                }),
294                multiview_mask: None,
295                cache: None,
296            })
297        };
298        Self {
299            retained_pipeline: pipeline(false),
300            clipped_pipeline: pipeline(true),
301            layout,
302        }
303    }
304}
305
306impl WgpuRenderer {
307    /// Creates immutable opaque sRGB RGBA8 texels with shared nearest/linear bindings.
308    /// Image/device limits and every alpha byte are validated before GPU creation.
309    pub fn create_texture3d_rgba8(
310        &self,
311        width: u32,
312        height: u32,
313        pixels: Vec<u8>,
314        budget: ImageBudget,
315    ) -> Result<Texture3d, Texture3dError> {
316        create_texture(
317            &self.device,
318            &self.queue,
319            &self.renderer_identity,
320            &self.mesh3d_renderer.textures.layout,
321            width,
322            height,
323            pixels,
324            budget,
325        )
326    }
327
328    /// Restores exact retained pixels on the current device. Existing handles
329    /// remain unchanged; atomic `restore_scene3d` restores shared textures once.
330    pub fn restore_texture3d(&self, source: &Texture3d) -> Result<Texture3d, Texture3dError> {
331        image::validate_image_shape(
332            source.size().0,
333            source.size().1,
334            source.pixels().len(),
335            source.budget(),
336            self.device.limits().max_texture_dimension_2d,
337        )
338        .map_err(Texture3dError::Image)?;
339        let pixels = copy_recovery_pixels(source)?;
340        self.create_texture3d_rgba8(source.size().0, source.size().1, pixels, source.budget())
341    }
342
343    /// Associates a shared material with a new retained mesh handle without
344    /// allocating/uploading topology. Existing clones and scene users keep
345    /// their previous material; rebind selected IDs using `Scene3d::set_mesh`.
346    pub fn with_mesh3d_material(
347        &self,
348        mesh: &RetainedMesh3d,
349        material: &TextureMaterial3d,
350    ) -> Result<RetainedMesh3d, Texture3dError> {
351        attach_material(&self.renderer_identity, mesh, material)
352    }
353}
354
355pub(super) fn attach_material(
356    identity: &Arc<()>,
357    mesh: &RetainedMesh3d,
358    material: &TextureMaterial3d,
359) -> Result<RetainedMesh3d, Texture3dError> {
360    if !Arc::ptr_eq(identity, &mesh.renderer_identity) || !material.texture.belongs_to(identity) {
361        return Err(Texture3dError::RendererMismatch);
362    }
363    if mesh.source.texture_coordinates().len() != mesh.source.vertices().len()
364        || mesh.source.triangle_count() == 0
365        || mesh.texture_coordinate_buffer.is_none()
366    {
367        return Err(Texture3dError::MissingTextureCoordinates);
368    }
369    let mut result = mesh.clone();
370    result.material = Some(material.clone());
371    Ok(result)
372}
373
374#[allow(clippy::too_many_arguments)]
375pub(super) fn create_texture(
376    device: &wgpu::Device,
377    queue: &wgpu::Queue,
378    identity: &Arc<()>,
379    layout: &wgpu::BindGroupLayout,
380    width: u32,
381    height: u32,
382    pixels: Vec<u8>,
383    budget: ImageBudget,
384) -> Result<Texture3d, Texture3dError> {
385    image::validate_image_shape(
386        width,
387        height,
388        pixels.len(),
389        budget,
390        device.limits().max_texture_dimension_2d,
391    )
392    .map_err(Texture3dError::Image)?;
393    if let Some(texel) = pixels.chunks_exact(4).position(|pixel| pixel[3] != 255) {
394        return Err(Texture3dError::NonOpaquePixel { texel });
395    }
396    let image = image::create_image_resources(
397        device,
398        queue,
399        Arc::clone(identity),
400        width,
401        height,
402        pixels,
403        budget,
404    )
405    .map_err(Texture3dError::Image)?;
406    let binding = |filter| {
407        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
408            label: Some("sim-engine 3D texture sampler"),
409            address_mode_u: wgpu::AddressMode::ClampToEdge,
410            address_mode_v: wgpu::AddressMode::ClampToEdge,
411            mag_filter: filter,
412            min_filter: filter,
413            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
414            ..Default::default()
415        });
416        device.create_bind_group(&wgpu::BindGroupDescriptor {
417            label: Some("sim-engine 3D texture binding"),
418            layout,
419            entries: &[
420                wgpu::BindGroupEntry {
421                    binding: 0,
422                    resource: wgpu::BindingResource::TextureView(&image.view),
423                },
424                wgpu::BindGroupEntry {
425                    binding: 1,
426                    resource: wgpu::BindingResource::Sampler(&sampler),
427                },
428            ],
429        })
430    };
431    let nearest = binding(wgpu::FilterMode::Nearest);
432    let linear = binding(wgpu::FilterMode::Linear);
433    Ok(Texture3d {
434        storage: Arc::new(TextureStorage {
435            renderer_identity: Arc::clone(identity),
436            image,
437            nearest,
438            linear,
439        }),
440    })
441}
442
443pub(super) fn copy_recovery_pixels(source: &Texture3d) -> Result<Vec<u8>, Texture3dError> {
444    let mut pixels = Vec::new();
445    pixels
446        .try_reserve_exact(source.pixels().len())
447        .map_err(|_| {
448            Texture3dError::Image(ImageError::AllocationFailed {
449                requested_bytes: source.pixels().len(),
450            })
451        })?;
452    pixels.extend_from_slice(source.pixels());
453    if pixels.capacity() > source.budget().max_bytes() {
454        return Err(Texture3dError::Image(ImageError::BudgetExceeded {
455            limit: source.budget().max_bytes(),
456            actual: pixels.capacity(),
457        }));
458    }
459    Ok(pixels)
460}
461
462pub(super) struct PreparedTextureRestore {
463    pub(super) key: usize,
464    pub(super) source: Texture3d,
465    pub(super) pixels: Vec<u8>,
466}
467
468pub(super) fn prepare_scene_restoration(
469    device: &wgpu::Device,
470    identity: &Arc<()>,
471    scene: &Scene3d,
472) -> Result<Vec<PreparedTextureRestore>, Mesh3dResourceError> {
473    let mut prepared = Vec::new();
474    prepared
475        .try_reserve_exact(scene.object_count())
476        .map_err(|_| Mesh3dResourceError::HostAllocationFailed {
477            requested_bytes: scene
478                .object_count()
479                .saturating_mul(std::mem::size_of::<PreparedTextureRestore>())
480                as u64,
481        })?;
482    for instance in scene.instances() {
483        if let Some(material) = instance.mesh.material()
484            && !material.texture().belongs_to(identity)
485        {
486            prepared.push(PreparedTextureRestore {
487                key: material.texture().identity_key(),
488                source: material.texture().clone(),
489                pixels: Vec::new(),
490            });
491        }
492    }
493    prepared.sort_unstable_by_key(|texture| texture.key);
494    prepared.dedup_by_key(|texture| texture.key);
495    for texture in &mut prepared {
496        let source = &texture.source;
497        image::validate_image_shape(
498            source.size().0,
499            source.size().1,
500            source.pixels().len(),
501            source.budget(),
502            device.limits().max_texture_dimension_2d,
503        )
504        .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?;
505        texture.pixels = copy_recovery_pixels(source).map_err(Mesh3dResourceError::Texture)?;
506    }
507    Ok(prepared)
508}