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