Skip to main content

sim_engine/renderer/image/
updates.rs

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