1use super::{
4 Arc, Color, Duration, Error, ImageBudget, ImageError, ImageSampling, ImageTexelRect, Instant,
5 Mesh3dResourceError, Object3dId, RetainedMesh3d, Scene3d, Scene3dError, SurfaceLayout,
6 SurfacePipelines, WgpuRenderer, create_surface_pipelines, fmt, image, lighting,
7 submit_pending_uploads,
8};
9use crate::mesh3d::{TextureAddressMode3d, TextureCoordinate2d, TextureUvTransform3d};
10mod mips;
11use mips::CpuMipChain;
12pub use mips::TextureMipmaps3d;
13mod options;
14pub use options::Texture3dOptions;
15mod creation;
16#[cfg(test)]
17pub(super) use creation::{create_texture_with_options, crop_texture_tile};
18mod updates;
19pub use updates::{
20 Texture3dUpdateBudget, Texture3dUpdateBudgetResource, Texture3dUpdateError,
21 Texture3dUpdateReport,
22};
23#[cfg(test)]
24pub(super) use updates::{update_scene_texture_region, update_texture_region};
25
26#[cfg(test)]
27mod tests;
28#[cfg(test)]
29pub(super) use tests::{
30 assert_gpu_partial_mip_recovery, assert_gpu_partial_mip_updates,
31 assert_gpu_restored_material_policy, assert_gpu_texture_contract, assert_gpu_texture_lifecycle,
32 assert_gpu_texture_lifecycle_recovery, assert_gpu_textured_recovery, benchmark_texture_updates,
33};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Texture3dError {
38 Image(ImageError),
40 NonOpaquePixel {
42 texel: usize,
44 },
45 InvalidTint,
47 MissingTextureCoordinates,
49 RendererMismatch,
51 InvalidRegion,
53 MipmappedAtlasRegion,
55}
56
57impl fmt::Display for Texture3dError {
58 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match self {
60 Self::Image(error) => write!(formatter, "3D texture: {error}"),
61 Self::NonOpaquePixel { texel } => {
62 write!(formatter, "3D texture texel {texel} is not opaque")
63 }
64 Self::InvalidTint => write!(
65 formatter,
66 "3D texture tint must be normalized; alpha requires the explicit with_alpha constructor"
67 ),
68 Self::MissingTextureCoordinates => {
69 write!(formatter, "textured 3D surfaces require per-vertex UVs")
70 }
71 Self::RendererMismatch => {
72 write!(formatter, "3D texture/mesh belongs to another renderer")
73 }
74 Self::InvalidRegion => write!(formatter, "3D texture atlas region is out of bounds"),
75 Self::MipmappedAtlasRegion => write!(
76 formatter,
77 "crop an independent 3D tile before mip filtering; atlas UV insets do not isolate mip levels"
78 ),
79 }
80 }
81}
82impl Error for Texture3dError {}
83
84struct TextureStorage {
85 renderer_identity: Arc<()>,
86 chain: CpuMipChain,
87 texture: wgpu::Texture,
88 bindings: [wgpu::BindGroup; 4],
89 preserve_alpha: bool,
90 first_nonopaque_texel: Option<usize>,
91}
92
93#[derive(Clone)]
103pub struct Texture3d {
104 storage: Arc<TextureStorage>,
105}
106
107impl Texture3d {
108 pub fn size(&self) -> (u32, u32) {
110 self.storage.chain.size()
111 }
112 pub fn pixels(&self) -> &[u8] {
114 self.storage.chain.pixels()
115 }
116 pub fn mip_level_count(&self) -> u32 {
118 self.storage.chain.levels().len() as u32
119 }
120 pub fn mip_level_pixels(&self, level: u32) -> Option<&[u8]> {
122 self.storage
123 .chain
124 .levels()
125 .get(level as usize)
126 .map(|level| self.storage.chain.level_pixels(*level))
127 }
128 pub fn mip_level_size(&self, level: u32) -> Option<(u32, u32)> {
130 self.storage
131 .chain
132 .levels()
133 .get(level as usize)
134 .map(|level| (level.width, level.height))
135 }
136 pub fn mipmaps(&self) -> TextureMipmaps3d {
138 self.storage.chain.mode()
139 }
140 pub fn options(&self) -> Texture3dOptions {
142 Texture3dOptions::new()
143 .with_mipmaps(self.mipmaps())
144 .with_alpha_preservation(self.preserves_alpha())
145 }
146 pub fn preserves_alpha(&self) -> bool {
148 self.storage.preserve_alpha
149 }
150 pub fn budget(&self) -> ImageBudget {
152 self.storage.chain.budget()
153 }
154 pub fn recovery_memory_bytes(&self) -> usize {
156 self.storage.chain.recovery_memory_bytes()
157 }
158 pub fn gpu_allocation_bytes(&self) -> usize {
160 self.storage.chain.gpu_allocation_bytes()
161 }
162 pub fn region_coordinates(
171 &self,
172 region: ImageTexelRect,
173 ) -> Result<[TextureCoordinate2d; 4], Texture3dError> {
174 if self.mip_level_count() > 1 {
175 return Err(Texture3dError::MipmappedAtlasRegion);
176 }
177 let (width, height) = self.size();
178 if !region.fits(width, height) {
179 return Err(Texture3dError::InvalidRegion);
180 }
181 let left = (region.x() as f64 + 0.5) / f64::from(width);
182 let right = (f64::from(region.x()) + f64::from(region.width()) - 0.5) / f64::from(width);
183 let top = (region.y() as f64 + 0.5) / f64::from(height);
184 let bottom = (f64::from(region.y()) + f64::from(region.height()) - 0.5) / f64::from(height);
185 let make = |u: f64, v: f64| {
186 TextureCoordinate2d::new(u as f32, v as f32).map_err(|_| Texture3dError::InvalidRegion)
187 };
188 Ok([
189 make(left, top)?,
190 make(right, top)?,
191 make(right, bottom)?,
192 make(left, bottom)?,
193 ])
194 }
195 pub(super) fn identity_key(&self) -> usize {
196 Arc::as_ptr(&self.storage) as usize
197 }
198 pub(super) fn belongs_to(&self, identity: &Arc<()>) -> bool {
199 Arc::ptr_eq(identity, &self.storage.renderer_identity)
200 }
201 fn bind_group(
202 &self,
203 sampling: ImageSampling,
204 address: TextureAddressMode3d,
205 ) -> &wgpu::BindGroup {
206 &self.storage.bindings[usize::from(address == TextureAddressMode3d::Repeat) * 2
207 + usize::from(sampling == ImageSampling::Linear)]
208 }
209}
210
211#[derive(Clone)]
217pub struct TextureMaterial3d {
218 texture: Texture3d,
219 sampling: ImageSampling,
220 tint: Color,
221 uv_transform: TextureUvTransform3d,
222 address_mode: TextureAddressMode3d,
223 require_opaque_texture: bool,
224}
225
226impl TextureMaterial3d {
227 pub fn new(
230 texture: &Texture3d,
231 sampling: ImageSampling,
232 tint: Color,
233 ) -> Result<Self, Texture3dError> {
234 if !tint.is_normalized() || tint.alpha() != 1.0 {
235 return Err(Texture3dError::InvalidTint);
236 }
237 if let Some(texel) = texture.storage.first_nonopaque_texel {
238 return Err(Texture3dError::NonOpaquePixel { texel });
239 }
240 let mut material = Self::with_alpha(texture, sampling, tint)?;
241 material.require_opaque_texture = true;
242 Ok(material)
243 }
244 pub fn with_alpha(
247 texture: &Texture3d,
248 sampling: ImageSampling,
249 tint: Color,
250 ) -> Result<Self, Texture3dError> {
251 if !tint.is_normalized() {
252 return Err(Texture3dError::InvalidTint);
253 }
254 Ok(Self {
255 texture: texture.clone(),
256 sampling,
257 tint,
258 uv_transform: TextureUvTransform3d::IDENTITY,
259 address_mode: TextureAddressMode3d::Clamp,
260 require_opaque_texture: false,
261 })
262 }
263 pub fn with_uv_transform(mut self, transform: TextureUvTransform3d) -> Self {
265 self.uv_transform = transform;
266 self
267 }
268 pub fn with_address_mode(mut self, mode: TextureAddressMode3d) -> Self {
270 self.address_mode = mode;
271 self
272 }
273 pub fn with_texture(&self, texture: &Texture3d) -> Result<Self, Texture3dError> {
276 if self.require_opaque_texture
277 && let Some(texel) = texture.storage.first_nonopaque_texel
278 {
279 return Err(Texture3dError::NonOpaquePixel { texel });
280 }
281 Ok(self.with_restored_texture(texture))
282 }
283 pub const fn uv_transform(&self) -> TextureUvTransform3d {
285 self.uv_transform
286 }
287 pub const fn address_mode(&self) -> TextureAddressMode3d {
289 self.address_mode
290 }
291 pub const fn texture(&self) -> &Texture3d {
293 &self.texture
294 }
295 pub const fn sampling(&self) -> ImageSampling {
299 self.sampling
300 }
301 pub const fn tint(&self) -> Color {
303 self.tint
304 }
305 pub(super) fn bind_group(&self) -> &wgpu::BindGroup {
306 self.texture.bind_group(self.sampling, self.address_mode)
307 }
308 pub(super) fn with_restored_texture(&self, texture: &Texture3d) -> Self {
309 Self {
310 texture: texture.clone(),
311 sampling: self.sampling,
312 tint: self.tint,
313 uv_transform: self.uv_transform,
314 address_mode: self.address_mode,
315 require_opaque_texture: self.require_opaque_texture,
316 }
317 }
318}
319
320#[repr(C)]
321#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
322pub(super) struct MeshUvGpu {
323 pub(super) coordinate: [f32; 2],
324}
325
326impl MeshUvGpu {
327 const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![5 => Float32x2];
328 pub(super) const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
329 array_stride: std::mem::size_of::<Self>() as u64,
330 step_mode: wgpu::VertexStepMode::Vertex,
331 attributes: &Self::ATTRIBUTES,
332 };
333}
334
335pub(super) struct MeshTextureRenderer {
336 pub(super) layout: wgpu::BindGroupLayout,
337 pub(super) retained_pipeline: SurfacePipelines,
338 pub(super) clipped_pipeline: SurfacePipelines,
339 pub(super) colored_retained_pipeline: SurfacePipelines,
340 pub(super) colored_clipped_pipeline: SurfacePipelines,
341}
342
343impl MeshTextureRenderer {
344 pub(super) fn new(
345 device: &wgpu::Device,
346 format: wgpu::TextureFormat,
347 camera_layout: &wgpu::BindGroupLayout,
348 ) -> Self {
349 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
350 label: Some("sim-engine 3D texture layout"),
351 entries: &[
352 wgpu::BindGroupLayoutEntry {
353 binding: 0,
354 visibility: wgpu::ShaderStages::FRAGMENT,
355 ty: wgpu::BindingType::Texture {
356 sample_type: wgpu::TextureSampleType::Float { filterable: true },
357 view_dimension: wgpu::TextureViewDimension::D2,
358 multisampled: false,
359 },
360 count: None,
361 },
362 wgpu::BindGroupLayoutEntry {
363 binding: 1,
364 visibility: wgpu::ShaderStages::FRAGMENT,
365 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
366 count: None,
367 },
368 ],
369 });
370 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
371 label: Some("sim-engine textured 3D surfaces"),
372 source: wgpu::ShaderSource::Wgsl(lighting::shader_source(include_str!(
373 "primitive.wgsl"
374 ))),
375 });
376 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
377 label: Some("sim-engine textured 3D pipeline layout"),
378 bind_group_layouts: &[Some(camera_layout), Some(&layout)],
379 immediate_size: 0,
380 });
381 let pipeline = |clipped: bool, colored: bool| {
382 create_surface_pipelines(
383 device,
384 format,
385 &pipeline_layout,
386 &shader,
387 SurfaceLayout {
388 clipped,
389 colored,
390 textured: true,
391 },
392 )
393 };
394 Self {
395 retained_pipeline: pipeline(false, false),
396 clipped_pipeline: pipeline(true, false),
397 colored_retained_pipeline: pipeline(false, true),
398 colored_clipped_pipeline: pipeline(true, true),
399 layout,
400 }
401 }
402}
403
404impl WgpuRenderer {
405 pub fn create_texture3d_rgba8(
408 &self,
409 width: u32,
410 height: u32,
411 pixels: Vec<u8>,
412 budget: ImageBudget,
413 ) -> Result<Texture3d, Texture3dError> {
414 create_texture(
415 &self.device,
416 &self.queue,
417 &self.renderer_identity,
418 &self.mesh3d_renderer.textures.layout,
419 width,
420 height,
421 pixels,
422 budget,
423 )
424 }
425
426 pub fn create_texture3d_rgba8_with_alpha(
429 &self,
430 width: u32,
431 height: u32,
432 pixels: Vec<u8>,
433 budget: ImageBudget,
434 ) -> Result<Texture3d, Texture3dError> {
435 create_texture_with_alpha(
436 &self.device,
437 &self.queue,
438 &self.renderer_identity,
439 &self.mesh3d_renderer.textures.layout,
440 width,
441 height,
442 pixels,
443 budget,
444 )
445 }
446
447 pub fn restore_texture3d(&self, source: &Texture3d) -> Result<Texture3d, Texture3dError> {
450 restore_texture(
451 &self.device,
452 &self.queue,
453 &self.renderer_identity,
454 &self.mesh3d_renderer.textures.layout,
455 source,
456 )
457 }
458
459 pub fn with_mesh3d_material(
463 &self,
464 mesh: &RetainedMesh3d,
465 material: &TextureMaterial3d,
466 ) -> Result<RetainedMesh3d, Texture3dError> {
467 attach_material(&self.renderer_identity, mesh, material)
468 }
469}
470
471pub(super) fn restore_texture(
472 device: &wgpu::Device,
473 queue: &wgpu::Queue,
474 identity: &Arc<()>,
475 layout: &wgpu::BindGroupLayout,
476 source: &Texture3d,
477) -> Result<Texture3d, Texture3dError> {
478 source
479 .storage
480 .chain
481 .validate_device_limit(device.limits().max_texture_dimension_2d)
482 .map_err(Texture3dError::Image)?;
483 let chain = source
484 .storage
485 .chain
486 .try_clone()
487 .map_err(Texture3dError::Image)?;
488 Ok(upload_chain(
489 device,
490 queue,
491 identity,
492 layout,
493 chain,
494 source.preserves_alpha(),
495 ))
496}
497
498pub(super) fn attach_material(
499 identity: &Arc<()>,
500 mesh: &RetainedMesh3d,
501 material: &TextureMaterial3d,
502) -> Result<RetainedMesh3d, Texture3dError> {
503 if !Arc::ptr_eq(identity, &mesh.renderer_identity) || !material.texture.belongs_to(identity) {
504 return Err(Texture3dError::RendererMismatch);
505 }
506 if mesh.source.texture_coordinates().len() != mesh.source.vertices().len()
507 || mesh.source.triangle_count() == 0
508 || mesh.texture_coordinate_buffer.is_none()
509 {
510 return Err(Texture3dError::MissingTextureCoordinates);
511 }
512 let mut result = mesh.clone();
513 result.material = Some(material.clone());
514 Ok(result)
515}
516
517pub(super) fn material_uv_parameters(material: Option<&TextureMaterial3d>) -> [f32; 4] {
518 let transform = material.map_or(
519 TextureUvTransform3d::IDENTITY,
520 TextureMaterial3d::uv_transform,
521 );
522 [
523 transform.scale().x(),
524 transform.scale().y(),
525 transform.offset().x(),
526 transform.offset().y(),
527 ]
528}
529
530#[allow(clippy::too_many_arguments)]
531pub(super) fn create_texture(
532 device: &wgpu::Device,
533 queue: &wgpu::Queue,
534 identity: &Arc<()>,
535 layout: &wgpu::BindGroupLayout,
536 width: u32,
537 height: u32,
538 pixels: Vec<u8>,
539 budget: ImageBudget,
540) -> Result<Texture3d, Texture3dError> {
541 create_texture_impl(
542 device, queue, identity, layout, width, height, pixels, budget, false,
543 )
544}
545
546#[allow(clippy::too_many_arguments)]
547pub(super) fn create_texture_with_alpha(
548 device: &wgpu::Device,
549 queue: &wgpu::Queue,
550 identity: &Arc<()>,
551 layout: &wgpu::BindGroupLayout,
552 width: u32,
553 height: u32,
554 pixels: Vec<u8>,
555 budget: ImageBudget,
556) -> Result<Texture3d, Texture3dError> {
557 create_texture_impl(
558 device, queue, identity, layout, width, height, pixels, budget, true,
559 )
560}
561
562#[allow(clippy::too_many_arguments)]
563pub(super) fn create_texture_impl(
564 device: &wgpu::Device,
565 queue: &wgpu::Queue,
566 identity: &Arc<()>,
567 layout: &wgpu::BindGroupLayout,
568 width: u32,
569 height: u32,
570 pixels: Vec<u8>,
571 budget: ImageBudget,
572 preserve_alpha: bool,
573) -> Result<Texture3d, Texture3dError> {
574 image::validate_image_shape(
575 width,
576 height,
577 pixels.len(),
578 budget,
579 device.limits().max_texture_dimension_2d,
580 )
581 .map_err(Texture3dError::Image)?;
582 let first_nonopaque_texel = pixels.chunks_exact(4).position(|pixel| pixel[3] != 255);
583 if !preserve_alpha && let Some(texel) = first_nonopaque_texel {
584 return Err(Texture3dError::NonOpaquePixel { texel });
585 }
586 let chain = CpuMipChain::new(
587 width,
588 height,
589 pixels,
590 budget,
591 device.limits().max_texture_dimension_2d,
592 TextureMipmaps3d::None,
593 )
594 .map_err(Texture3dError::Image)?;
595 Ok(upload_chain(
596 device,
597 queue,
598 identity,
599 layout,
600 chain,
601 preserve_alpha,
602 ))
603}
604
605pub(super) fn upload_chain(
606 device: &wgpu::Device,
607 queue: &wgpu::Queue,
608 identity: &Arc<()>,
609 layout: &wgpu::BindGroupLayout,
610 chain: CpuMipChain,
611 preserve_alpha: bool,
612) -> Texture3d {
613 let texture = chain.allocate_gpu(device);
614 let bindings = create_bindings(device, layout, &texture, chain.levels().len());
615 chain.upload_levels(queue, &texture, 0);
616 submit_pending_uploads(queue);
617 let first_nonopaque_texel = chain
618 .pixels()
619 .chunks_exact(4)
620 .position(|pixel| pixel[3] != 255);
621 Texture3d {
622 storage: Arc::new(TextureStorage {
623 renderer_identity: Arc::clone(identity),
624 chain,
625 texture,
626 bindings,
627 preserve_alpha,
628 first_nonopaque_texel,
629 }),
630 }
631}
632
633fn create_bindings(
634 device: &wgpu::Device,
635 layout: &wgpu::BindGroupLayout,
636 texture: &wgpu::Texture,
637 levels: usize,
638) -> [wgpu::BindGroup; 4] {
639 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
640 std::array::from_fn(|index| {
641 let address = if index >= 2 {
642 wgpu::AddressMode::Repeat
643 } else {
644 wgpu::AddressMode::ClampToEdge
645 };
646 let linear = index % 2 == 1;
647 let filter = if linear {
648 wgpu::FilterMode::Linear
649 } else {
650 wgpu::FilterMode::Nearest
651 };
652 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
653 label: Some("sim-engine 3D texture sampler"),
654 address_mode_u: address,
655 address_mode_v: address,
656 mag_filter: filter,
657 min_filter: filter,
658 mipmap_filter: if linear {
659 wgpu::MipmapFilterMode::Linear
660 } else {
661 wgpu::MipmapFilterMode::Nearest
662 },
663 lod_min_clamp: 0.0,
664 lod_max_clamp: (levels - 1) as f32,
665 ..Default::default()
666 });
667 device.create_bind_group(&wgpu::BindGroupDescriptor {
668 label: Some("sim-engine 3D texture binding"),
669 layout,
670 entries: &[
671 wgpu::BindGroupEntry {
672 binding: 0,
673 resource: wgpu::BindingResource::TextureView(&view),
674 },
675 wgpu::BindGroupEntry {
676 binding: 1,
677 resource: wgpu::BindingResource::Sampler(&sampler),
678 },
679 ],
680 })
681 })
682}
683
684pub(super) struct PreparedTextureRestore {
685 pub(super) key: usize,
686 pub(super) source: Texture3d,
687 pub(super) chain: Option<CpuMipChain>,
688}
689
690pub(super) fn prepare_scene_restoration(
691 device: &wgpu::Device,
692 identity: &Arc<()>,
693 scene: &Scene3d,
694) -> Result<Vec<PreparedTextureRestore>, Mesh3dResourceError> {
695 let mut prepared = Vec::new();
696 prepared
697 .try_reserve_exact(scene.object_count())
698 .map_err(|_| Mesh3dResourceError::HostAllocationFailed {
699 requested_bytes: scene
700 .object_count()
701 .saturating_mul(std::mem::size_of::<PreparedTextureRestore>())
702 as u64,
703 })?;
704 for instance in scene.instances() {
705 if let Some(material) = instance.mesh.material()
706 && !material.texture().belongs_to(identity)
707 {
708 prepared.push(PreparedTextureRestore {
709 key: material.texture().identity_key(),
710 source: material.texture().clone(),
711 chain: None,
712 });
713 }
714 }
715 prepared.sort_unstable_by_key(|texture| texture.key);
716 prepared.dedup_by_key(|texture| texture.key);
717 for texture in &mut prepared {
718 let source = &texture.source;
719 image::validate_image_shape(
720 source.size().0,
721 source.size().1,
722 source.pixels().len(),
723 source.budget(),
724 device.limits().max_texture_dimension_2d,
725 )
726 .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?;
727 source
728 .storage
729 .chain
730 .validate_device_limit(device.limits().max_texture_dimension_2d)
731 .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?;
732 texture.chain = Some(
733 source
734 .storage
735 .chain
736 .try_clone()
737 .map_err(|error| Mesh3dResourceError::Texture(Texture3dError::Image(error)))?,
738 );
739 }
740 Ok(prepared)
741}