Skip to main content

sim_engine/renderer/image/
updates.rs

1use std::sync::Arc;
2
3use super::{
4    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchUploadReport, ImageError, ImageInstance,
5    ImageSprite2d, logical_image_region_is_portable, preflight_image_batch_capacity, proof,
6};
7use crate::renderer::{WgpuRenderer, submit_pending_uploads};
8
9pub(in crate::renderer) fn batch_retained_bytes(count: usize) -> usize {
10    count.saturating_mul(ImageBatchBudget::RETAINED_BYTES_PER_SPRITE)
11}
12
13impl WgpuRenderer {
14    /// Atomically updates retained sprite descriptions from borrowed input.
15    ///
16    /// Reuses both CPU arrays and the GPU buffer while capacity permits. Equal
17    /// input submits no upload. Shrinking, including to zero sprites, retains
18    /// capacity. Growth reserves exact bounded replacement arrays before changing
19    /// drawable state. Synchronous validation/allocation errors preserve the old
20    /// batch. Device failure is not a rollback of already submitted GPU work.
21    ///
22    /// The original image and current renderer generation must match. The queue
23    /// orders uploads after previously submitted draws; the frame borrow prevents
24    /// updating a batch still referenced by an unsubmitted composer.
25    pub fn update_image_batch(
26        &self,
27        image: &Image2d,
28        batch: &mut ImageBatch2d,
29        sprites: &[ImageSprite2d],
30    ) -> Result<ImageBatchUploadReport, ImageError> {
31        self.validate_image_batch(image, batch)?;
32        update_image_batch_resources(
33            &self.device,
34            &self.queue,
35            image,
36            batch,
37            sprites.iter().copied(),
38            sprites.len(),
39            batch.budget,
40        )
41    }
42}
43
44fn replacement_array<T: Copy>(
45    current_capacity: usize,
46    count: usize,
47    compact: bool,
48) -> Result<Option<Vec<T>>, ImageError> {
49    if count <= current_capacity && !compact {
50        return Ok(None);
51    }
52    let mut replacement = Vec::new();
53    replacement
54        .try_reserve_exact(count)
55        .map_err(|_| ImageError::AllocationFailed {
56            requested_bytes: count.saturating_mul(std::mem::size_of::<T>()),
57        })?;
58    Ok(Some(replacement))
59}
60
61fn instance_for(image: &Image2d, sprite: ImageSprite2d) -> ImageInstance {
62    let origin = sprite.destination.origin().to_vec2();
63    let viewport = sprite.destination.viewport();
64    let source = sprite.source;
65    ImageInstance {
66        destination: [origin.x, origin.y, viewport.width(), viewport.height()],
67        uv_rect: [
68            (source.x as f32 + 0.5) / image.width as f32,
69            (source.y as f32 + 0.5) / image.height as f32,
70            (source.x as f32 + source.width as f32 - 0.5) / image.width as f32,
71            (source.y as f32 + source.height as f32 - 0.5) / image.height as f32,
72        ],
73        tint: sprite.tint.to_array(),
74    }
75}
76
77#[allow(clippy::too_many_arguments)]
78pub(in crate::renderer) fn update_image_batch_resources<I>(
79    device: &wgpu::Device,
80    queue: &wgpu::Queue,
81    image: &Image2d,
82    batch: &mut ImageBatch2d,
83    sprites: I,
84    count: usize,
85    budget: ImageBatchBudget,
86) -> Result<ImageBatchUploadReport, ImageError>
87where
88    I: Iterator<Item = ImageSprite2d> + Clone,
89{
90    if !Arc::ptr_eq(&image.renderer_identity, &batch.renderer_identity)
91        || !Arc::ptr_eq(&image.resource_identity, &batch.image_identity)
92    {
93        return Err(ImageError::RendererMismatch);
94    }
95    preflight_image_batch_capacity(device, count, budget)?;
96    let mut destinations_unchanged = count == batch.sprites.len();
97    let mut sprites_unchanged = destinations_unchanged;
98    let mut actual_count = 0;
99    for (index, sprite) in sprites.clone().enumerate() {
100        // Fuse count, source/tint, destination proof and equality checks. Glyph
101        // placements are a lazy transformed iterator; replaying it for each
102        // check would repeat the same construction and interval arithmetic.
103        if index >= count {
104            return Err(ImageError::InvalidSprite);
105        }
106        let previous = batch.sprites.get(index);
107        let same_destination = previous.is_some_and(|previous| {
108            proof::destination_bits(*previous) == proof::destination_bits(sprite)
109        });
110        if !sprite.source.fits(image.width, image.height)
111            || !sprite.tint.is_normalized()
112            || (!same_destination && !logical_image_region_is_portable(sprite.destination))
113        {
114            return Err(ImageError::InvalidSprite);
115        }
116        // Every stored sprite already passed this exact immutable destination
117        // proof. Reuse it only for all four bit-identical components, while
118        // validating source and tint even on geometry-preserving updates.
119        destinations_unchanged &= same_destination;
120        sprites_unchanged &= previous == Some(&sprite);
121        actual_count += 1;
122    }
123    if actual_count != count {
124        return Err(ImageError::InvalidSprite);
125    }
126
127    let old_cpu = batch.recovery_memory_bytes();
128    let old_gpu = batch.gpu_allocation_bytes();
129    if sprites_unchanged && old_cpu <= budget.max_retained_bytes {
130        batch.budget = budget;
131        return Ok(report(batch, 0, false, old_cpu, old_gpu));
132    }
133    let compact = old_cpu > budget.max_retained_bytes;
134    let new_sprites: Option<Vec<ImageSprite2d>> =
135        replacement_array(batch.sprites.capacity(), count, compact)?;
136    let new_instances: Option<Vec<ImageInstance>> =
137        replacement_array(batch.instances.capacity(), count, compact)?;
138    let sprite_capacity = new_sprites
139        .as_ref()
140        .map_or(batch.sprites.capacity(), Vec::capacity);
141    let instance_capacity = new_instances
142        .as_ref()
143        .map_or(batch.instances.capacity(), Vec::capacity);
144    let cpu_bytes = sprite_capacity
145        .saturating_mul(std::mem::size_of::<ImageSprite2d>())
146        .saturating_add(instance_capacity.saturating_mul(std::mem::size_of::<ImageInstance>()));
147    if cpu_bytes > budget.max_retained_bytes {
148        return Err(ImageError::BatchBudgetExceeded {
149            limit: budget.max_retained_bytes,
150            actual: cpu_bytes,
151        });
152    }
153    let peak_cpu = old_cpu
154        .saturating_add(new_sprites.as_ref().map_or(0, |v| {
155            v.capacity()
156                .saturating_mul(std::mem::size_of::<ImageSprite2d>())
157        }))
158        .saturating_add(new_instances.as_ref().map_or(0, |v| {
159            v.capacity()
160                .saturating_mul(std::mem::size_of::<ImageInstance>())
161        }));
162    let gpu_bytes = count.max(1) * std::mem::size_of::<ImageInstance>();
163    let replacement = (gpu_bytes > old_gpu).then(|| {
164        device.create_buffer(&wgpu::BufferDescriptor {
165            label: Some("sim-engine grown image sprite instances"),
166            size: gpu_bytes as u64,
167            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
168            mapped_at_creation: false,
169        })
170    });
171    let replaced = replacement.is_some();
172    let peak_gpu = old_gpu.saturating_add(if replaced { gpu_bytes } else { 0 });
173    // No remaining synchronous rejection precedes publishing the new arrays.
174    // UV/tint never participate in the geometry proof. Keep that exact result
175    // when every ordered destination component is bit-identical; any changed
176    // position, size or count invalidates before the new arrays are published.
177    if !destinations_unchanged {
178        batch.geometry_proof.invalidate();
179    }
180    if let Some(values) = new_sprites {
181        batch.sprites = values;
182    }
183    if let Some(values) = new_instances {
184        batch.instances = values;
185    }
186    if let Some(buffer) = replacement {
187        batch.instance_buffer = buffer;
188    }
189    batch.sprites.clear();
190    batch.instances.clear();
191    for sprite in sprites {
192        batch.instances.push(instance_for(image, sprite));
193        batch.sprites.push(sprite);
194    }
195    batch.budget = budget;
196    let uploaded = count * std::mem::size_of::<ImageInstance>();
197    if uploaded > 0 {
198        queue.write_buffer(
199            &batch.instance_buffer,
200            0,
201            bytemuck::cast_slice(&batch.instances),
202        );
203        submit_pending_uploads(queue);
204    }
205    Ok(report(batch, uploaded, replaced, peak_cpu, peak_gpu))
206}
207
208fn report(
209    batch: &ImageBatch2d,
210    uploaded: usize,
211    replaced: bool,
212    peak_cpu: usize,
213    peak_gpu: usize,
214) -> ImageBatchUploadReport {
215    ImageBatchUploadReport {
216        uploaded_instance_bytes: uploaded,
217        replaced_instance_buffer: replaced,
218        sprite_count: batch.sprite_count(),
219        retained_capacity: batch.capacity(),
220        gpu_capacity: batch.gpu_allocation_bytes() / std::mem::size_of::<ImageInstance>(),
221        retained_bytes: batch.recovery_memory_bytes(),
222        peak_retained_bytes: peak_cpu,
223        peak_gpu_bytes: peak_gpu,
224    }
225}