Skip to main content

sim_engine/renderer/
image.rs

1use super::*;
2
3const IMAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
4
5mod updates;
6pub(super) use updates::{batch_retained_bytes, update_image_batch_resources};
7mod proof;
8use proof::BatchProofCache;
9#[cfg(test)]
10pub(super) use proof::sprites_are_safe_for_target;
11
12#[cfg(test)]
13mod update_tests;
14#[cfg(test)]
15pub(super) use update_tests::verify_retained_ui_updates;
16
17/// Immutable resource limits retained with an [`Image2d`].
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct ImageBudget {
20    max_width: u32,
21    max_height: u32,
22    max_bytes: usize,
23}
24
25impl ImageBudget {
26    /// Creates non-zero image dimension and byte limits.
27    pub fn new(max_width: u32, max_height: u32, max_bytes: usize) -> Result<Self, ImageError> {
28        if max_width == 0 || max_height == 0 || max_bytes < 4 {
29            return Err(ImageError::InvalidBudget);
30        }
31        Ok(Self {
32            max_width,
33            max_height,
34            max_bytes,
35        })
36    }
37
38    /// Returns maximum image width in physical texels.
39    pub const fn max_width(self) -> u32 {
40        self.max_width
41    }
42
43    /// Returns maximum image height in physical texels.
44    pub const fn max_height(self) -> u32 {
45        self.max_height
46    }
47
48    /// Returns maximum retained and GPU RGBA bytes.
49    pub const fn max_bytes(self) -> usize {
50        self.max_bytes
51    }
52}
53
54impl Default for ImageBudget {
55    fn default() -> Self {
56        Self {
57            max_width: 4096,
58            max_height: 4096,
59            max_bytes: 64 * 1024 * 1024,
60        }
61    }
62}
63
64/// Validated non-empty atlas rectangle in physical source texels.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct ImageTexelRect {
67    x: u32,
68    y: u32,
69    width: u32,
70    height: u32,
71}
72
73impl ImageTexelRect {
74    /// Creates a non-empty source rectangle. Image bounds are checked at use.
75    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageError> {
76        if width == 0 || height == 0 {
77            return Err(ImageError::ZeroDimension);
78        }
79        x.checked_add(width)
80            .zip(y.checked_add(height))
81            .ok_or(ImageError::DimensionsTooLarge)?;
82        Ok(Self {
83            x,
84            y,
85            width,
86            height,
87        })
88    }
89
90    /// Returns the left source texel.
91    pub const fn x(self) -> u32 {
92        self.x
93    }
94
95    /// Returns the top source texel.
96    pub const fn y(self) -> u32 {
97        self.y
98    }
99
100    /// Returns source width in texels.
101    pub const fn width(self) -> u32 {
102        self.width
103    }
104
105    /// Returns source height in texels.
106    pub const fn height(self) -> u32 {
107        self.height
108    }
109
110    pub(super) fn fits(self, width: u32, height: u32) -> bool {
111        self.x
112            .checked_add(self.width)
113            .is_some_and(|maximum| maximum <= width)
114            && self
115                .y
116                .checked_add(self.height)
117                .is_some_and(|maximum| maximum <= height)
118    }
119}
120
121/// Texture filtering used by a composed image or atlas region.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
123pub enum ImageSampling {
124    /// Preserve exact texel boundaries for pixel art and masks.
125    #[default]
126    Nearest,
127    /// Bilinearly interpolate neighboring source texels.
128    Linear,
129}
130
131/// Independent presentation of one retained image batch or glyph run.
132///
133/// Translation uses top-left logical pixels in the pass's local coordinates.
134/// It moves content before viewport placement, without moving the pass clip.
135/// Tint multiplies each instance's straight-linear RGBA, including alpha.
136/// Multiple draws can share immutable layout with different placements.
137#[derive(Debug, Clone, Copy, PartialEq)]
138pub struct ImageBatchPlacement {
139    translation: crate::LogicalScreenVector,
140    tint: Color,
141}
142
143impl ImageBatchPlacement {
144    /// Creates a portable logical translation and normalized multiplicative tint.
145    /// Negative translation is supported. Target-dependent arithmetic is checked
146    /// again before submission; leaving the target is ordinary clipping.
147    pub fn new(translation: crate::LogicalScreenVector, tint: Color) -> Result<Self, ImageError> {
148        let offset = translation.to_vec2();
149        if ![offset.x, offset.y]
150            .into_iter()
151            .all(is_portable_shader_source)
152            || !tint.is_normalized()
153        {
154            return Err(ImageError::InvalidPlacement);
155        }
156        Ok(Self { translation, tint })
157    }
158
159    /// Returns the content offset in local logical pixels.
160    pub const fn translation(self) -> crate::LogicalScreenVector {
161        self.translation
162    }
163    /// Returns the draw-wide straight-linear tint.
164    pub const fn tint(self) -> Color {
165        self.tint
166    }
167}
168
169impl Default for ImageBatchPlacement {
170    fn default() -> Self {
171        Self {
172            translation: crate::LogicalScreenVector::new(0.0, 0.0),
173            tint: Color::WHITE,
174        }
175    }
176}
177
178/// Failure while creating, restoring, or updating an RGBA image.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum ImageError {
181    /// A width or height was zero.
182    ZeroDimension,
183    /// A resource budget cannot fit its minimum image or batch element.
184    InvalidBudget,
185    /// Dimensions or their RGBA byte arithmetic exceed a configured/device limit.
186    DimensionsTooLarge,
187    /// Pixel data does not contain exactly width × height × four bytes.
188    InvalidPixelCount,
189    /// The image exceeds its host-selected byte limit.
190    BudgetExceeded {
191        /// Configured byte ceiling.
192        limit: usize,
193        /// Required RGBA bytes.
194        actual: usize,
195    },
196    /// CPU recovery, conversion, or batch-staging storage could not be
197    /// reserved.
198    AllocationFailed {
199        /// Bytes requested by the failed reservation.
200        requested_bytes: usize,
201    },
202    /// A retained image belongs to another renderer generation.
203    RendererMismatch,
204    /// A recovery operation was given a different logical image than the source used.
205    RecoverySourceMismatch,
206    /// A partial update does not fit in the image.
207    UpdateRegionOutOfBounds,
208    /// A sprite source rectangle or tint is invalid for its image.
209    InvalidSprite,
210    /// Draw translation is outside the portable envelope or tint is not normalized.
211    InvalidPlacement,
212    /// A sprite batch exceeds its retained count or CPU metadata byte limit.
213    BatchBudgetExceeded {
214        /// Configured upper bound.
215        limit: usize,
216        /// Requested count or bytes.
217        actual: usize,
218    },
219}
220
221impl fmt::Display for ImageError {
222    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223        match self {
224            Self::ZeroDimension => write!(formatter, "image dimensions must be non-zero"),
225            Self::InvalidBudget => write!(
226                formatter,
227                "resource budget must fit at least one image texel or batch element"
228            ),
229            Self::DimensionsTooLarge => write!(formatter, "image dimensions exceed limits"),
230            Self::InvalidPixelCount => write!(formatter, "image RGBA byte count is invalid"),
231            Self::BudgetExceeded { limit, actual } => {
232                write!(
233                    formatter,
234                    "image requires {actual} bytes, over limit {limit}"
235                )
236            }
237            Self::AllocationFailed { requested_bytes } => write!(
238                formatter,
239                "could not reserve {requested_bytes} bytes for image storage or staging"
240            ),
241            Self::RendererMismatch => write!(formatter, "image belongs to another renderer"),
242            Self::RecoverySourceMismatch => {
243                write!(
244                    formatter,
245                    "image is not a restored copy of the recovery source"
246                )
247            }
248            Self::UpdateRegionOutOfBounds => write!(formatter, "image update is out of bounds"),
249            Self::InvalidSprite => write!(formatter, "image sprite source or tint is invalid"),
250            Self::InvalidPlacement => {
251                write!(formatter, "image batch translation or tint is invalid")
252            }
253            Self::BatchBudgetExceeded { limit, actual } => {
254                write!(formatter, "image batch work {actual} exceeds limit {limit}")
255            }
256        }
257    }
258}
259
260impl Error for ImageError {}
261
262/// CPU outcome of a complete or partial image upload.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct ImageUploadReport {
265    uploaded_bytes: usize,
266    replaced_texture: bool,
267}
268
269impl ImageUploadReport {
270    /// Returns RGBA bytes submitted to the queue.
271    pub const fn uploaded_bytes(self) -> usize {
272        self.uploaded_bytes
273    }
274
275    /// Returns whether the operation replaced the underlying texture.
276    pub const fn replaced_texture(self) -> bool {
277        self.replaced_texture
278    }
279}
280
281/// CPU outcome of replacing a retained image/sprite instance batch.
282///
283/// This report is intentionally distinct from [`ImageUploadReport`]: batch
284/// replacement uploads instance-buffer records and does not replace or upload
285/// the referenced image texture.
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub struct ImageBatchUploadReport {
288    uploaded_instance_bytes: usize,
289    replaced_instance_buffer: bool,
290    sprite_count: usize,
291    retained_capacity: usize,
292    gpu_capacity: usize,
293    retained_bytes: usize,
294    peak_retained_bytes: usize,
295    peak_gpu_bytes: usize,
296}
297
298impl ImageBatchUploadReport {
299    /// Returns instance-buffer bytes submitted to the queue.
300    pub const fn uploaded_instance_bytes(self) -> usize {
301        self.uploaded_instance_bytes
302    }
303
304    /// Returns whether the operation replaced the underlying instance buffer.
305    pub const fn replaced_instance_buffer(self) -> bool {
306        self.replaced_instance_buffer
307    }
308
309    /// Returns the accepted logical sprite count, including zero for an empty update.
310    pub const fn sprite_count(self) -> usize {
311        self.sprite_count
312    }
313
314    /// Returns reusable CPU sprite/instance capacity, excluding allocator metadata.
315    pub const fn retained_capacity(self) -> usize {
316        self.retained_capacity
317    }
318
319    /// Returns reusable GPU instance capacity (an empty buffer has one slot).
320    pub const fn gpu_capacity(self) -> usize {
321        self.gpu_capacity
322    }
323
324    /// Returns retained CPU description and conversion-staging allocation bytes.
325    pub const fn retained_bytes(self) -> usize {
326        self.retained_bytes
327    }
328
329    /// Returns the maximum old-plus-new CPU allocation bytes owned during this update.
330    /// Caller input and opaque allocator/backend staging are not included.
331    pub const fn peak_retained_bytes(self) -> usize {
332        self.peak_retained_bytes
333    }
334
335    /// Returns old-plus-new GPU instance-buffer bytes during replacement, or the
336    /// reused allocation size. In-flight retirement remains owned by wgpu.
337    pub const fn peak_gpu_bytes(self) -> usize {
338        self.peak_gpu_bytes
339    }
340}
341
342/// Renderer-owned straight-alpha sRGB RGBA image with exact recovery pixels.
343///
344/// Source bytes use row-major top-to-bottom `R8 G8 B8 A8` texels. The sRGB GPU
345/// texture decodes RGB to linear light before tinting and alpha composition;
346/// alpha remains linear. Retained bytes make device-loss restoration exact.
347pub struct Image2d {
348    renderer_identity: Arc<()>,
349    pub(super) resource_identity: Arc<()>,
350    pub(super) recovery_identity: Arc<()>,
351    texture: wgpu::Texture,
352    pub(super) view: wgpu::TextureView,
353    width: u32,
354    height: u32,
355    pixels: Vec<u8>,
356    budget: ImageBudget,
357}
358
359impl Image2d {
360    /// Returns image width in source texels.
361    pub const fn width(&self) -> u32 {
362        self.width
363    }
364
365    /// Returns image height in source texels.
366    pub const fn height(&self) -> u32 {
367        self.height
368    }
369
370    /// Returns complete image dimensions.
371    pub const fn size(&self) -> (u32, u32) {
372        (self.width, self.height)
373    }
374
375    /// Returns the retained creation/replacement budget.
376    pub const fn budget(&self) -> ImageBudget {
377        self.budget
378    }
379
380    /// Returns exact CPU recovery pixels in row-major sRGB RGBA8 form.
381    pub fn pixels(&self) -> &[u8] {
382        &self.pixels
383    }
384
385    /// Returns retained CPU recovery bytes.
386    pub fn recovery_memory_bytes(&self) -> usize {
387        self.pixels.capacity()
388    }
389
390    /// Returns nominal single-level RGBA8 texel-storage bytes requested from
391    /// the GPU, excluding backend row/tile/page alignment and metadata.
392    pub fn gpu_allocation_bytes(&self) -> usize {
393        self.pixels.len()
394    }
395
396    /// Returns a full-image atlas rectangle.
397    pub fn full_rect(&self) -> ImageTexelRect {
398        ImageTexelRect {
399            x: 0,
400            y: 0,
401            width: self.width,
402            height: self.height,
403        }
404    }
405}
406
407/// One validated atlas region placed in local logical-screen coordinates.
408#[derive(Debug, Clone, Copy, PartialEq)]
409pub struct ImageSprite2d {
410    source: ImageTexelRect,
411    destination: LogicalViewportRegion,
412    tint: Color,
413}
414
415impl ImageSprite2d {
416    /// Creates a sprite. Atlas bounds are checked against an image at upload.
417    pub fn new(
418        source: ImageTexelRect,
419        destination: LogicalViewportRegion,
420        tint: Color,
421    ) -> Result<Self, ImageError> {
422        let origin = destination.origin().to_vec2();
423        let end = origin + destination.viewport().size();
424        if !tint.is_normalized() || !origin.is_finite() || !end.is_finite() {
425            return Err(ImageError::InvalidSprite);
426        }
427        Ok(Self {
428            source,
429            destination,
430            tint,
431        })
432    }
433
434    /// Returns its physical atlas source rectangle.
435    pub const fn source(self) -> ImageTexelRect {
436        self.source
437    }
438
439    /// Returns its local logical destination rectangle.
440    pub const fn destination(self) -> LogicalViewportRegion {
441        self.destination
442    }
443
444    /// Returns its normalized straight-linear tint.
445    pub const fn tint(self) -> Color {
446        self.tint
447    }
448}
449
450/// Hard retained-count and byte limits for an [`ImageBatch2d`].
451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
452pub struct ImageBatchBudget {
453    max_sprites: usize,
454    max_retained_bytes: usize,
455}
456
457impl ImageBatchBudget {
458    /// CPU bytes per sprite capacity slot: description plus conversion staging.
459    /// Does not include image pixels, fixed inline handle/proof metadata,
460    /// Vec headers or allocator metadata.
461    pub const RETAINED_BYTES_PER_SPRITE: usize =
462        std::mem::size_of::<ImageSprite2d>() + std::mem::size_of::<ImageInstance>();
463
464    /// GPU instance record bytes; empty batches retain one minimum buffer slot.
465    pub const GPU_BYTES_PER_SPRITE: usize = std::mem::size_of::<ImageInstance>();
466
467    /// Creates non-zero sprite-count and retained-byte limits.
468    pub fn new(max_sprites: usize, max_retained_bytes: usize) -> Result<Self, ImageError> {
469        if max_sprites == 0 || max_retained_bytes < batch_retained_bytes(1) {
470            return Err(ImageError::InvalidBudget);
471        }
472        Ok(Self {
473            max_sprites,
474            max_retained_bytes,
475        })
476    }
477
478    /// Returns maximum sprite instances.
479    pub const fn max_sprites(self) -> usize {
480        self.max_sprites
481    }
482
483    /// Returns maximum retained CPU sprite-description and conversion-staging bytes.
484    pub const fn max_retained_bytes(self) -> usize {
485        self.max_retained_bytes
486    }
487}
488
489impl Default for ImageBatchBudget {
490    fn default() -> Self {
491        Self {
492            max_sprites: 100_000,
493            max_retained_bytes: 16 * 1024 * 1024,
494        }
495    }
496}
497
498/// Renderer-owned atlas sprite batch drawn with at most one instanced draw call.
499///
500/// Sprite positions are local logical pixels and can be placed in any frame
501/// viewport without rebuilding or uploading the batch. The exact CPU sprite
502/// list is retained for renderer recovery. An empty batch is valid and emits
503/// no draw call. One fixed inline entry reuses the exact geometry validation
504/// result when ordered destination rectangles and their transform are unchanged;
505/// position, size or count updates invalidate it, while UV/tint-only updates
506/// preserve it. Restoration starts with no cached proof. This
507/// does not skip drawing or upload validation and allocates no cache storage.
508pub struct ImageBatch2d {
509    renderer_identity: Arc<()>,
510    image_identity: Arc<()>,
511    pub(super) image_recovery_identity: Arc<()>,
512    pub(super) instance_buffer: wgpu::Buffer,
513    sprites: Vec<ImageSprite2d>,
514    instances: Vec<ImageInstance>,
515    budget: ImageBatchBudget,
516    // Fixed inline metadata, not an allocation or caller-sized retained array.
517    // Successful destination/count mutations invalidate this exact proof.
518    geometry_proof: BatchProofCache,
519}
520
521impl ImageBatch2d {
522    /// Returns retained sprite count.
523    pub fn sprite_count(&self) -> usize {
524        self.sprites.len()
525    }
526
527    /// Returns the exact retained sprite descriptions.
528    pub fn sprites(&self) -> &[ImageSprite2d] {
529        &self.sprites
530    }
531
532    /// Returns its creation/replacement budget.
533    pub const fn budget(&self) -> ImageBatchBudget {
534        self.budget
535    }
536
537    /// Returns retained CPU recovery and reusable conversion-staging bytes.
538    /// Fixed inline handle/proof metadata is excluded, like Vec headers.
539    pub fn recovery_memory_bytes(&self) -> usize {
540        self.sprites
541            .capacity()
542            .saturating_mul(std::mem::size_of::<ImageSprite2d>())
543            .saturating_add(
544                self.instances
545                    .capacity()
546                    .saturating_mul(std::mem::size_of::<ImageInstance>()),
547            )
548    }
549
550    /// Returns actual retained GPU buffer bytes, including reusable spare capacity.
551    pub fn gpu_allocation_bytes(&self) -> usize {
552        self.instance_buffer.size() as usize
553    }
554
555    /// Returns CPU capacity reusable without growing either retained array.
556    pub fn capacity(&self) -> usize {
557        self.sprites.capacity().min(self.instances.capacity())
558    }
559
560    pub(super) fn sprites_are_safe_for_target(
561        &self,
562        viewport_origin: Vec2,
563        clip_transform: [f32; 4],
564    ) -> bool {
565        self.geometry_proof
566            .validate(&self.sprites, viewport_origin, clip_transform)
567    }
568}
569
570#[repr(C)]
571#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
572pub(super) struct ImageInstance {
573    pub(super) destination: [f32; 4],
574    pub(super) uv_rect: [f32; 4],
575    pub(super) tint: [f32; 4],
576}
577
578impl ImageInstance {
579    const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
580        wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4];
581    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
582        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
583        step_mode: wgpu::VertexStepMode::Instance,
584        attributes: &Self::ATTRIBUTES,
585    };
586}
587
588#[repr(C)]
589#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
590pub(super) struct ImageUniform {
591    pub(super) destination: [f32; 4],
592    pub(super) uv_rect: [f32; 4],
593    pub(super) tint: [f32; 4],
594    pub(super) world_clip_x: [f32; 4],
595    pub(super) world_clip_y: [f32; 4],
596    pub(super) world_mode: [f32; 4],
597}
598
599pub(super) fn batch_uniform(
600    target: LogicalViewport,
601    viewport_origin: Vec2,
602    placement: ImageBatchPlacement,
603) -> Result<ImageUniform, RendererFrameError> {
604    let origin = viewport_origin + placement.translation().to_vec2();
605    let destination = [2.0 / target.width(), -2.0 / target.height(), -1.0, 1.0];
606    if ![origin.x, origin.y]
607        .into_iter()
608        .chain(destination)
609        .all(is_portable_shader_source)
610    {
611        return Err(RendererFrameError::InvalidGeometryTransform);
612    }
613    Ok(ImageUniform {
614        destination,
615        uv_rect: [origin.x, origin.y, 0.0, 0.0],
616        tint: placement.tint().to_array(),
617        world_clip_x: [0.0; 4],
618        world_clip_y: [0.0; 4],
619        world_mode: [0.0; 4],
620    })
621}
622
623pub(super) struct ImageRenderer {
624    pub(super) pipeline: wgpu::RenderPipeline,
625    pub(super) batch_pipeline: wgpu::RenderPipeline,
626    pub(super) bind_group_layout: wgpu::BindGroupLayout,
627    nearest_sampler: wgpu::Sampler,
628    linear_sampler: wgpu::Sampler,
629}
630
631impl ImageRenderer {
632    pub(super) fn new(
633        device: &wgpu::Device,
634        format: wgpu::TextureFormat,
635        sample_count: u32,
636    ) -> Self {
637        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
638            label: Some("sim-engine image shader"),
639            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("image.wgsl"))),
640        });
641        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
642            label: Some("sim-engine image bind group layout"),
643            entries: &[
644                wgpu::BindGroupLayoutEntry {
645                    binding: 0,
646                    visibility: wgpu::ShaderStages::FRAGMENT,
647                    ty: wgpu::BindingType::Texture {
648                        multisampled: false,
649                        view_dimension: wgpu::TextureViewDimension::D2,
650                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
651                    },
652                    count: None,
653                },
654                wgpu::BindGroupLayoutEntry {
655                    binding: 1,
656                    visibility: wgpu::ShaderStages::FRAGMENT,
657                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
658                    count: None,
659                },
660                wgpu::BindGroupLayoutEntry {
661                    binding: 2,
662                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
663                    ty: wgpu::BindingType::Buffer {
664                        ty: wgpu::BufferBindingType::Uniform,
665                        has_dynamic_offset: false,
666                        min_binding_size: None,
667                    },
668                    count: None,
669                },
670            ],
671        });
672        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
673            label: Some("sim-engine image pipeline layout"),
674            bind_group_layouts: &[Some(&bind_group_layout)],
675            immediate_size: 0,
676        });
677        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
678            label: Some("sim-engine image pipeline"),
679            layout: Some(&layout),
680            vertex: wgpu::VertexState {
681                module: &shader,
682                entry_point: Some("image_vs_main"),
683                compilation_options: wgpu::PipelineCompilationOptions::default(),
684                buffers: &[],
685            },
686            primitive: wgpu::PrimitiveState {
687                topology: wgpu::PrimitiveTopology::TriangleList,
688                ..Default::default()
689            },
690            depth_stencil: None,
691            multisample: wgpu::MultisampleState {
692                count: sample_count,
693                ..Default::default()
694            },
695            fragment: Some(wgpu::FragmentState {
696                module: &shader,
697                entry_point: Some("image_fs_main"),
698                compilation_options: wgpu::PipelineCompilationOptions::default(),
699                targets: &[Some(wgpu::ColorTargetState {
700                    format,
701                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
702                    write_mask: wgpu::ColorWrites::ALL,
703                })],
704            }),
705            multiview_mask: None,
706            cache: None,
707        });
708        let batch_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
709            label: Some("sim-engine image batch pipeline"),
710            layout: Some(&layout),
711            vertex: wgpu::VertexState {
712                module: &shader,
713                entry_point: Some("image_batch_vs_main"),
714                compilation_options: wgpu::PipelineCompilationOptions::default(),
715                buffers: &[Some(ImageInstance::LAYOUT)],
716            },
717            primitive: wgpu::PrimitiveState {
718                topology: wgpu::PrimitiveTopology::TriangleList,
719                ..Default::default()
720            },
721            depth_stencil: None,
722            multisample: wgpu::MultisampleState {
723                count: sample_count,
724                ..Default::default()
725            },
726            fragment: Some(wgpu::FragmentState {
727                module: &shader,
728                entry_point: Some("image_fs_main"),
729                compilation_options: wgpu::PipelineCompilationOptions::default(),
730                targets: &[Some(wgpu::ColorTargetState {
731                    format,
732                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
733                    write_mask: wgpu::ColorWrites::ALL,
734                })],
735            }),
736            multiview_mask: None,
737            cache: None,
738        });
739        let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
740            label: Some("sim-engine nearest image sampler"),
741            mag_filter: wgpu::FilterMode::Nearest,
742            min_filter: wgpu::FilterMode::Nearest,
743            ..Default::default()
744        });
745        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
746            label: Some("sim-engine linear image sampler"),
747            mag_filter: wgpu::FilterMode::Linear,
748            min_filter: wgpu::FilterMode::Linear,
749            ..Default::default()
750        });
751        Self {
752            pipeline,
753            batch_pipeline,
754            bind_group_layout,
755            nearest_sampler,
756            linear_sampler,
757        }
758    }
759
760    pub(super) fn sampler(&self, sampling: ImageSampling) -> &wgpu::Sampler {
761        match sampling {
762            ImageSampling::Nearest => &self.nearest_sampler,
763            ImageSampling::Linear => &self.linear_sampler,
764        }
765    }
766}
767
768impl WgpuRenderer {
769    /// Creates an image while taking ownership of its exact recovery pixels.
770    pub fn create_image_rgba8(
771        &self,
772        width: u32,
773        height: u32,
774        pixels: Vec<u8>,
775        budget: ImageBudget,
776    ) -> Result<Image2d, ImageError> {
777        create_image_resources(
778            &self.device,
779            &self.queue,
780            Arc::clone(&self.renderer_identity),
781            width,
782            height,
783            pixels,
784            budget,
785        )
786    }
787
788    /// Copies a bounded byte slice into a retained image recovery snapshot.
789    pub fn create_image_rgba8_from_slice(
790        &self,
791        width: u32,
792        height: u32,
793        pixels: &[u8],
794        budget: ImageBudget,
795    ) -> Result<Image2d, ImageError> {
796        let byte_count = validate_image_shape(
797            width,
798            height,
799            pixels.len(),
800            budget,
801            self.device.limits().max_texture_dimension_2d,
802        )?;
803        let mut owned = Vec::new();
804        owned
805            .try_reserve_exact(byte_count)
806            .map_err(|_| ImageError::AllocationFailed {
807                requested_bytes: byte_count,
808            })?;
809        owned.extend_from_slice(pixels);
810        self.create_image_rgba8(width, height, owned, budget)
811    }
812
813    /// Replaces dimensions and pixels atomically after full preflight.
814    pub fn replace_image_rgba8(
815        &self,
816        image: &mut Image2d,
817        width: u32,
818        height: u32,
819        pixels: Vec<u8>,
820    ) -> Result<ImageUploadReport, ImageError> {
821        self.validate_image(image)?;
822        let replacement = self.create_image_rgba8(width, height, pixels, image.budget)?;
823        let uploaded_bytes = replacement.pixels.len();
824        *image = replacement;
825        Ok(ImageUploadReport {
826            uploaded_bytes,
827            replaced_texture: true,
828        })
829    }
830
831    /// Uploads one exact row-major RGBA region and updates recovery pixels.
832    pub fn update_image_region(
833        &self,
834        image: &mut Image2d,
835        region: ImageTexelRect,
836        pixels: &[u8],
837    ) -> Result<ImageUploadReport, ImageError> {
838        self.validate_image(image)?;
839        let required = validate_image_region_upload(image, region, pixels.len())?;
840        write_image_texture(
841            &self.queue,
842            &image.texture,
843            region.x,
844            region.y,
845            region.width,
846            region.height,
847            pixels,
848        );
849        let source_stride = region.width as usize * 4;
850        let destination_stride = image.width as usize * 4;
851        for row in 0..region.height as usize {
852            let source_start = row * source_stride;
853            let destination_start =
854                (region.y as usize + row) * destination_stride + region.x as usize * 4;
855            image.pixels[destination_start..destination_start + source_stride]
856                .copy_from_slice(&pixels[source_start..source_start + source_stride]);
857        }
858        Ok(ImageUploadReport {
859            uploaded_bytes: required,
860            replaced_texture: false,
861        })
862    }
863
864    /// Recreates an exact image for this renderer from retained source bytes.
865    pub fn restore_image(&self, source: &Image2d) -> Result<Image2d, ImageError> {
866        let mut restored = self.create_image_rgba8_from_slice(
867            source.width,
868            source.height,
869            &source.pixels,
870            source.budget,
871        )?;
872        restored.recovery_identity = Arc::clone(&source.recovery_identity);
873        Ok(restored)
874    }
875
876    /// Creates one retained instanced batch tied to an image or atlas.
877    pub fn create_image_batch(
878        &self,
879        image: &Image2d,
880        sprites: Vec<ImageSprite2d>,
881        budget: ImageBatchBudget,
882    ) -> Result<ImageBatch2d, ImageError> {
883        self.validate_image(image)?;
884        create_image_batch_resources(
885            &self.device,
886            &self.queue,
887            Arc::clone(&self.renderer_identity),
888            image,
889            sprites,
890            budget,
891        )
892    }
893
894    /// Updates a batch from owned input, reusing capacity when possible.
895    /// Prefer [`Self::update_image_batch`] when the host retains its input storage.
896    pub fn replace_image_batch(
897        &self,
898        image: &Image2d,
899        batch: &mut ImageBatch2d,
900        sprites: Vec<ImageSprite2d>,
901    ) -> Result<ImageBatchUploadReport, ImageError> {
902        self.update_image_batch(image, batch, &sprites)
903    }
904
905    /// Restores a batch against the restored copy of its original atlas.
906    pub fn restore_image_batch(
907        &self,
908        image: &Image2d,
909        source: &ImageBatch2d,
910    ) -> Result<ImageBatch2d, ImageError> {
911        self.validate_image(image)?;
912        if !Arc::ptr_eq(&image.recovery_identity, &source.image_recovery_identity) {
913            return Err(ImageError::RecoverySourceMismatch);
914        }
915        preflight_image_batch_capacity(&self.device, source.sprites.len(), source.budget)?;
916        let mut sprites = Vec::new();
917        let requested_bytes = source
918            .sprites
919            .len()
920            .checked_mul(std::mem::size_of::<ImageSprite2d>())
921            .ok_or(ImageError::DimensionsTooLarge)?;
922        sprites
923            .try_reserve_exact(source.sprites.len())
924            .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
925        sprites.extend_from_slice(&source.sprites);
926        self.create_image_batch(image, sprites, source.budget)
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        if !prepared_scene_belongs_to(&self.renderer_identity, &batch.renderer_identity)
942            || !prepared_scene_belongs_to(&image.resource_identity, &batch.image_identity)
943        {
944            return Err(ImageError::RendererMismatch);
945        }
946        Ok(())
947    }
948}
949
950pub(super) fn validate_image_region_upload(
951    image: &Image2d,
952    region: ImageTexelRect,
953    pixel_count: usize,
954) -> Result<usize, ImageError> {
955    if !region.fits(image.width, image.height) {
956        return Err(ImageError::UpdateRegionOutOfBounds);
957    }
958    let required =
959        image_byte_count(region.width, region.height).ok_or(ImageError::DimensionsTooLarge)?;
960    if pixel_count != required {
961        return Err(ImageError::InvalidPixelCount);
962    }
963    Ok(required)
964}
965
966#[allow(clippy::too_many_arguments)]
967pub(super) fn create_image_batch_resources(
968    device: &wgpu::Device,
969    queue: &wgpu::Queue,
970    renderer_identity: Arc<()>,
971    image: &Image2d,
972    sprites: Vec<ImageSprite2d>,
973    budget: ImageBatchBudget,
974) -> Result<ImageBatch2d, ImageError> {
975    preflight_image_batch_capacity(device, sprites.len(), budget)?;
976    let gpu_bytes = sprites
977        .len()
978        .max(1)
979        .checked_mul(std::mem::size_of::<ImageInstance>())
980        .ok_or(ImageError::DimensionsTooLarge)?;
981    if sprites.iter().any(|sprite| {
982        !sprite.source.fits(image.width, image.height)
983            || !sprite.tint.is_normalized()
984            || !logical_image_region_is_portable(sprite.destination)
985    }) {
986        return Err(ImageError::InvalidSprite);
987    }
988    let staging_bytes = sprites
989        .len()
990        .saturating_mul(std::mem::size_of::<ImageInstance>());
991    let sprites = compact_vec_with_byte_limit(
992        sprites,
993        budget.max_retained_bytes.saturating_sub(staging_bytes),
994        |actual| ImageError::BatchBudgetExceeded {
995            limit: budget.max_retained_bytes,
996            actual,
997        },
998    )?;
999    let mut instances = Vec::new();
1000    instances
1001        .try_reserve_exact(sprites.len())
1002        .map_err(|_| ImageError::AllocationFailed {
1003            requested_bytes: sprites
1004                .len()
1005                .saturating_mul(std::mem::size_of::<ImageInstance>()),
1006        })?;
1007    for sprite in &sprites {
1008        let origin = sprite.destination.origin().to_vec2();
1009        let viewport = sprite.destination.viewport();
1010        let image_width = image.width as f32;
1011        let image_height = image.height as f32;
1012        let source = sprite.source;
1013        let instance = ImageInstance {
1014            destination: [origin.x, origin.y, viewport.width(), viewport.height()],
1015            uv_rect: [
1016                (source.x as f32 + 0.5) / image_width,
1017                (source.y as f32 + 0.5) / image_height,
1018                (source.x as f32 + source.width as f32 - 0.5) / image_width,
1019                (source.y as f32 + source.height as f32 - 0.5) / image_height,
1020            ],
1021            tint: sprite.tint.to_array(),
1022        };
1023        if !instance
1024            .destination
1025            .iter()
1026            .chain(instance.uv_rect.iter())
1027            .chain(instance.tint.iter())
1028            .all(|value| value.is_finite())
1029        {
1030            return Err(ImageError::InvalidSprite);
1031        }
1032        instances.push(instance);
1033    }
1034    let retained_bytes = sprites
1035        .capacity()
1036        .saturating_mul(std::mem::size_of::<ImageSprite2d>())
1037        .saturating_add(
1038            instances
1039                .capacity()
1040                .saturating_mul(std::mem::size_of::<ImageInstance>()),
1041        );
1042    if retained_bytes > budget.max_retained_bytes {
1043        return Err(ImageError::BatchBudgetExceeded {
1044            limit: budget.max_retained_bytes,
1045            actual: retained_bytes,
1046        });
1047    }
1048    let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
1049        label: Some("sim-engine retained image sprite instances"),
1050        size: gpu_bytes as wgpu::BufferAddress,
1051        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1052        mapped_at_creation: false,
1053    });
1054    if !instances.is_empty() {
1055        queue.write_buffer(&instance_buffer, 0, bytemuck::cast_slice(&instances));
1056        submit_pending_uploads(queue);
1057    }
1058    Ok(ImageBatch2d {
1059        renderer_identity,
1060        image_identity: Arc::clone(&image.resource_identity),
1061        image_recovery_identity: Arc::clone(&image.recovery_identity),
1062        instance_buffer,
1063        sprites,
1064        instances,
1065        budget,
1066        geometry_proof: BatchProofCache::default(),
1067    })
1068}
1069
1070pub(super) fn logical_image_region_is_portable(region: LogicalViewportRegion) -> bool {
1071    let origin = region.origin().to_vec2();
1072    let size = region.viewport().size();
1073    [origin.x, origin.y, size.x, size.y]
1074        .into_iter()
1075        .all(is_portable_shader_source)
1076        && shader_interval_sum_range([
1077            (f64::from(origin.x), f64::from(origin.x)),
1078            (0.0, f64::from(size.x)),
1079        ])
1080        .is_some()
1081        && shader_interval_sum_range([
1082            (f64::from(origin.y), f64::from(origin.y)),
1083            (0.0, f64::from(size.y)),
1084        ])
1085        .is_some()
1086}
1087
1088#[allow(clippy::too_many_arguments)]
1089pub(super) fn create_image_resources(
1090    device: &wgpu::Device,
1091    queue: &wgpu::Queue,
1092    renderer_identity: Arc<()>,
1093    width: u32,
1094    height: u32,
1095    pixels: Vec<u8>,
1096    budget: ImageBudget,
1097) -> Result<Image2d, ImageError> {
1098    validate_image_shape(
1099        width,
1100        height,
1101        pixels.len(),
1102        budget,
1103        device.limits().max_texture_dimension_2d,
1104    )?;
1105    // Do not retain an arbitrarily over-capacity caller allocation behind a
1106    // small logical image budget. Compaction finishes before GPU mutation.
1107    let pixels = compact_vec_with_byte_limit(pixels, budget.max_bytes, |actual| {
1108        ImageError::BudgetExceeded {
1109            limit: budget.max_bytes,
1110            actual,
1111        }
1112    })?;
1113    let texture = device.create_texture(&wgpu::TextureDescriptor {
1114        label: Some("sim-engine retained RGBA image"),
1115        size: wgpu::Extent3d {
1116            width,
1117            height,
1118            depth_or_array_layers: 1,
1119        },
1120        mip_level_count: 1,
1121        sample_count: 1,
1122        dimension: wgpu::TextureDimension::D2,
1123        format: IMAGE_FORMAT,
1124        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1125        view_formats: &[],
1126    });
1127    write_image_texture(queue, &texture, 0, 0, width, height, &pixels);
1128    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1129    Ok(Image2d {
1130        renderer_identity,
1131        resource_identity: Arc::new(()),
1132        recovery_identity: Arc::new(()),
1133        texture,
1134        view,
1135        width,
1136        height,
1137        pixels,
1138        budget,
1139    })
1140}
1141
1142fn compact_vec_with_byte_limit<T: Copy>(
1143    values: Vec<T>,
1144    maximum_bytes: usize,
1145    capacity_error: impl FnOnce(usize) -> ImageError,
1146) -> Result<Vec<T>, ImageError> {
1147    let element_size = std::mem::size_of::<T>();
1148    let allocation_bytes = values.capacity().saturating_mul(element_size);
1149    if allocation_bytes <= maximum_bytes {
1150        return Ok(values);
1151    }
1152    let requested_bytes = values
1153        .len()
1154        .checked_mul(element_size)
1155        .ok_or(ImageError::DimensionsTooLarge)?;
1156    let mut compact = Vec::new();
1157    compact
1158        .try_reserve_exact(values.len())
1159        .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
1160    compact.extend_from_slice(&values);
1161    let actual = compact.capacity().saturating_mul(element_size);
1162    if actual > maximum_bytes {
1163        return Err(capacity_error(actual));
1164    }
1165    Ok(compact)
1166}
1167
1168pub(super) fn validate_image_shape(
1169    width: u32,
1170    height: u32,
1171    pixel_count: usize,
1172    budget: ImageBudget,
1173    max_texture_dimension: u32,
1174) -> Result<usize, ImageError> {
1175    if width == 0 || height == 0 {
1176        return Err(ImageError::ZeroDimension);
1177    }
1178    if width > budget.max_width
1179        || height > budget.max_height
1180        || width > max_texture_dimension
1181        || height > max_texture_dimension
1182        || width.checked_mul(4).is_none()
1183    {
1184        return Err(ImageError::DimensionsTooLarge);
1185    }
1186    let bytes = image_byte_count(width, height).ok_or(ImageError::DimensionsTooLarge)?;
1187    if bytes > budget.max_bytes {
1188        return Err(ImageError::BudgetExceeded {
1189            limit: budget.max_bytes,
1190            actual: bytes,
1191        });
1192    }
1193    if pixel_count != bytes {
1194        return Err(ImageError::InvalidPixelCount);
1195    }
1196    Ok(bytes)
1197}
1198
1199pub(super) fn preflight_image_batch_capacity(
1200    device: &wgpu::Device,
1201    sprite_count: usize,
1202    budget: ImageBatchBudget,
1203) -> Result<(), ImageError> {
1204    if sprite_count > budget.max_sprites {
1205        return Err(ImageError::BatchBudgetExceeded {
1206            limit: budget.max_sprites,
1207            actual: sprite_count,
1208        });
1209    }
1210    if u32::try_from(sprite_count).is_err() {
1211        return Err(ImageError::DimensionsTooLarge);
1212    }
1213    let retained_bytes = sprite_count
1214        .checked_mul(batch_retained_bytes(1))
1215        .ok_or(ImageError::DimensionsTooLarge)?;
1216    if retained_bytes > budget.max_retained_bytes {
1217        return Err(ImageError::BatchBudgetExceeded {
1218            limit: budget.max_retained_bytes,
1219            actual: retained_bytes,
1220        });
1221    }
1222    let gpu_bytes = sprite_count
1223        .max(1)
1224        .checked_mul(std::mem::size_of::<ImageInstance>())
1225        .ok_or(ImageError::DimensionsTooLarge)?;
1226    if gpu_bytes as u64 > device.limits().max_buffer_size {
1227        return Err(ImageError::DimensionsTooLarge);
1228    }
1229    Ok(())
1230}
1231
1232fn image_byte_count(width: u32, height: u32) -> Option<usize> {
1233    (width as usize)
1234        .checked_mul(height as usize)?
1235        .checked_mul(4)
1236}
1237
1238#[allow(clippy::too_many_arguments)]
1239fn write_image_texture(
1240    queue: &wgpu::Queue,
1241    texture: &wgpu::Texture,
1242    x: u32,
1243    y: u32,
1244    width: u32,
1245    height: u32,
1246    pixels: &[u8],
1247) {
1248    queue.write_texture(
1249        wgpu::TexelCopyTextureInfo {
1250            texture,
1251            mip_level: 0,
1252            origin: wgpu::Origin3d { x, y, z: 0 },
1253            aspect: wgpu::TextureAspect::All,
1254        },
1255        pixels,
1256        wgpu::TexelCopyBufferLayout {
1257            offset: 0,
1258            bytes_per_row: Some(width * 4),
1259            rows_per_image: Some(height),
1260        },
1261        wgpu::Extent3d {
1262            width,
1263            height,
1264            depth_or_array_layers: 1,
1265        },
1266    );
1267    submit_pending_uploads(queue);
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use super::*;
1273
1274    #[test]
1275    fn image_shape_checks_budget_device_and_exact_pixels_before_allocation() {
1276        let budget = ImageBudget::new(8, 8, 8 * 8 * 4).unwrap();
1277        assert_eq!(validate_image_shape(8, 8, 256, budget, 8), Ok(256));
1278        assert_eq!(
1279            validate_image_shape(8, 8, 255, budget, 8),
1280            Err(ImageError::InvalidPixelCount)
1281        );
1282        assert_eq!(
1283            validate_image_shape(9, 1, 36, budget, 16),
1284            Err(ImageError::DimensionsTooLarge)
1285        );
1286        let strict = ImageBudget::new(8, 8, 64).unwrap();
1287        assert_eq!(
1288            validate_image_shape(8, 8, 256, strict, 8),
1289            Err(ImageError::BudgetExceeded {
1290                limit: 64,
1291                actual: 256,
1292            })
1293        );
1294    }
1295
1296    #[test]
1297    fn atlas_rect_rejects_empty_and_overflowing_ranges() {
1298        assert_eq!(
1299            ImageTexelRect::new(0, 0, 0, 1),
1300            Err(ImageError::ZeroDimension)
1301        );
1302        assert_eq!(
1303            ImageTexelRect::new(u32::MAX, 0, 2, 1),
1304            Err(ImageError::DimensionsTooLarge)
1305        );
1306        assert!(ImageTexelRect::new(1, 2, 3, 4).unwrap().fits(4, 6));
1307    }
1308
1309    #[test]
1310    fn retained_sprite_region_must_fit_portable_shader_sources() {
1311        let subnormal = LogicalViewportRegion::new(
1312            LogicalScreenPosition::new(f32::from_bits(1), 0.0),
1313            LogicalViewport::new(1.0, 1.0).unwrap(),
1314        )
1315        .unwrap();
1316        let overflowing = LogicalViewportRegion::new(
1317            LogicalScreenPosition::new(2.0e38, 0.0),
1318            LogicalViewport::new(2.0e38, 1.0).unwrap(),
1319        )
1320        .unwrap();
1321        assert!(!logical_image_region_is_portable(subnormal));
1322        assert!(!logical_image_region_is_portable(overflowing));
1323    }
1324
1325    #[test]
1326    fn sprite_rejects_finite_inputs_whose_logical_extent_overflows() {
1327        let source = ImageTexelRect::new(0, 0, 1, 1).unwrap();
1328        let destination = LogicalViewportRegion::new(
1329            LogicalScreenPosition::new(f32::MAX, 0.0),
1330            LogicalViewport::new(f32::MAX, 1.0).unwrap(),
1331        )
1332        .unwrap();
1333        assert_eq!(
1334            ImageSprite2d::new(source, destination, Color::WHITE),
1335            Err(ImageError::InvalidSprite)
1336        );
1337    }
1338
1339    #[test]
1340    fn texture_and_batch_upload_reports_have_distinct_resource_semantics() {
1341        let replacement = ImageUploadReport {
1342            uploaded_bytes: 64,
1343            replaced_texture: true,
1344        };
1345        let region = ImageUploadReport {
1346            uploaded_bytes: 16,
1347            replaced_texture: false,
1348        };
1349        let batch = ImageBatchUploadReport {
1350            uploaded_instance_bytes: 96,
1351            replaced_instance_buffer: true,
1352            sprite_count: 2,
1353            retained_capacity: 2,
1354            gpu_capacity: 2,
1355            retained_bytes: batch_retained_bytes(2),
1356            peak_retained_bytes: batch_retained_bytes(2),
1357            peak_gpu_bytes: 96,
1358        };
1359
1360        assert!(replacement.replaced_texture());
1361        assert!(!region.replaced_texture());
1362        assert_eq!(replacement.uploaded_bytes(), 64);
1363        assert_eq!(region.uploaded_bytes(), 16);
1364        assert!(batch.replaced_instance_buffer());
1365        assert_eq!(batch.uploaded_instance_bytes(), 96);
1366    }
1367}