1use std::borrow::Cow;
2use std::error::Error;
3use std::fmt;
4use std::sync::Arc;
5
6use super::{
7 Color, LogicalViewport, LogicalViewportRegion, RendererFrameError, Vec2, WgpuRenderer,
8 is_portable_shader_source, prepared_scene_belongs_to, shader_interval_sum_range,
9 submit_pending_uploads,
10};
11
12const IMAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
13
14mod updates;
15pub(super) use updates::{batch_retained_bytes, update_image_batch_resources};
16mod proof;
17use proof::BatchProofCache;
18#[cfg(test)]
19pub(super) use proof::sprites_are_safe_for_target;
20
21#[cfg(test)]
22pub(super) use tests::verify_retained_ui_updates;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct ImageBudget {
27 max_width: u32,
28 max_height: u32,
29 max_bytes: usize,
30}
31
32impl ImageBudget {
33 pub fn new(max_width: u32, max_height: u32, max_bytes: usize) -> Result<Self, ImageError> {
35 if max_width == 0 || max_height == 0 || max_bytes < 4 {
36 return Err(ImageError::InvalidBudget);
37 }
38 Ok(Self {
39 max_width,
40 max_height,
41 max_bytes,
42 })
43 }
44
45 pub const fn max_width(self) -> u32 {
47 self.max_width
48 }
49
50 pub const fn max_height(self) -> u32 {
52 self.max_height
53 }
54
55 pub const fn max_bytes(self) -> usize {
57 self.max_bytes
58 }
59}
60
61impl Default for ImageBudget {
62 fn default() -> Self {
63 Self {
64 max_width: 4096,
65 max_height: 4096,
66 max_bytes: 64 * 1024 * 1024,
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct ImageTexelRect {
74 x: u32,
75 y: u32,
76 width: u32,
77 height: u32,
78}
79
80impl ImageTexelRect {
81 pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageError> {
83 if width == 0 || height == 0 {
84 return Err(ImageError::ZeroDimension);
85 }
86 x.checked_add(width)
87 .zip(y.checked_add(height))
88 .ok_or(ImageError::DimensionsTooLarge)?;
89 Ok(Self {
90 x,
91 y,
92 width,
93 height,
94 })
95 }
96
97 pub const fn x(self) -> u32 {
99 self.x
100 }
101
102 pub const fn y(self) -> u32 {
104 self.y
105 }
106
107 pub const fn width(self) -> u32 {
109 self.width
110 }
111
112 pub const fn height(self) -> u32 {
114 self.height
115 }
116
117 pub(super) fn fits(self, width: u32, height: u32) -> bool {
118 self.x
119 .checked_add(self.width)
120 .is_some_and(|maximum| maximum <= width)
121 && self
122 .y
123 .checked_add(self.height)
124 .is_some_and(|maximum| maximum <= height)
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
130pub enum ImageSampling {
131 #[default]
133 Nearest,
134 Linear,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct ImageBatchPlacement {
146 translation: crate::LogicalScreenVector,
147 tint: Color,
148}
149
150impl ImageBatchPlacement {
151 pub fn new(translation: crate::LogicalScreenVector, tint: Color) -> Result<Self, ImageError> {
155 let offset = translation.to_vec2();
156 if ![offset.x, offset.y]
157 .into_iter()
158 .all(is_portable_shader_source)
159 || !tint.is_normalized()
160 {
161 return Err(ImageError::InvalidPlacement);
162 }
163 Ok(Self { translation, tint })
164 }
165
166 pub const fn translation(self) -> crate::LogicalScreenVector {
168 self.translation
169 }
170 pub const fn tint(self) -> Color {
172 self.tint
173 }
174}
175
176impl Default for ImageBatchPlacement {
177 fn default() -> Self {
178 Self {
179 translation: crate::LogicalScreenVector::new(0.0, 0.0),
180 tint: Color::WHITE,
181 }
182 }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum ImageError {
188 ZeroDimension,
190 InvalidBudget,
192 DimensionsTooLarge,
194 InvalidPixelCount,
196 BudgetExceeded {
198 limit: usize,
200 actual: usize,
202 },
203 AllocationFailed {
206 requested_bytes: usize,
208 },
209 RendererMismatch,
211 RecoverySourceMismatch,
213 UpdateRegionOutOfBounds,
215 InvalidSprite,
217 InvalidPlacement,
219 BatchBudgetExceeded {
221 limit: usize,
223 actual: usize,
225 },
226}
227
228impl fmt::Display for ImageError {
229 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
230 match self {
231 Self::ZeroDimension => write!(formatter, "image dimensions must be non-zero"),
232 Self::InvalidBudget => write!(
233 formatter,
234 "resource budget must fit at least one image texel or batch element"
235 ),
236 Self::DimensionsTooLarge => write!(formatter, "image dimensions exceed limits"),
237 Self::InvalidPixelCount => write!(formatter, "image RGBA byte count is invalid"),
238 Self::BudgetExceeded { limit, actual } => {
239 write!(
240 formatter,
241 "image requires {actual} bytes, over limit {limit}"
242 )
243 }
244 Self::AllocationFailed { requested_bytes } => write!(
245 formatter,
246 "could not reserve {requested_bytes} bytes for image storage or staging"
247 ),
248 Self::RendererMismatch => write!(formatter, "image belongs to another renderer"),
249 Self::RecoverySourceMismatch => {
250 write!(
251 formatter,
252 "image is not a restored copy of the recovery source"
253 )
254 }
255 Self::UpdateRegionOutOfBounds => write!(formatter, "image update is out of bounds"),
256 Self::InvalidSprite => write!(formatter, "image sprite source or tint is invalid"),
257 Self::InvalidPlacement => {
258 write!(formatter, "image batch translation or tint is invalid")
259 }
260 Self::BatchBudgetExceeded { limit, actual } => {
261 write!(formatter, "image batch work {actual} exceeds limit {limit}")
262 }
263 }
264 }
265}
266
267impl Error for ImageError {}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct ImageUploadReport {
272 uploaded_bytes: usize,
273 replaced_texture: bool,
274}
275
276impl ImageUploadReport {
277 pub const fn uploaded_bytes(self) -> usize {
279 self.uploaded_bytes
280 }
281
282 pub const fn replaced_texture(self) -> bool {
284 self.replaced_texture
285 }
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub struct ImageBatchUploadReport {
295 uploaded_instance_bytes: usize,
296 replaced_instance_buffer: bool,
297 sprite_count: usize,
298 retained_capacity: usize,
299 gpu_capacity: usize,
300 retained_bytes: usize,
301 peak_retained_bytes: usize,
302 peak_gpu_bytes: usize,
303}
304
305impl ImageBatchUploadReport {
306 pub const fn uploaded_instance_bytes(self) -> usize {
308 self.uploaded_instance_bytes
309 }
310
311 pub const fn replaced_instance_buffer(self) -> bool {
313 self.replaced_instance_buffer
314 }
315
316 pub const fn sprite_count(self) -> usize {
318 self.sprite_count
319 }
320
321 pub const fn retained_capacity(self) -> usize {
323 self.retained_capacity
324 }
325
326 pub const fn gpu_capacity(self) -> usize {
328 self.gpu_capacity
329 }
330
331 pub const fn retained_bytes(self) -> usize {
333 self.retained_bytes
334 }
335
336 pub const fn peak_retained_bytes(self) -> usize {
339 self.peak_retained_bytes
340 }
341
342 pub const fn peak_gpu_bytes(self) -> usize {
345 self.peak_gpu_bytes
346 }
347}
348
349pub struct Image2d {
355 renderer_identity: Arc<()>,
356 pub(super) resource_identity: Arc<()>,
357 pub(super) recovery_identity: Arc<()>,
358 texture: wgpu::Texture,
359 pub(super) view: wgpu::TextureView,
360 width: u32,
361 height: u32,
362 pixels: Vec<u8>,
363 budget: ImageBudget,
364}
365
366impl Image2d {
367 pub const fn width(&self) -> u32 {
369 self.width
370 }
371
372 pub const fn height(&self) -> u32 {
374 self.height
375 }
376
377 pub const fn size(&self) -> (u32, u32) {
379 (self.width, self.height)
380 }
381
382 pub const fn budget(&self) -> ImageBudget {
384 self.budget
385 }
386
387 pub fn pixels(&self) -> &[u8] {
389 &self.pixels
390 }
391
392 pub fn recovery_memory_bytes(&self) -> usize {
394 self.pixels.capacity()
395 }
396
397 pub fn gpu_allocation_bytes(&self) -> usize {
400 self.pixels.len()
401 }
402
403 pub fn full_rect(&self) -> ImageTexelRect {
405 ImageTexelRect {
406 x: 0,
407 y: 0,
408 width: self.width,
409 height: self.height,
410 }
411 }
412}
413
414#[derive(Debug, Clone, Copy, PartialEq)]
416pub struct ImageSprite2d {
417 source: ImageTexelRect,
418 destination: LogicalViewportRegion,
419 tint: Color,
420}
421
422impl ImageSprite2d {
423 pub fn new(
425 source: ImageTexelRect,
426 destination: LogicalViewportRegion,
427 tint: Color,
428 ) -> Result<Self, ImageError> {
429 let origin = destination.origin().to_vec2();
430 let end = origin + destination.viewport().size();
431 if !tint.is_normalized() || !origin.is_finite() || !end.is_finite() {
432 return Err(ImageError::InvalidSprite);
433 }
434 Ok(Self {
435 source,
436 destination,
437 tint,
438 })
439 }
440
441 pub const fn source(self) -> ImageTexelRect {
443 self.source
444 }
445
446 pub const fn destination(self) -> LogicalViewportRegion {
448 self.destination
449 }
450
451 pub const fn tint(self) -> Color {
453 self.tint
454 }
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub struct ImageBatchBudget {
460 max_sprites: usize,
461 max_retained_bytes: usize,
462}
463
464impl ImageBatchBudget {
465 pub const RETAINED_BYTES_PER_SPRITE: usize =
469 std::mem::size_of::<ImageSprite2d>() + std::mem::size_of::<ImageInstance>();
470
471 pub const GPU_BYTES_PER_SPRITE: usize = std::mem::size_of::<ImageInstance>();
473
474 pub fn new(max_sprites: usize, max_retained_bytes: usize) -> Result<Self, ImageError> {
476 if max_sprites == 0 || max_retained_bytes < batch_retained_bytes(1) {
477 return Err(ImageError::InvalidBudget);
478 }
479 Ok(Self {
480 max_sprites,
481 max_retained_bytes,
482 })
483 }
484
485 pub const fn max_sprites(self) -> usize {
487 self.max_sprites
488 }
489
490 pub const fn max_retained_bytes(self) -> usize {
492 self.max_retained_bytes
493 }
494}
495
496impl Default for ImageBatchBudget {
497 fn default() -> Self {
498 Self {
499 max_sprites: 100_000,
500 max_retained_bytes: 16 * 1024 * 1024,
501 }
502 }
503}
504
505pub struct ImageBatch2d {
516 renderer_identity: Arc<()>,
517 image_identity: Arc<()>,
518 pub(super) image_recovery_identity: Arc<()>,
519 pub(super) instance_buffer: wgpu::Buffer,
520 sprites: Vec<ImageSprite2d>,
521 instances: Vec<ImageInstance>,
522 budget: ImageBatchBudget,
523 geometry_proof: BatchProofCache,
526}
527
528impl ImageBatch2d {
529 pub fn sprite_count(&self) -> usize {
531 self.sprites.len()
532 }
533
534 pub fn sprites(&self) -> &[ImageSprite2d] {
536 &self.sprites
537 }
538
539 pub const fn budget(&self) -> ImageBatchBudget {
541 self.budget
542 }
543
544 pub fn recovery_memory_bytes(&self) -> usize {
547 self.sprites
548 .capacity()
549 .saturating_mul(std::mem::size_of::<ImageSprite2d>())
550 .saturating_add(
551 self.instances
552 .capacity()
553 .saturating_mul(std::mem::size_of::<ImageInstance>()),
554 )
555 }
556
557 pub fn gpu_allocation_bytes(&self) -> usize {
559 self.instance_buffer.size() as usize
560 }
561
562 pub fn capacity(&self) -> usize {
564 self.sprites.capacity().min(self.instances.capacity())
565 }
566
567 pub(super) fn sprites_are_safe_for_target(
568 &self,
569 viewport_origin: Vec2,
570 clip_transform: [f32; 4],
571 ) -> bool {
572 self.geometry_proof
573 .validate(&self.sprites, viewport_origin, clip_transform)
574 }
575}
576
577#[repr(C)]
578#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
579pub(super) struct ImageInstance {
580 pub(super) destination: [f32; 4],
581 pub(super) uv_rect: [f32; 4],
582 pub(super) tint: [f32; 4],
583}
584
585impl ImageInstance {
586 const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
587 wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4];
588 const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
589 array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
590 step_mode: wgpu::VertexStepMode::Instance,
591 attributes: &Self::ATTRIBUTES,
592 };
593}
594
595#[repr(C)]
596#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
597pub(super) struct ImageUniform {
598 pub(super) destination: [f32; 4],
599 pub(super) uv_rect: [f32; 4],
600 pub(super) tint: [f32; 4],
601 pub(super) world_clip_x: [f32; 4],
602 pub(super) world_clip_y: [f32; 4],
603 pub(super) world_mode: [f32; 4],
604}
605
606pub(super) fn batch_uniform(
607 target: LogicalViewport,
608 viewport_origin: Vec2,
609 placement: ImageBatchPlacement,
610) -> Result<ImageUniform, RendererFrameError> {
611 let origin = viewport_origin + placement.translation().to_vec2();
612 let destination = [2.0 / target.width(), -2.0 / target.height(), -1.0, 1.0];
613 if ![origin.x, origin.y]
614 .into_iter()
615 .chain(destination)
616 .all(is_portable_shader_source)
617 {
618 return Err(RendererFrameError::InvalidGeometryTransform);
619 }
620 Ok(ImageUniform {
621 destination,
622 uv_rect: [origin.x, origin.y, 0.0, 0.0],
623 tint: placement.tint().to_array(),
624 world_clip_x: [0.0; 4],
625 world_clip_y: [0.0; 4],
626 world_mode: [0.0; 4],
627 })
628}
629
630pub(super) struct ImageRenderer {
631 pub(super) pipeline: wgpu::RenderPipeline,
632 pub(super) batch_pipeline: wgpu::RenderPipeline,
633 pub(super) bind_group_layout: wgpu::BindGroupLayout,
634 nearest_sampler: wgpu::Sampler,
635 linear_sampler: wgpu::Sampler,
636}
637
638impl ImageRenderer {
639 pub(super) fn new(
640 device: &wgpu::Device,
641 format: wgpu::TextureFormat,
642 sample_count: u32,
643 ) -> Self {
644 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
645 label: Some("sim-engine image shader"),
646 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("../image.wgsl"))),
647 });
648 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
649 label: Some("sim-engine image bind group layout"),
650 entries: &[
651 wgpu::BindGroupLayoutEntry {
652 binding: 0,
653 visibility: wgpu::ShaderStages::FRAGMENT,
654 ty: wgpu::BindingType::Texture {
655 multisampled: false,
656 view_dimension: wgpu::TextureViewDimension::D2,
657 sample_type: wgpu::TextureSampleType::Float { filterable: true },
658 },
659 count: None,
660 },
661 wgpu::BindGroupLayoutEntry {
662 binding: 1,
663 visibility: wgpu::ShaderStages::FRAGMENT,
664 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
665 count: None,
666 },
667 wgpu::BindGroupLayoutEntry {
668 binding: 2,
669 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
670 ty: wgpu::BindingType::Buffer {
671 ty: wgpu::BufferBindingType::Uniform,
672 has_dynamic_offset: false,
673 min_binding_size: None,
674 },
675 count: None,
676 },
677 ],
678 });
679 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
680 label: Some("sim-engine image pipeline layout"),
681 bind_group_layouts: &[Some(&bind_group_layout)],
682 immediate_size: 0,
683 });
684 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
685 label: Some("sim-engine image pipeline"),
686 layout: Some(&layout),
687 vertex: wgpu::VertexState {
688 module: &shader,
689 entry_point: Some("image_vs_main"),
690 compilation_options: wgpu::PipelineCompilationOptions::default(),
691 buffers: &[],
692 },
693 primitive: wgpu::PrimitiveState {
694 topology: wgpu::PrimitiveTopology::TriangleList,
695 ..Default::default()
696 },
697 depth_stencil: None,
698 multisample: wgpu::MultisampleState {
699 count: sample_count,
700 ..Default::default()
701 },
702 fragment: Some(wgpu::FragmentState {
703 module: &shader,
704 entry_point: Some("image_fs_main"),
705 compilation_options: wgpu::PipelineCompilationOptions::default(),
706 targets: &[Some(wgpu::ColorTargetState {
707 format,
708 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
709 write_mask: wgpu::ColorWrites::ALL,
710 })],
711 }),
712 multiview_mask: None,
713 cache: None,
714 });
715 let batch_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
716 label: Some("sim-engine image batch pipeline"),
717 layout: Some(&layout),
718 vertex: wgpu::VertexState {
719 module: &shader,
720 entry_point: Some("image_batch_vs_main"),
721 compilation_options: wgpu::PipelineCompilationOptions::default(),
722 buffers: &[Some(ImageInstance::LAYOUT)],
723 },
724 primitive: wgpu::PrimitiveState {
725 topology: wgpu::PrimitiveTopology::TriangleList,
726 ..Default::default()
727 },
728 depth_stencil: None,
729 multisample: wgpu::MultisampleState {
730 count: sample_count,
731 ..Default::default()
732 },
733 fragment: Some(wgpu::FragmentState {
734 module: &shader,
735 entry_point: Some("image_fs_main"),
736 compilation_options: wgpu::PipelineCompilationOptions::default(),
737 targets: &[Some(wgpu::ColorTargetState {
738 format,
739 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
740 write_mask: wgpu::ColorWrites::ALL,
741 })],
742 }),
743 multiview_mask: None,
744 cache: None,
745 });
746 let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
747 label: Some("sim-engine nearest image sampler"),
748 mag_filter: wgpu::FilterMode::Nearest,
749 min_filter: wgpu::FilterMode::Nearest,
750 ..Default::default()
751 });
752 let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
753 label: Some("sim-engine linear image sampler"),
754 mag_filter: wgpu::FilterMode::Linear,
755 min_filter: wgpu::FilterMode::Linear,
756 ..Default::default()
757 });
758 Self {
759 pipeline,
760 batch_pipeline,
761 bind_group_layout,
762 nearest_sampler,
763 linear_sampler,
764 }
765 }
766
767 pub(super) fn sampler(&self, sampling: ImageSampling) -> &wgpu::Sampler {
768 match sampling {
769 ImageSampling::Nearest => &self.nearest_sampler,
770 ImageSampling::Linear => &self.linear_sampler,
771 }
772 }
773}
774
775impl WgpuRenderer {
776 pub fn create_image_rgba8(
778 &self,
779 width: u32,
780 height: u32,
781 pixels: Vec<u8>,
782 budget: ImageBudget,
783 ) -> Result<Image2d, ImageError> {
784 create_image_resources(
785 &self.device,
786 &self.queue,
787 Arc::clone(&self.renderer_identity),
788 width,
789 height,
790 pixels,
791 budget,
792 )
793 }
794
795 pub fn create_image_rgba8_from_slice(
797 &self,
798 width: u32,
799 height: u32,
800 pixels: &[u8],
801 budget: ImageBudget,
802 ) -> Result<Image2d, ImageError> {
803 let byte_count = validate_image_shape(
804 width,
805 height,
806 pixels.len(),
807 budget,
808 self.device.limits().max_texture_dimension_2d,
809 )?;
810 let mut owned = Vec::new();
811 owned
812 .try_reserve_exact(byte_count)
813 .map_err(|_| ImageError::AllocationFailed {
814 requested_bytes: byte_count,
815 })?;
816 owned.extend_from_slice(pixels);
817 self.create_image_rgba8(width, height, owned, budget)
818 }
819
820 pub fn replace_image_rgba8(
822 &self,
823 image: &mut Image2d,
824 width: u32,
825 height: u32,
826 pixels: Vec<u8>,
827 ) -> Result<ImageUploadReport, ImageError> {
828 self.validate_image(image)?;
829 let replacement = self.create_image_rgba8(width, height, pixels, image.budget)?;
830 let uploaded_bytes = replacement.pixels.len();
831 *image = replacement;
832 Ok(ImageUploadReport {
833 uploaded_bytes,
834 replaced_texture: true,
835 })
836 }
837
838 pub fn update_image_region(
840 &self,
841 image: &mut Image2d,
842 region: ImageTexelRect,
843 pixels: &[u8],
844 ) -> Result<ImageUploadReport, ImageError> {
845 self.validate_image(image)?;
846 let required = validate_image_region_upload(image, region, pixels.len())?;
847 write_image_texture(
848 &self.queue,
849 &image.texture,
850 region.x,
851 region.y,
852 region.width,
853 region.height,
854 pixels,
855 );
856 let source_stride = region.width as usize * 4;
857 let destination_stride = image.width as usize * 4;
858 for row in 0..region.height as usize {
859 let source_start = row * source_stride;
860 let destination_start =
861 (region.y as usize + row) * destination_stride + region.x as usize * 4;
862 image.pixels[destination_start..destination_start + source_stride]
863 .copy_from_slice(&pixels[source_start..source_start + source_stride]);
864 }
865 Ok(ImageUploadReport {
866 uploaded_bytes: required,
867 replaced_texture: false,
868 })
869 }
870
871 pub fn restore_image(&self, source: &Image2d) -> Result<Image2d, ImageError> {
873 let mut restored = self.create_image_rgba8_from_slice(
874 source.width,
875 source.height,
876 &source.pixels,
877 source.budget,
878 )?;
879 restored.recovery_identity = Arc::clone(&source.recovery_identity);
880 Ok(restored)
881 }
882
883 pub fn create_image_batch(
885 &self,
886 image: &Image2d,
887 sprites: Vec<ImageSprite2d>,
888 budget: ImageBatchBudget,
889 ) -> Result<ImageBatch2d, ImageError> {
890 self.validate_image(image)?;
891 create_image_batch_resources(
892 &self.device,
893 &self.queue,
894 Arc::clone(&self.renderer_identity),
895 image,
896 sprites,
897 budget,
898 )
899 }
900
901 pub fn replace_image_batch(
904 &self,
905 image: &Image2d,
906 batch: &mut ImageBatch2d,
907 sprites: Vec<ImageSprite2d>,
908 ) -> Result<ImageBatchUploadReport, ImageError> {
909 self.update_image_batch(image, batch, &sprites)
910 }
911
912 pub fn restore_image_batch(
914 &self,
915 image: &Image2d,
916 source: &ImageBatch2d,
917 ) -> Result<ImageBatch2d, ImageError> {
918 self.validate_image(image)?;
919 restore_image_batch_resources(
920 &self.device,
921 &self.queue,
922 Arc::clone(&self.renderer_identity),
923 image,
924 source,
925 source.budget,
926 )
927 }
928
929 pub(super) fn validate_image(&self, image: &Image2d) -> Result<(), ImageError> {
930 prepared_scene_belongs_to(&self.renderer_identity, &image.renderer_identity)
931 .then_some(())
932 .ok_or(ImageError::RendererMismatch)
933 }
934
935 pub(super) fn validate_image_batch(
936 &self,
937 image: &Image2d,
938 batch: &ImageBatch2d,
939 ) -> Result<(), ImageError> {
940 self.validate_image(image)?;
941 validate_batch_image(image, batch)
942 }
943}
944
945pub(super) fn restore_image_batch_resources(
946 device: &wgpu::Device,
947 queue: &wgpu::Queue,
948 renderer_identity: Arc<()>,
949 image: &Image2d,
950 source: &ImageBatch2d,
951 budget: ImageBatchBudget,
952) -> Result<ImageBatch2d, ImageError> {
953 if !Arc::ptr_eq(&renderer_identity, &image.renderer_identity) {
954 return Err(ImageError::RendererMismatch);
955 }
956 if !Arc::ptr_eq(&image.recovery_identity, &source.image_recovery_identity) {
957 return Err(ImageError::RecoverySourceMismatch);
958 }
959 preflight_image_batch_capacity(device, source.sprites.len(), budget)?;
960 let mut sprites = Vec::new();
961 let requested_bytes = source
962 .sprites
963 .len()
964 .checked_mul(std::mem::size_of::<ImageSprite2d>())
965 .ok_or(ImageError::DimensionsTooLarge)?;
966 sprites
967 .try_reserve_exact(source.sprites.len())
968 .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
969 sprites.extend_from_slice(&source.sprites);
970 create_image_batch_resources(device, queue, renderer_identity, image, sprites, budget)
971}
972
973pub(super) fn validate_batch_image(
974 image: &Image2d,
975 batch: &ImageBatch2d,
976) -> Result<(), ImageError> {
977 if !prepared_scene_belongs_to(&image.renderer_identity, &batch.renderer_identity)
978 || !prepared_scene_belongs_to(&image.resource_identity, &batch.image_identity)
979 {
980 return Err(ImageError::RendererMismatch);
981 }
982 Ok(())
983}
984
985pub(super) fn validate_image_region_upload(
986 image: &Image2d,
987 region: ImageTexelRect,
988 pixel_count: usize,
989) -> Result<usize, ImageError> {
990 if !region.fits(image.width, image.height) {
991 return Err(ImageError::UpdateRegionOutOfBounds);
992 }
993 let required =
994 image_byte_count(region.width, region.height).ok_or(ImageError::DimensionsTooLarge)?;
995 if pixel_count != required {
996 return Err(ImageError::InvalidPixelCount);
997 }
998 Ok(required)
999}
1000
1001#[allow(clippy::too_many_arguments)]
1002pub(super) fn create_image_batch_resources(
1003 device: &wgpu::Device,
1004 queue: &wgpu::Queue,
1005 renderer_identity: Arc<()>,
1006 image: &Image2d,
1007 sprites: Vec<ImageSprite2d>,
1008 budget: ImageBatchBudget,
1009) -> Result<ImageBatch2d, ImageError> {
1010 preflight_image_batch_capacity(device, sprites.len(), budget)?;
1011 let gpu_bytes = sprites
1012 .len()
1013 .max(1)
1014 .checked_mul(std::mem::size_of::<ImageInstance>())
1015 .ok_or(ImageError::DimensionsTooLarge)?;
1016 if sprites.iter().any(|sprite| {
1017 !sprite.source.fits(image.width, image.height)
1018 || !sprite.tint.is_normalized()
1019 || !logical_image_region_is_portable(sprite.destination)
1020 }) {
1021 return Err(ImageError::InvalidSprite);
1022 }
1023 let staging_bytes = sprites
1024 .len()
1025 .saturating_mul(std::mem::size_of::<ImageInstance>());
1026 let sprites = compact_vec_with_byte_limit(
1027 sprites,
1028 budget.max_retained_bytes.saturating_sub(staging_bytes),
1029 |actual| ImageError::BatchBudgetExceeded {
1030 limit: budget.max_retained_bytes,
1031 actual,
1032 },
1033 )?;
1034 let mut instances = Vec::new();
1035 instances
1036 .try_reserve_exact(sprites.len())
1037 .map_err(|_| ImageError::AllocationFailed {
1038 requested_bytes: sprites
1039 .len()
1040 .saturating_mul(std::mem::size_of::<ImageInstance>()),
1041 })?;
1042 for sprite in &sprites {
1043 let origin = sprite.destination.origin().to_vec2();
1044 let viewport = sprite.destination.viewport();
1045 let image_width = image.width as f32;
1046 let image_height = image.height as f32;
1047 let source = sprite.source;
1048 let instance = ImageInstance {
1049 destination: [origin.x, origin.y, viewport.width(), viewport.height()],
1050 uv_rect: [
1051 (source.x as f32 + 0.5) / image_width,
1052 (source.y as f32 + 0.5) / image_height,
1053 (source.x as f32 + source.width as f32 - 0.5) / image_width,
1054 (source.y as f32 + source.height as f32 - 0.5) / image_height,
1055 ],
1056 tint: sprite.tint.to_array(),
1057 };
1058 if !instance
1059 .destination
1060 .iter()
1061 .chain(instance.uv_rect.iter())
1062 .chain(instance.tint.iter())
1063 .all(|value| value.is_finite())
1064 {
1065 return Err(ImageError::InvalidSprite);
1066 }
1067 instances.push(instance);
1068 }
1069 let retained_bytes = sprites
1070 .capacity()
1071 .saturating_mul(std::mem::size_of::<ImageSprite2d>())
1072 .saturating_add(
1073 instances
1074 .capacity()
1075 .saturating_mul(std::mem::size_of::<ImageInstance>()),
1076 );
1077 if retained_bytes > budget.max_retained_bytes {
1078 return Err(ImageError::BatchBudgetExceeded {
1079 limit: budget.max_retained_bytes,
1080 actual: retained_bytes,
1081 });
1082 }
1083 let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
1084 label: Some("sim-engine retained image sprite instances"),
1085 size: gpu_bytes as wgpu::BufferAddress,
1086 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1087 mapped_at_creation: false,
1088 });
1089 if !instances.is_empty() {
1090 queue.write_buffer(&instance_buffer, 0, bytemuck::cast_slice(&instances));
1091 submit_pending_uploads(queue);
1092 }
1093 Ok(ImageBatch2d {
1094 renderer_identity,
1095 image_identity: Arc::clone(&image.resource_identity),
1096 image_recovery_identity: Arc::clone(&image.recovery_identity),
1097 instance_buffer,
1098 sprites,
1099 instances,
1100 budget,
1101 geometry_proof: BatchProofCache::default(),
1102 })
1103}
1104
1105pub(super) fn logical_image_region_is_portable(region: LogicalViewportRegion) -> bool {
1106 let origin = region.origin().to_vec2();
1107 let size = region.viewport().size();
1108 let components = [origin.x, origin.y, size.x, size.y];
1109 if !components.into_iter().all(is_portable_shader_source) {
1110 return false;
1111 }
1112 if components
1118 .into_iter()
1119 .all(|value| value.abs() <= super::MAX_PORTABLE_SHADER_VALUE * 0.25)
1120 {
1121 return true;
1122 }
1123 shader_interval_sum_range([
1124 (f64::from(origin.x), f64::from(origin.x)),
1125 (0.0, f64::from(size.x)),
1126 ])
1127 .is_some()
1128 && shader_interval_sum_range([
1129 (f64::from(origin.y), f64::from(origin.y)),
1130 (0.0, f64::from(size.y)),
1131 ])
1132 .is_some()
1133}
1134
1135#[allow(clippy::too_many_arguments)]
1136pub(super) fn create_image_resources(
1137 device: &wgpu::Device,
1138 queue: &wgpu::Queue,
1139 renderer_identity: Arc<()>,
1140 width: u32,
1141 height: u32,
1142 pixels: Vec<u8>,
1143 budget: ImageBudget,
1144) -> Result<Image2d, ImageError> {
1145 validate_image_shape(
1146 width,
1147 height,
1148 pixels.len(),
1149 budget,
1150 device.limits().max_texture_dimension_2d,
1151 )?;
1152 let pixels = compact_vec_with_byte_limit(pixels, budget.max_bytes, |actual| {
1155 ImageError::BudgetExceeded {
1156 limit: budget.max_bytes,
1157 actual,
1158 }
1159 })?;
1160 let texture = device.create_texture(&wgpu::TextureDescriptor {
1161 label: Some("sim-engine retained RGBA image"),
1162 size: wgpu::Extent3d {
1163 width,
1164 height,
1165 depth_or_array_layers: 1,
1166 },
1167 mip_level_count: 1,
1168 sample_count: 1,
1169 dimension: wgpu::TextureDimension::D2,
1170 format: IMAGE_FORMAT,
1171 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1172 view_formats: &[],
1173 });
1174 write_image_texture(queue, &texture, 0, 0, width, height, &pixels);
1175 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1176 Ok(Image2d {
1177 renderer_identity,
1178 resource_identity: Arc::new(()),
1179 recovery_identity: Arc::new(()),
1180 texture,
1181 view,
1182 width,
1183 height,
1184 pixels,
1185 budget,
1186 })
1187}
1188
1189fn compact_vec_with_byte_limit<T: Copy>(
1190 values: Vec<T>,
1191 maximum_bytes: usize,
1192 capacity_error: impl FnOnce(usize) -> ImageError,
1193) -> Result<Vec<T>, ImageError> {
1194 let element_size = std::mem::size_of::<T>();
1195 let allocation_bytes = values.capacity().saturating_mul(element_size);
1196 if allocation_bytes <= maximum_bytes {
1197 return Ok(values);
1198 }
1199 let requested_bytes = values
1200 .len()
1201 .checked_mul(element_size)
1202 .ok_or(ImageError::DimensionsTooLarge)?;
1203 let mut compact = Vec::new();
1204 compact
1205 .try_reserve_exact(values.len())
1206 .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
1207 compact.extend_from_slice(&values);
1208 let actual = compact.capacity().saturating_mul(element_size);
1209 if actual > maximum_bytes {
1210 return Err(capacity_error(actual));
1211 }
1212 Ok(compact)
1213}
1214
1215pub(super) fn validate_image_shape(
1216 width: u32,
1217 height: u32,
1218 pixel_count: usize,
1219 budget: ImageBudget,
1220 max_texture_dimension: u32,
1221) -> Result<usize, ImageError> {
1222 if width == 0 || height == 0 {
1223 return Err(ImageError::ZeroDimension);
1224 }
1225 if width > budget.max_width
1226 || height > budget.max_height
1227 || width > max_texture_dimension
1228 || height > max_texture_dimension
1229 || width.checked_mul(4).is_none()
1230 {
1231 return Err(ImageError::DimensionsTooLarge);
1232 }
1233 let bytes = image_byte_count(width, height).ok_or(ImageError::DimensionsTooLarge)?;
1234 if bytes > budget.max_bytes {
1235 return Err(ImageError::BudgetExceeded {
1236 limit: budget.max_bytes,
1237 actual: bytes,
1238 });
1239 }
1240 if pixel_count != bytes {
1241 return Err(ImageError::InvalidPixelCount);
1242 }
1243 Ok(bytes)
1244}
1245
1246pub(super) fn preflight_image_batch_capacity(
1247 device: &wgpu::Device,
1248 sprite_count: usize,
1249 budget: ImageBatchBudget,
1250) -> Result<(), ImageError> {
1251 if sprite_count > budget.max_sprites {
1252 return Err(ImageError::BatchBudgetExceeded {
1253 limit: budget.max_sprites,
1254 actual: sprite_count,
1255 });
1256 }
1257 if u32::try_from(sprite_count).is_err() {
1258 return Err(ImageError::DimensionsTooLarge);
1259 }
1260 let retained_bytes = sprite_count
1261 .checked_mul(batch_retained_bytes(1))
1262 .ok_or(ImageError::DimensionsTooLarge)?;
1263 if retained_bytes > budget.max_retained_bytes {
1264 return Err(ImageError::BatchBudgetExceeded {
1265 limit: budget.max_retained_bytes,
1266 actual: retained_bytes,
1267 });
1268 }
1269 let gpu_bytes = sprite_count
1270 .max(1)
1271 .checked_mul(std::mem::size_of::<ImageInstance>())
1272 .ok_or(ImageError::DimensionsTooLarge)?;
1273 if gpu_bytes as u64 > device.limits().max_buffer_size {
1274 return Err(ImageError::DimensionsTooLarge);
1275 }
1276 Ok(())
1277}
1278
1279fn image_byte_count(width: u32, height: u32) -> Option<usize> {
1280 (width as usize)
1281 .checked_mul(height as usize)?
1282 .checked_mul(4)
1283}
1284
1285#[allow(clippy::too_many_arguments)]
1286fn write_image_texture(
1287 queue: &wgpu::Queue,
1288 texture: &wgpu::Texture,
1289 x: u32,
1290 y: u32,
1291 width: u32,
1292 height: u32,
1293 pixels: &[u8],
1294) {
1295 queue.write_texture(
1296 wgpu::TexelCopyTextureInfo {
1297 texture,
1298 mip_level: 0,
1299 origin: wgpu::Origin3d { x, y, z: 0 },
1300 aspect: wgpu::TextureAspect::All,
1301 },
1302 pixels,
1303 wgpu::TexelCopyBufferLayout {
1304 offset: 0,
1305 bytes_per_row: Some(width * 4),
1306 rows_per_image: Some(height),
1307 },
1308 wgpu::Extent3d {
1309 width,
1310 height,
1311 depth_or_array_layers: 1,
1312 },
1313 );
1314 submit_pending_uploads(queue);
1315}
1316
1317#[cfg(test)]
1318mod tests;