Skip to main content

sim_engine/renderer/image/
mod.rs

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/// Immutable resource limits retained with an [`Image2d`].
25#[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    /// Creates non-zero image dimension and byte limits.
34    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    /// Returns maximum image width in physical texels.
46    pub const fn max_width(self) -> u32 {
47        self.max_width
48    }
49
50    /// Returns maximum image height in physical texels.
51    pub const fn max_height(self) -> u32 {
52        self.max_height
53    }
54
55    /// Returns maximum retained and GPU RGBA bytes.
56    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/// Validated non-empty atlas rectangle in physical source texels.
72#[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    /// Creates a non-empty source rectangle. Image bounds are checked at use.
82    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    /// Returns the left source texel.
98    pub const fn x(self) -> u32 {
99        self.x
100    }
101
102    /// Returns the top source texel.
103    pub const fn y(self) -> u32 {
104        self.y
105    }
106
107    /// Returns source width in texels.
108    pub const fn width(self) -> u32 {
109        self.width
110    }
111
112    /// Returns source height in texels.
113    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/// Texture filtering used by a composed image or atlas region.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
130pub enum ImageSampling {
131    /// Preserve exact texel boundaries for pixel art and masks.
132    #[default]
133    Nearest,
134    /// Bilinearly interpolate neighboring source texels.
135    Linear,
136}
137
138/// Independent presentation of one retained image batch or glyph run.
139///
140/// Translation uses top-left logical pixels in the pass's local coordinates.
141/// It moves content before viewport placement, without moving the pass clip.
142/// Tint multiplies each instance's straight-linear RGBA, including alpha.
143/// Multiple draws can share immutable layout with different placements.
144#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct ImageBatchPlacement {
146    translation: crate::LogicalScreenVector,
147    tint: Color,
148}
149
150impl ImageBatchPlacement {
151    /// Creates a portable logical translation and normalized multiplicative tint.
152    /// Negative translation is supported. Target-dependent arithmetic is checked
153    /// again before submission; leaving the target is ordinary clipping.
154    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    /// Returns the content offset in local logical pixels.
167    pub const fn translation(self) -> crate::LogicalScreenVector {
168        self.translation
169    }
170    /// Returns the draw-wide straight-linear tint.
171    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/// Failure while creating, restoring, or updating an RGBA image.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum ImageError {
188    /// A width or height was zero.
189    ZeroDimension,
190    /// A resource budget cannot fit its minimum image or batch element.
191    InvalidBudget,
192    /// Dimensions or their RGBA byte arithmetic exceed a configured/device limit.
193    DimensionsTooLarge,
194    /// Pixel data does not contain exactly width × height × four bytes.
195    InvalidPixelCount,
196    /// The image exceeds its host-selected byte limit.
197    BudgetExceeded {
198        /// Configured byte ceiling.
199        limit: usize,
200        /// Required RGBA bytes.
201        actual: usize,
202    },
203    /// CPU recovery, conversion, or batch-staging storage could not be
204    /// reserved.
205    AllocationFailed {
206        /// Bytes requested by the failed reservation.
207        requested_bytes: usize,
208    },
209    /// A retained image belongs to another renderer generation.
210    RendererMismatch,
211    /// A recovery operation was given a different logical image than the source used.
212    RecoverySourceMismatch,
213    /// A partial update does not fit in the image.
214    UpdateRegionOutOfBounds,
215    /// A sprite source rectangle or tint is invalid for its image.
216    InvalidSprite,
217    /// Draw translation is outside the portable envelope or tint is not normalized.
218    InvalidPlacement,
219    /// A sprite batch exceeds its retained count or CPU metadata byte limit.
220    BatchBudgetExceeded {
221        /// Configured upper bound.
222        limit: usize,
223        /// Requested count or bytes.
224        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/// CPU outcome of a complete or partial image upload.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct ImageUploadReport {
272    uploaded_bytes: usize,
273    replaced_texture: bool,
274}
275
276impl ImageUploadReport {
277    /// Returns RGBA bytes submitted to the queue.
278    pub const fn uploaded_bytes(self) -> usize {
279        self.uploaded_bytes
280    }
281
282    /// Returns whether the operation replaced the underlying texture.
283    pub const fn replaced_texture(self) -> bool {
284        self.replaced_texture
285    }
286}
287
288/// CPU outcome of replacing a retained image/sprite instance batch.
289///
290/// This report is intentionally distinct from [`ImageUploadReport`]: batch
291/// replacement uploads instance-buffer records and does not replace or upload
292/// the referenced image texture.
293#[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    /// Returns instance-buffer bytes submitted to the queue.
307    pub const fn uploaded_instance_bytes(self) -> usize {
308        self.uploaded_instance_bytes
309    }
310
311    /// Returns whether the operation replaced the underlying instance buffer.
312    pub const fn replaced_instance_buffer(self) -> bool {
313        self.replaced_instance_buffer
314    }
315
316    /// Returns the accepted logical sprite count, including zero for an empty update.
317    pub const fn sprite_count(self) -> usize {
318        self.sprite_count
319    }
320
321    /// Returns reusable CPU sprite/instance capacity, excluding allocator metadata.
322    pub const fn retained_capacity(self) -> usize {
323        self.retained_capacity
324    }
325
326    /// Returns reusable GPU instance capacity (an empty buffer has one slot).
327    pub const fn gpu_capacity(self) -> usize {
328        self.gpu_capacity
329    }
330
331    /// Returns retained CPU description and conversion-staging allocation bytes.
332    pub const fn retained_bytes(self) -> usize {
333        self.retained_bytes
334    }
335
336    /// Returns the maximum old-plus-new CPU allocation bytes owned during this update.
337    /// Caller input and opaque allocator/backend staging are not included.
338    pub const fn peak_retained_bytes(self) -> usize {
339        self.peak_retained_bytes
340    }
341
342    /// Returns old-plus-new GPU instance-buffer bytes during replacement, or the
343    /// reused allocation size. In-flight retirement remains owned by wgpu.
344    pub const fn peak_gpu_bytes(self) -> usize {
345        self.peak_gpu_bytes
346    }
347}
348
349/// Renderer-owned straight-alpha sRGB RGBA image with exact recovery pixels.
350///
351/// Source bytes use row-major top-to-bottom `R8 G8 B8 A8` texels. The sRGB GPU
352/// texture decodes RGB to linear light before tinting and alpha composition;
353/// alpha remains linear. Retained bytes make device-loss restoration exact.
354pub 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    /// Returns image width in source texels.
368    pub const fn width(&self) -> u32 {
369        self.width
370    }
371
372    /// Returns image height in source texels.
373    pub const fn height(&self) -> u32 {
374        self.height
375    }
376
377    /// Returns complete image dimensions.
378    pub const fn size(&self) -> (u32, u32) {
379        (self.width, self.height)
380    }
381
382    /// Returns the retained creation/replacement budget.
383    pub const fn budget(&self) -> ImageBudget {
384        self.budget
385    }
386
387    /// Returns exact CPU recovery pixels in row-major sRGB RGBA8 form.
388    pub fn pixels(&self) -> &[u8] {
389        &self.pixels
390    }
391
392    /// Returns retained CPU recovery bytes.
393    pub fn recovery_memory_bytes(&self) -> usize {
394        self.pixels.capacity()
395    }
396
397    /// Returns nominal single-level RGBA8 texel-storage bytes requested from
398    /// the GPU, excluding backend row/tile/page alignment and metadata.
399    pub fn gpu_allocation_bytes(&self) -> usize {
400        self.pixels.len()
401    }
402
403    /// Returns a full-image atlas rectangle.
404    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/// One validated atlas region placed in local logical-screen coordinates.
415#[derive(Debug, Clone, Copy, PartialEq)]
416pub struct ImageSprite2d {
417    source: ImageTexelRect,
418    destination: LogicalViewportRegion,
419    tint: Color,
420}
421
422impl ImageSprite2d {
423    /// Creates a sprite. Atlas bounds are checked against an image at upload.
424    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    /// Returns its physical atlas source rectangle.
442    pub const fn source(self) -> ImageTexelRect {
443        self.source
444    }
445
446    /// Returns its local logical destination rectangle.
447    pub const fn destination(self) -> LogicalViewportRegion {
448        self.destination
449    }
450
451    /// Returns its normalized straight-linear tint.
452    pub const fn tint(self) -> Color {
453        self.tint
454    }
455}
456
457/// Hard retained-count and byte limits for an [`ImageBatch2d`].
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub struct ImageBatchBudget {
460    max_sprites: usize,
461    max_retained_bytes: usize,
462}
463
464impl ImageBatchBudget {
465    /// CPU bytes per sprite capacity slot: description plus conversion staging.
466    /// Does not include image pixels, fixed inline handle/proof metadata,
467    /// Vec headers or allocator metadata.
468    pub const RETAINED_BYTES_PER_SPRITE: usize =
469        std::mem::size_of::<ImageSprite2d>() + std::mem::size_of::<ImageInstance>();
470
471    /// GPU instance record bytes; empty batches retain one minimum buffer slot.
472    pub const GPU_BYTES_PER_SPRITE: usize = std::mem::size_of::<ImageInstance>();
473
474    /// Creates non-zero sprite-count and retained-byte limits.
475    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    /// Returns maximum sprite instances.
486    pub const fn max_sprites(self) -> usize {
487        self.max_sprites
488    }
489
490    /// Returns maximum retained CPU sprite-description and conversion-staging bytes.
491    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
505/// Renderer-owned atlas sprite batch drawn with at most one instanced draw call.
506///
507/// Sprite positions are local logical pixels and can be placed in any frame
508/// viewport without rebuilding or uploading the batch. The exact CPU sprite
509/// list is retained for renderer recovery. An empty batch is valid and emits
510/// no draw call. One fixed inline entry reuses the exact geometry validation
511/// result when ordered destination rectangles and their transform are unchanged;
512/// position, size or count updates invalidate it, while UV/tint-only updates
513/// preserve it. Restoration starts with no cached proof. This
514/// does not skip drawing or upload validation and allocates no cache storage.
515pub 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    // Fixed inline metadata, not an allocation or caller-sized retained array.
524    // Successful destination/count mutations invalidate this exact proof.
525    geometry_proof: BatchProofCache,
526}
527
528impl ImageBatch2d {
529    /// Returns retained sprite count.
530    pub fn sprite_count(&self) -> usize {
531        self.sprites.len()
532    }
533
534    /// Returns the exact retained sprite descriptions.
535    pub fn sprites(&self) -> &[ImageSprite2d] {
536        &self.sprites
537    }
538
539    /// Returns its creation/replacement budget.
540    pub const fn budget(&self) -> ImageBatchBudget {
541        self.budget
542    }
543
544    /// Returns retained CPU recovery and reusable conversion-staging bytes.
545    /// Fixed inline handle/proof metadata is excluded, like Vec headers.
546    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    /// Returns actual retained GPU buffer bytes, including reusable spare capacity.
558    pub fn gpu_allocation_bytes(&self) -> usize {
559        self.instance_buffer.size() as usize
560    }
561
562    /// Returns CPU capacity reusable without growing either retained array.
563    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    /// Creates an image while taking ownership of its exact recovery pixels.
777    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    /// Copies a bounded byte slice into a retained image recovery snapshot.
796    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    /// Replaces dimensions and pixels atomically after full preflight.
821    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    /// Uploads one exact row-major RGBA region and updates recovery pixels.
839    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    /// Recreates an exact image for this renderer from retained source bytes.
872    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    /// Creates one retained instanced batch tied to an image or atlas.
884    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    /// Updates a batch from owned input, reusing capacity when possible.
902    /// Prefer [`Self::update_image_batch`] when the host retains its input storage.
903    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    /// Restores a batch against the restored copy of its original atlas.
913    pub fn restore_image_batch(
914        &self,
915        image: &Image2d,
916        source: &ImageBatch2d,
917    ) -> Result<ImageBatch2d, ImageError> {
918        self.validate_image(image)?;
919        if !Arc::ptr_eq(&image.recovery_identity, &source.image_recovery_identity) {
920            return Err(ImageError::RecoverySourceMismatch);
921        }
922        preflight_image_batch_capacity(&self.device, source.sprites.len(), source.budget)?;
923        let mut sprites = Vec::new();
924        let requested_bytes = source
925            .sprites
926            .len()
927            .checked_mul(std::mem::size_of::<ImageSprite2d>())
928            .ok_or(ImageError::DimensionsTooLarge)?;
929        sprites
930            .try_reserve_exact(source.sprites.len())
931            .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
932        sprites.extend_from_slice(&source.sprites);
933        self.create_image_batch(image, sprites, source.budget)
934    }
935
936    pub(super) fn validate_image(&self, image: &Image2d) -> Result<(), ImageError> {
937        prepared_scene_belongs_to(&self.renderer_identity, &image.renderer_identity)
938            .then_some(())
939            .ok_or(ImageError::RendererMismatch)
940    }
941
942    pub(super) fn validate_image_batch(
943        &self,
944        image: &Image2d,
945        batch: &ImageBatch2d,
946    ) -> Result<(), ImageError> {
947        self.validate_image(image)?;
948        if !prepared_scene_belongs_to(&self.renderer_identity, &batch.renderer_identity)
949            || !prepared_scene_belongs_to(&image.resource_identity, &batch.image_identity)
950        {
951            return Err(ImageError::RendererMismatch);
952        }
953        Ok(())
954    }
955}
956
957pub(super) fn validate_image_region_upload(
958    image: &Image2d,
959    region: ImageTexelRect,
960    pixel_count: usize,
961) -> Result<usize, ImageError> {
962    if !region.fits(image.width, image.height) {
963        return Err(ImageError::UpdateRegionOutOfBounds);
964    }
965    let required =
966        image_byte_count(region.width, region.height).ok_or(ImageError::DimensionsTooLarge)?;
967    if pixel_count != required {
968        return Err(ImageError::InvalidPixelCount);
969    }
970    Ok(required)
971}
972
973#[allow(clippy::too_many_arguments)]
974pub(super) fn create_image_batch_resources(
975    device: &wgpu::Device,
976    queue: &wgpu::Queue,
977    renderer_identity: Arc<()>,
978    image: &Image2d,
979    sprites: Vec<ImageSprite2d>,
980    budget: ImageBatchBudget,
981) -> Result<ImageBatch2d, ImageError> {
982    preflight_image_batch_capacity(device, sprites.len(), budget)?;
983    let gpu_bytes = sprites
984        .len()
985        .max(1)
986        .checked_mul(std::mem::size_of::<ImageInstance>())
987        .ok_or(ImageError::DimensionsTooLarge)?;
988    if sprites.iter().any(|sprite| {
989        !sprite.source.fits(image.width, image.height)
990            || !sprite.tint.is_normalized()
991            || !logical_image_region_is_portable(sprite.destination)
992    }) {
993        return Err(ImageError::InvalidSprite);
994    }
995    let staging_bytes = sprites
996        .len()
997        .saturating_mul(std::mem::size_of::<ImageInstance>());
998    let sprites = compact_vec_with_byte_limit(
999        sprites,
1000        budget.max_retained_bytes.saturating_sub(staging_bytes),
1001        |actual| ImageError::BatchBudgetExceeded {
1002            limit: budget.max_retained_bytes,
1003            actual,
1004        },
1005    )?;
1006    let mut instances = Vec::new();
1007    instances
1008        .try_reserve_exact(sprites.len())
1009        .map_err(|_| ImageError::AllocationFailed {
1010            requested_bytes: sprites
1011                .len()
1012                .saturating_mul(std::mem::size_of::<ImageInstance>()),
1013        })?;
1014    for sprite in &sprites {
1015        let origin = sprite.destination.origin().to_vec2();
1016        let viewport = sprite.destination.viewport();
1017        let image_width = image.width as f32;
1018        let image_height = image.height as f32;
1019        let source = sprite.source;
1020        let instance = ImageInstance {
1021            destination: [origin.x, origin.y, viewport.width(), viewport.height()],
1022            uv_rect: [
1023                (source.x as f32 + 0.5) / image_width,
1024                (source.y as f32 + 0.5) / image_height,
1025                (source.x as f32 + source.width as f32 - 0.5) / image_width,
1026                (source.y as f32 + source.height as f32 - 0.5) / image_height,
1027            ],
1028            tint: sprite.tint.to_array(),
1029        };
1030        if !instance
1031            .destination
1032            .iter()
1033            .chain(instance.uv_rect.iter())
1034            .chain(instance.tint.iter())
1035            .all(|value| value.is_finite())
1036        {
1037            return Err(ImageError::InvalidSprite);
1038        }
1039        instances.push(instance);
1040    }
1041    let retained_bytes = sprites
1042        .capacity()
1043        .saturating_mul(std::mem::size_of::<ImageSprite2d>())
1044        .saturating_add(
1045            instances
1046                .capacity()
1047                .saturating_mul(std::mem::size_of::<ImageInstance>()),
1048        );
1049    if retained_bytes > budget.max_retained_bytes {
1050        return Err(ImageError::BatchBudgetExceeded {
1051            limit: budget.max_retained_bytes,
1052            actual: retained_bytes,
1053        });
1054    }
1055    let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
1056        label: Some("sim-engine retained image sprite instances"),
1057        size: gpu_bytes as wgpu::BufferAddress,
1058        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1059        mapped_at_creation: false,
1060    });
1061    if !instances.is_empty() {
1062        queue.write_buffer(&instance_buffer, 0, bytemuck::cast_slice(&instances));
1063        submit_pending_uploads(queue);
1064    }
1065    Ok(ImageBatch2d {
1066        renderer_identity,
1067        image_identity: Arc::clone(&image.resource_identity),
1068        image_recovery_identity: Arc::clone(&image.recovery_identity),
1069        instance_buffer,
1070        sprites,
1071        instances,
1072        budget,
1073        geometry_proof: BatchProofCache::default(),
1074    })
1075}
1076
1077pub(super) fn logical_image_region_is_portable(region: LogicalViewportRegion) -> bool {
1078    let origin = region.origin().to_vec2();
1079    let size = region.viewport().size();
1080    [origin.x, origin.y, size.x, size.y]
1081        .into_iter()
1082        .all(is_portable_shader_source)
1083        && shader_interval_sum_range([
1084            (f64::from(origin.x), f64::from(origin.x)),
1085            (0.0, f64::from(size.x)),
1086        ])
1087        .is_some()
1088        && shader_interval_sum_range([
1089            (f64::from(origin.y), f64::from(origin.y)),
1090            (0.0, f64::from(size.y)),
1091        ])
1092        .is_some()
1093}
1094
1095#[allow(clippy::too_many_arguments)]
1096pub(super) fn create_image_resources(
1097    device: &wgpu::Device,
1098    queue: &wgpu::Queue,
1099    renderer_identity: Arc<()>,
1100    width: u32,
1101    height: u32,
1102    pixels: Vec<u8>,
1103    budget: ImageBudget,
1104) -> Result<Image2d, ImageError> {
1105    validate_image_shape(
1106        width,
1107        height,
1108        pixels.len(),
1109        budget,
1110        device.limits().max_texture_dimension_2d,
1111    )?;
1112    // Do not retain an arbitrarily over-capacity caller allocation behind a
1113    // small logical image budget. Compaction finishes before GPU mutation.
1114    let pixels = compact_vec_with_byte_limit(pixels, budget.max_bytes, |actual| {
1115        ImageError::BudgetExceeded {
1116            limit: budget.max_bytes,
1117            actual,
1118        }
1119    })?;
1120    let texture = device.create_texture(&wgpu::TextureDescriptor {
1121        label: Some("sim-engine retained RGBA image"),
1122        size: wgpu::Extent3d {
1123            width,
1124            height,
1125            depth_or_array_layers: 1,
1126        },
1127        mip_level_count: 1,
1128        sample_count: 1,
1129        dimension: wgpu::TextureDimension::D2,
1130        format: IMAGE_FORMAT,
1131        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1132        view_formats: &[],
1133    });
1134    write_image_texture(queue, &texture, 0, 0, width, height, &pixels);
1135    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1136    Ok(Image2d {
1137        renderer_identity,
1138        resource_identity: Arc::new(()),
1139        recovery_identity: Arc::new(()),
1140        texture,
1141        view,
1142        width,
1143        height,
1144        pixels,
1145        budget,
1146    })
1147}
1148
1149fn compact_vec_with_byte_limit<T: Copy>(
1150    values: Vec<T>,
1151    maximum_bytes: usize,
1152    capacity_error: impl FnOnce(usize) -> ImageError,
1153) -> Result<Vec<T>, ImageError> {
1154    let element_size = std::mem::size_of::<T>();
1155    let allocation_bytes = values.capacity().saturating_mul(element_size);
1156    if allocation_bytes <= maximum_bytes {
1157        return Ok(values);
1158    }
1159    let requested_bytes = values
1160        .len()
1161        .checked_mul(element_size)
1162        .ok_or(ImageError::DimensionsTooLarge)?;
1163    let mut compact = Vec::new();
1164    compact
1165        .try_reserve_exact(values.len())
1166        .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
1167    compact.extend_from_slice(&values);
1168    let actual = compact.capacity().saturating_mul(element_size);
1169    if actual > maximum_bytes {
1170        return Err(capacity_error(actual));
1171    }
1172    Ok(compact)
1173}
1174
1175pub(super) fn validate_image_shape(
1176    width: u32,
1177    height: u32,
1178    pixel_count: usize,
1179    budget: ImageBudget,
1180    max_texture_dimension: u32,
1181) -> Result<usize, ImageError> {
1182    if width == 0 || height == 0 {
1183        return Err(ImageError::ZeroDimension);
1184    }
1185    if width > budget.max_width
1186        || height > budget.max_height
1187        || width > max_texture_dimension
1188        || height > max_texture_dimension
1189        || width.checked_mul(4).is_none()
1190    {
1191        return Err(ImageError::DimensionsTooLarge);
1192    }
1193    let bytes = image_byte_count(width, height).ok_or(ImageError::DimensionsTooLarge)?;
1194    if bytes > budget.max_bytes {
1195        return Err(ImageError::BudgetExceeded {
1196            limit: budget.max_bytes,
1197            actual: bytes,
1198        });
1199    }
1200    if pixel_count != bytes {
1201        return Err(ImageError::InvalidPixelCount);
1202    }
1203    Ok(bytes)
1204}
1205
1206pub(super) fn preflight_image_batch_capacity(
1207    device: &wgpu::Device,
1208    sprite_count: usize,
1209    budget: ImageBatchBudget,
1210) -> Result<(), ImageError> {
1211    if sprite_count > budget.max_sprites {
1212        return Err(ImageError::BatchBudgetExceeded {
1213            limit: budget.max_sprites,
1214            actual: sprite_count,
1215        });
1216    }
1217    if u32::try_from(sprite_count).is_err() {
1218        return Err(ImageError::DimensionsTooLarge);
1219    }
1220    let retained_bytes = sprite_count
1221        .checked_mul(batch_retained_bytes(1))
1222        .ok_or(ImageError::DimensionsTooLarge)?;
1223    if retained_bytes > budget.max_retained_bytes {
1224        return Err(ImageError::BatchBudgetExceeded {
1225            limit: budget.max_retained_bytes,
1226            actual: retained_bytes,
1227        });
1228    }
1229    let gpu_bytes = sprite_count
1230        .max(1)
1231        .checked_mul(std::mem::size_of::<ImageInstance>())
1232        .ok_or(ImageError::DimensionsTooLarge)?;
1233    if gpu_bytes as u64 > device.limits().max_buffer_size {
1234        return Err(ImageError::DimensionsTooLarge);
1235    }
1236    Ok(())
1237}
1238
1239fn image_byte_count(width: u32, height: u32) -> Option<usize> {
1240    (width as usize)
1241        .checked_mul(height as usize)?
1242        .checked_mul(4)
1243}
1244
1245#[allow(clippy::too_many_arguments)]
1246fn write_image_texture(
1247    queue: &wgpu::Queue,
1248    texture: &wgpu::Texture,
1249    x: u32,
1250    y: u32,
1251    width: u32,
1252    height: u32,
1253    pixels: &[u8],
1254) {
1255    queue.write_texture(
1256        wgpu::TexelCopyTextureInfo {
1257            texture,
1258            mip_level: 0,
1259            origin: wgpu::Origin3d { x, y, z: 0 },
1260            aspect: wgpu::TextureAspect::All,
1261        },
1262        pixels,
1263        wgpu::TexelCopyBufferLayout {
1264            offset: 0,
1265            bytes_per_row: Some(width * 4),
1266            rows_per_image: Some(height),
1267        },
1268        wgpu::Extent3d {
1269            width,
1270            height,
1271            depth_or_array_layers: 1,
1272        },
1273    );
1274    submit_pending_uploads(queue);
1275}
1276
1277#[cfg(test)]
1278mod tests;