Skip to main content

sim_engine/renderer/
mesh3d_dynamic.rs

1//! Scene-owned whole-bundle updates with immutable snapshot isolation.
2
3use super::*;
4
5#[path = "mesh3d_dynamic_types.rs"]
6mod types;
7pub use types::{
8    DynamicMesh3dBudget, DynamicMesh3dBudgetResource, DynamicMesh3dError, DynamicMesh3dUpdateReport,
9};
10
11#[cfg(test)]
12#[path = "mesh3d_dynamic_tests.rs"]
13mod tests;
14#[cfg(test)]
15pub(super) use tests::{assert_gpu_dynamic_contract, assert_gpu_dynamic_recovery};
16
17#[derive(Default)]
18pub(super) struct DynamicMesh3dScratch {
19    vertices: Vec<MeshVertexGpu>,
20    edges: Vec<MeshEdgeGpu>,
21    coordinates: Vec<MeshUvGpu>,
22    colors: Vec<MeshColorGpu>,
23    normals: Vec<MeshNormalGpu>,
24}
25
26impl WgpuRenderer {
27    /// Renderer-owned dynamic mesh conversion capacity, separate from scene
28    /// resources and `FrameCacheBudget`. Backend upload staging is excluded.
29    pub fn mesh3d_update_scratch_bytes(&self) -> usize {
30        self.mesh3d_renderer.dynamic_scratch.capacity_bytes()
31    }
32
33    /// Releases retained dynamic conversion scratch without changing scene/GPU
34    /// resources, returning the nominal CPU capacity released. Clear before
35    /// requesting a smaller retained-scratch limit than a previous update used.
36    pub fn clear_mesh3d_update_scratch(&mut self) -> usize {
37        let previous = std::mem::take(&mut self.mesh3d_renderer.dynamic_scratch);
38        previous.capacity_bytes()
39    }
40
41    /// Updates only the selected scene object, reusing unique GPU buffer capacity.
42    ///
43    /// Other objects and exported immutable mesh/instance clones remain unchanged:
44    /// aliases cause one whole-bundle copy-on-write. Once only this scene object
45    /// owns the new bundle, subsequent fitting updates allocate no GPU buffers.
46    /// Growth or an optional-attribute layout change replaces the whole bundle; all live vertices,
47    /// indices, UVs, colors, normals and edges are uploaded even for an identical source.
48    ///
49    /// Limits include retained capacity and old/new overlap. Validation, scene
50    /// accounting and every fallible host preparation complete before GPU writes.
51    /// Returned errors preserve the object's previous geometry and scene state;
52    /// private bounded conversion scratch may warm before a later device failure.
53    /// Asynchronous device loss is separate; recovery restores committed source
54    /// and reserved capacities. Queue ordering protects earlier submitted frames.
55    ///
56    /// Source topology is a validated nonempty `Mesh3d`. Hide/remove an object for
57    /// an empty chunk. Its ID, transform, visibility and material are preserved.
58    /// UV-bearing material cannot be retained after removing source UVs.
59    pub fn update_scene3d_mesh(
60        &mut self,
61        scene: &mut Scene3d,
62        object_id: Object3dId,
63        source: Mesh3d,
64        budget: DynamicMesh3dBudget,
65    ) -> Result<DynamicMesh3dUpdateReport, DynamicMesh3dError> {
66        update_scene_mesh(
67            &self.device,
68            &self.queue,
69            &self.renderer_identity,
70            &mut self.mesh3d_renderer.dynamic_scratch,
71            scene,
72            object_id,
73            source,
74            budget,
75        )
76    }
77}
78
79fn final_limit(
80    resource: Mesh3dUploadBudgetResource,
81    actual: usize,
82    limit: usize,
83) -> Result<(), DynamicMesh3dError> {
84    if actual > limit {
85        return Err(Mesh3dResourceError::BudgetExceeded {
86            resource,
87            actual,
88            limit,
89        }
90        .into());
91    }
92    Ok(())
93}
94
95fn peak_limit(
96    resource: DynamicMesh3dBudgetResource,
97    actual: usize,
98    limit: usize,
99) -> Result<(), DynamicMesh3dError> {
100    if actual > limit {
101        return Err(DynamicMesh3dError::BudgetExceeded {
102            resource,
103            actual,
104            limit,
105        });
106    }
107    Ok(())
108}
109
110fn checked_sum(values: impl IntoIterator<Item = usize>) -> Result<usize, DynamicMesh3dError> {
111    values.into_iter().try_fold(0usize, |sum, value| {
112        sum.checked_add(value)
113            .ok_or_else(|| Mesh3dResourceError::CapacityTooLarge.into())
114    })
115}
116
117fn bundle_is_unique(mesh: &RetainedMesh3d) -> bool {
118    Arc::strong_count(&mesh.vertex_buffer) == 1
119        && [
120            &mesh.index_buffer,
121            &mesh.edge_buffer,
122            &mesh.texture_coordinate_buffer,
123            &mesh.color_buffer,
124            &mesh.normal_buffer,
125        ]
126        .into_iter()
127        .all(|buffer| {
128            buffer
129                .as_ref()
130                .is_none_or(|buffer| Arc::strong_count(buffer) == 1)
131        })
132}
133
134fn planned_allocation(
135    old: Mesh3dUploadLayout,
136    source: &Mesh3d,
137    budget: DynamicMesh3dBudget,
138    max_buffer_size: u64,
139) -> Result<Mesh3dUploadLayout, Mesh3dResourceError> {
140    let vertices = (old.vertex_bytes as usize / std::mem::size_of::<MeshVertexGpu>())
141        .max(source.vertices().len())
142        .max(budget.minimum_vertices);
143    let indices = (old.index_bytes as usize / std::mem::size_of::<u32>())
144        .max(source.triangle_indices().len())
145        .max(budget.minimum_indices);
146    let edges = (old.edge_bytes as usize / std::mem::size_of::<MeshEdgeGpu>())
147        .max(source.display_edges().len())
148        .max(budget.minimum_edges);
149    let mut allocation = preflight_mesh3d_upload(vertices, indices, edges, max_buffer_size)?;
150    if !source.texture_coordinates().is_empty() {
151        allocation.texture_coordinate_bytes = u64::try_from(vertices)
152            .ok()
153            .and_then(|vertices| vertices.checked_mul(std::mem::size_of::<MeshUvGpu>() as u64))
154            .filter(|bytes| *bytes <= max_buffer_size)
155            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
156        allocation.total_bytes = allocation
157            .total_bytes
158            .checked_add(allocation.texture_coordinate_bytes)
159            .filter(|bytes| usize::try_from(*bytes).is_ok())
160            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
161    }
162    if !source.vertex_colors().is_empty() {
163        allocation.color_bytes = u64::try_from(vertices)
164            .ok()
165            .and_then(|count| count.checked_mul(std::mem::size_of::<MeshColorGpu>() as u64))
166            .filter(|bytes| *bytes <= max_buffer_size)
167            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
168        allocation.total_bytes = allocation
169            .total_bytes
170            .checked_add(allocation.color_bytes)
171            .filter(|bytes| usize::try_from(*bytes).is_ok())
172            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
173    }
174    if !source.normals().is_empty() {
175        allocation.normal_bytes = u64::try_from(vertices)
176            .ok()
177            .and_then(|count| count.checked_mul(std::mem::size_of::<MeshNormalGpu>() as u64))
178            .filter(|bytes| *bytes <= max_buffer_size)
179            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
180        allocation.total_bytes = allocation
181            .total_bytes
182            .checked_add(allocation.normal_bytes)
183            .filter(|bytes| usize::try_from(*bytes).is_ok())
184            .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
185    }
186    Ok(allocation)
187}
188
189#[allow(clippy::too_many_arguments)]
190pub(super) fn update_scene_mesh(
191    device: &wgpu::Device,
192    queue: &wgpu::Queue,
193    identity: &Arc<()>,
194    scratch: &mut DynamicMesh3dScratch,
195    scene: &mut Scene3d,
196    object_id: Object3dId,
197    source: Mesh3d,
198    budget: DynamicMesh3dBudget,
199) -> Result<DynamicMesh3dUpdateReport, DynamicMesh3dError> {
200    let instance = scene.instance(object_id)?;
201    let old = &instance.mesh;
202    if !Arc::ptr_eq(identity, &old.renderer_identity)
203        || old
204            .material
205            .as_ref()
206            .is_some_and(|material| !material.texture().belongs_to(identity))
207    {
208        return Err(Mesh3dResourceError::RendererMismatch.into());
209    }
210    validate_mesh_source_style(&source, instance.style)?;
211    if old.material.is_some()
212        && (source.texture_coordinates().len() != source.vertices().len()
213            || source.triangle_count() == 0)
214    {
215        return Err(Mesh3dResourceError::Texture(Texture3dError::MissingTextureCoordinates).into());
216    }
217    let live = preflight_mesh3d_source(&source, device.limits().max_buffer_size)?;
218    if !mesh3d_source_is_portable(&source) {
219        return Err(Mesh3dResourceError::NonPortableVertex.into());
220    }
221    if source.texture_coordinates().iter().any(|coordinate| {
222        !is_portable_shader_source(coordinate.u()) || !is_portable_shader_source(coordinate.v())
223    }) {
224        return Err(Mesh3dResourceError::NonPortableTextureCoordinate.into());
225    }
226    let allocation = planned_allocation(
227        old.allocation,
228        &source,
229        budget,
230        device.limits().max_buffer_size,
231    )?;
232    upload::validate_allocation(device, allocation, budget.upload)?;
233    final_limit(
234        Mesh3dUploadBudgetResource::RecoveryBytes,
235        source.recovery_memory_bytes(),
236        budget.upload.max_recovery_bytes(),
237    )?;
238    let detached_aliases = !bundle_is_unique(old);
239    let layout_changed = old.allocation != allocation;
240    let grew_capacity = [
241        (allocation.vertex_bytes, old.allocation.vertex_bytes),
242        (allocation.index_bytes, old.allocation.index_bytes),
243        (allocation.edge_bytes, old.allocation.edge_bytes),
244        (allocation.color_bytes, old.allocation.color_bytes),
245        (allocation.normal_bytes, old.allocation.normal_bytes),
246        (
247            allocation.texture_coordinate_bytes,
248            old.allocation.texture_coordinate_bytes,
249        ),
250    ]
251    .into_iter()
252    .any(|(new, old)| new > old);
253    let replace_buffers = detached_aliases || layout_changed;
254    let peak_gpu_bytes = checked_sum([
255        old.gpu_allocation_bytes(),
256        if replace_buffers {
257            allocation.total_bytes as usize
258        } else {
259            0
260        },
261    ])?;
262    let same_source = old.source.vertices().as_ptr() == source.vertices().as_ptr();
263    let peak_recovery_bytes = checked_sum([
264        old.recovery_memory_bytes(),
265        if same_source {
266            0
267        } else {
268            source.recovery_memory_bytes()
269        },
270    ])?;
271    peak_limit(
272        DynamicMesh3dBudgetResource::PeakGpuBytes,
273        peak_gpu_bytes,
274        budget.peak_gpu,
275    )?;
276    peak_limit(
277        DynamicMesh3dBudgetResource::PeakRecoveryBytes,
278        peak_recovery_bytes,
279        budget.peak_recovery,
280    )?;
281    // This clone is a private candidate, after testing external snapshot aliases.
282    // No caller can acquire another scene alias while its exclusive borrow lasts.
283    let mut candidate = old.clone();
284    candidate.source = source;
285    candidate.index_count = live.index_count;
286    candidate.edge_count = live.edge_count;
287    candidate.budget = budget.upload;
288    let change = scene.prepare_dynamic_mesh_change(
289        object_id,
290        &candidate.source,
291        allocation.total_bytes as usize,
292        replace_buffers,
293    )?;
294    let (scratch_reallocations, peak_staging_bytes) = scratch.prepare(&candidate.source, budget)?;
295    let gpu_allocations = if replace_buffers {
296        let material = candidate.material.take();
297        candidate = allocate_retained_mesh(
298            device,
299            Arc::clone(identity),
300            candidate.source,
301            live,
302            allocation,
303            budget.upload,
304        );
305        candidate.material = material;
306        [
307            allocation.vertex_bytes,
308            allocation.index_bytes,
309            allocation.edge_bytes,
310            allocation.texture_coordinate_bytes,
311            allocation.color_bytes,
312            allocation.normal_bytes,
313        ]
314        .into_iter()
315        .filter(|bytes| *bytes > 0)
316        .count()
317    } else {
318        0
319    };
320    let upload_calls = write_retained_mesh_uploads(
321        queue,
322        &candidate,
323        &scratch.vertices,
324        &scratch.edges,
325        &scratch.coordinates,
326        &scratch.colors,
327        &scratch.normals,
328    );
329    submit_pending_uploads(queue);
330    let scene_statistics = scene.commit_dynamic_mesh_change(change, candidate);
331    Ok(DynamicMesh3dUpdateReport {
332        uploaded_bytes: live.total_bytes as usize,
333        upload_calls,
334        gpu_allocations,
335        detached_aliases,
336        grew_capacity,
337        capacity_gpu_bytes: allocation.total_bytes as usize,
338        scratch_capacity_bytes: scratch.capacity_bytes(),
339        scratch_reallocations,
340        peak_staging_bytes,
341        peak_gpu_bytes,
342        peak_recovery_bytes,
343        scene_statistics,
344    })
345}
346
347impl DynamicMesh3dScratch {
348    fn capacity_bytes(&self) -> usize {
349        self.vertices.capacity() * std::mem::size_of::<MeshVertexGpu>()
350            + self.edges.capacity() * std::mem::size_of::<MeshEdgeGpu>()
351            + self.coordinates.capacity() * std::mem::size_of::<MeshUvGpu>()
352            + self.colors.capacity() * std::mem::size_of::<MeshColorGpu>()
353            + self.normals.capacity() * std::mem::size_of::<MeshNormalGpu>()
354    }
355
356    fn prepare(
357        &mut self,
358        source: &Mesh3d,
359        budget: DynamicMesh3dBudget,
360    ) -> Result<(usize, usize), DynamicMesh3dError> {
361        let counts = [
362            source.vertices().len(),
363            source.display_edges().len(),
364            source.texture_coordinates().len(),
365            source.vertex_colors().len(),
366            source.normals().len(),
367        ];
368        let capacities = [
369            self.vertices.capacity(),
370            self.edges.capacity(),
371            self.coordinates.capacity(),
372            self.colors.capacity(),
373            self.normals.capacity(),
374        ];
375        let strides = [
376            std::mem::size_of::<MeshVertexGpu>(),
377            std::mem::size_of::<MeshEdgeGpu>(),
378            std::mem::size_of::<MeshUvGpu>(),
379            std::mem::size_of::<MeshColorGpu>(),
380            std::mem::size_of::<MeshNormalGpu>(),
381        ];
382        let planned = std::array::from_fn::<_, 5, _>(|index| capacities[index].max(counts[index]));
383        let bytes = |values: [usize; 5]| -> Result<usize, DynamicMesh3dError> {
384            let mut total = 0usize;
385            for (count, stride) in values.into_iter().zip(strides) {
386                total = count
387                    .checked_mul(stride)
388                    .and_then(|bytes| total.checked_add(bytes))
389                    .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
390            }
391            Ok(total)
392        };
393        let final_bytes = bytes(planned)?;
394        let replacing = std::array::from_fn(|index| {
395            if counts[index] > capacities[index] {
396                counts[index]
397            } else {
398                0
399            }
400        });
401        let old_bytes = bytes(capacities)?;
402        let peak = checked_sum([old_bytes, bytes(replacing)?])?;
403        final_limit(
404            Mesh3dUploadBudgetResource::StagingBytes,
405            final_bytes,
406            budget.upload.max_staging_bytes(),
407        )?;
408        peak_limit(
409            DynamicMesh3dBudgetResource::PeakStagingBytes,
410            peak,
411            budget.peak_staging,
412        )?;
413        let vertices = reserve_conversion::<MeshVertexGpu>(capacities[0], counts[0])?;
414        let edges = reserve_conversion::<MeshEdgeGpu>(capacities[1], counts[1])?;
415        let coordinates = reserve_conversion::<MeshUvGpu>(capacities[2], counts[2])?;
416        let colors = reserve_conversion::<MeshColorGpu>(capacities[3], counts[3])?;
417        let normals = reserve_conversion::<MeshNormalGpu>(capacities[4], counts[4])?;
418        let actual = [
419            vertices.as_ref().map_or(capacities[0], Vec::capacity),
420            edges.as_ref().map_or(capacities[1], Vec::capacity),
421            coordinates.as_ref().map_or(capacities[2], Vec::capacity),
422            colors.as_ref().map_or(capacities[3], Vec::capacity),
423            normals.as_ref().map_or(capacities[4], Vec::capacity),
424        ];
425        let actual_new = [
426            vertices.as_ref().map_or(0, Vec::capacity),
427            edges.as_ref().map_or(0, Vec::capacity),
428            coordinates.as_ref().map_or(0, Vec::capacity),
429            colors.as_ref().map_or(0, Vec::capacity),
430            normals.as_ref().map_or(0, Vec::capacity),
431        ];
432        let peak = checked_sum([old_bytes, bytes(actual_new)?])?;
433        final_limit(
434            Mesh3dUploadBudgetResource::StagingBytes,
435            bytes(actual)?,
436            budget.upload.max_staging_bytes(),
437        )?;
438        peak_limit(
439            DynamicMesh3dBudgetResource::PeakStagingBytes,
440            peak,
441            budget.peak_staging,
442        )?;
443        let reallocations = usize::from(vertices.is_some())
444            + usize::from(edges.is_some())
445            + usize::from(coordinates.is_some())
446            + usize::from(colors.is_some())
447            + usize::from(normals.is_some());
448        if let Some(vertices) = vertices {
449            self.vertices = vertices;
450        }
451        if let Some(edges) = edges {
452            self.edges = edges;
453        }
454        if let Some(coordinates) = coordinates {
455            self.coordinates = coordinates;
456        }
457        if let Some(colors) = colors {
458            self.colors = colors;
459        }
460        if let Some(normals) = normals {
461            self.normals = normals;
462        }
463        self.normals.clear();
464        self.normals
465            .extend(source.normals().iter().map(MeshNormalGpu::from_source));
466        self.colors.clear();
467        self.colors
468            .extend(source.vertex_colors().iter().map(|color| MeshColorGpu {
469                color: color.to_array(),
470            }));
471        self.vertices.clear();
472        self.vertices
473            .extend(source.vertices().iter().map(|vertex| MeshVertexGpu {
474                position: [vertex.x(), vertex.y(), vertex.z()],
475            }));
476        self.edges.clear();
477        self.edges.extend(source.display_edges().iter().map(|edge| {
478            let start = source.vertices()[edge.start() as usize];
479            let end = source.vertices()[edge.end() as usize];
480            MeshEdgeGpu {
481                start: [start.x(), start.y(), start.z()],
482                end: [end.x(), end.y(), end.z()],
483            }
484        }));
485        self.coordinates.clear();
486        self.coordinates.extend(
487            source
488                .texture_coordinates()
489                .iter()
490                .map(|coordinate| MeshUvGpu {
491                    coordinate: [coordinate.u(), coordinate.v()],
492                }),
493        );
494        Ok((reallocations, peak))
495    }
496}
497
498fn reserve_conversion<T>(
499    capacity: usize,
500    count: usize,
501) -> Result<Option<Vec<T>>, Mesh3dResourceError> {
502    if count <= capacity {
503        return Ok(None);
504    }
505    let requested_bytes = count
506        .checked_mul(std::mem::size_of::<T>())
507        .and_then(|bytes| u64::try_from(bytes).ok())
508        .ok_or(Mesh3dResourceError::CapacityTooLarge)?;
509    let mut values = Vec::new();
510    values
511        .try_reserve_exact(count)
512        .map_err(|_| Mesh3dResourceError::HostAllocationFailed { requested_bytes })?;
513    Ok(Some(values))
514}