Skip to main content

sim_engine/renderer/
dynamic_mesh.rs

1//! Mutable triangle-mesh creation, updates, recovery and drawing.
2
3use super::{
4    Arc, Camera2d, Color, Duration, DynamicGpu, Error, GeometryExtents, GeometryValidationCache,
5    GeometryValidationSource, Instant, PreparedDrawBatch, RenderReport, RenderStatus,
6    RendererFrameError, TessellationStats, Vec2, WgpuRenderer, buffer_capacity_fits,
7    create_dynamic_vertex_buffer, dynamic_mesh_bytes, dynamic_vertex_capacity,
8    dynamic_vertices_to_gpu, fmt, prepared_scene_belongs_to, replace_dynamic_mesh_resources,
9    restore_dynamic_mesh_resources, submit_pending_uploads, validate_dynamic_mesh_budget,
10    validate_dynamic_retained_capacity,
11};
12
13/// One world-space vertex in a dynamic triangle-list mesh.
14///
15/// Dynamic meshes use plain filled triangles. Positions are measured in world
16/// units, `depth` uses the active camera projection, and colors are linear RGBA.
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub struct DynamicVertex2d {
19    pub(super) world_position: Vec2,
20    pub(super) depth: f32,
21    pub(super) color: Color,
22}
23
24impl DynamicVertex2d {
25    /// Builds a finite dynamic vertex.
26    pub fn new(world_position: Vec2, depth: f32, color: Color) -> Result<Self, DynamicMeshError> {
27        if !world_position.is_finite() || !depth.is_finite() || !color.is_normalized() {
28            return Err(DynamicMeshError::InvalidVertex);
29        }
30        Ok(Self {
31            world_position,
32            depth,
33            color,
34        })
35    }
36
37    /// Returns the world-space triangle position.
38    pub fn world_position(self) -> Vec2 {
39        self.world_position
40    }
41
42    /// Returns pseudo-depth in caller-defined units.
43    pub fn depth(self) -> f32 {
44        self.depth
45    }
46
47    /// Returns the linear RGBA vertex color.
48    pub fn color(self) -> Color {
49        self.color
50    }
51}
52
53/// Validation or ownership failure while changing a dynamic mesh.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum DynamicMeshError {
56    /// Triangle-list vertex counts must be divisible by three.
57    InvalidVertexCount,
58    /// A position/depth is outside the portable shader envelope or a color is invalid.
59    InvalidVertex,
60    /// A partial update lies outside the mesh's current vertex range.
61    UpdateRangeOutOfBounds,
62    /// The mesh belongs to a different renderer and GPU device.
63    RendererMismatch,
64    /// The mesh capacity exceeds the current device's vertex-buffer limit.
65    CapacityTooLarge,
66    /// At least one complete triangle must fit in every configured limit.
67    InvalidBudget,
68    /// A bounded mesh operation exceeded a host-selected limit.
69    BudgetExceeded {
70        /// Work category that exceeded its ceiling.
71        resource: DynamicMeshBudgetResource,
72        /// Configured upper bound.
73        limit: usize,
74        /// Required work for the requested mesh state.
75        actual: usize,
76    },
77    /// CPU recovery storage could not be reserved without changing the mesh.
78    AllocationFailed {
79        /// Bytes requested by the failed reservation.
80        requested_bytes: usize,
81    },
82}
83
84impl fmt::Display for DynamicMeshError {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::InvalidVertexCount => write!(
88                formatter,
89                "dynamic mesh vertex count must be divisible by three"
90            ),
91            Self::InvalidVertex => write!(
92                formatter,
93                "dynamic mesh positions/depth must be portable and colors normalized"
94            ),
95            Self::UpdateRangeOutOfBounds => write!(
96                formatter,
97                "dynamic mesh update range is outside the current mesh"
98            ),
99            Self::RendererMismatch => {
100                write!(formatter, "dynamic mesh belongs to a different renderer")
101            }
102            Self::CapacityTooLarge => {
103                write!(
104                    formatter,
105                    "dynamic mesh exceeds the GPU vertex-buffer limit"
106                )
107            }
108            Self::InvalidBudget => write!(formatter, "dynamic mesh budget must fit one triangle"),
109            Self::BudgetExceeded {
110                resource,
111                limit,
112                actual,
113            } => write!(
114                formatter,
115                "dynamic mesh {resource:?} work {actual} exceeds limit {limit}"
116            ),
117            Self::AllocationFailed { requested_bytes } => write!(
118                formatter,
119                "could not reserve {requested_bytes} bytes for dynamic mesh recovery data"
120            ),
121        }
122    }
123}
124
125impl Error for DynamicMeshError {}
126
127/// Host-selected work category constrained by [`DynamicMeshBudget`].
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum DynamicMeshBudgetResource {
130    /// Triangle-list vertex count.
131    Vertices,
132    /// CPU bytes retained for exact recovery.
133    RetainedBytes,
134    /// GPU bytes uploaded by a full replacement.
135    UploadBytes,
136}
137
138/// Explicit retained and upload limits for caller-provided colored triangles.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct DynamicMeshBudget {
141    pub(super) max_vertices: usize,
142    pub(super) max_retained_bytes: usize,
143    pub(super) max_upload_bytes: usize,
144}
145
146impl DynamicMeshBudget {
147    /// Creates limits large enough for at least one complete triangle.
148    pub fn new(
149        max_vertices: usize,
150        max_retained_bytes: usize,
151        max_upload_bytes: usize,
152    ) -> Result<Self, DynamicMeshError> {
153        let triangle_bytes = 3 * std::mem::size_of::<DynamicGpu>();
154        if max_vertices < 3
155            || max_retained_bytes < triangle_bytes
156            || max_upload_bytes < triangle_bytes
157        {
158            return Err(DynamicMeshError::InvalidBudget);
159        }
160        Ok(Self {
161            max_vertices,
162            max_retained_bytes,
163            max_upload_bytes,
164        })
165    }
166
167    /// Returns the maximum retained triangle-list vertex count.
168    pub const fn max_vertices(self) -> usize {
169        self.max_vertices
170    }
171
172    /// Returns the maximum exact CPU recovery bytes.
173    pub const fn max_retained_bytes(self) -> usize {
174        self.max_retained_bytes
175    }
176
177    /// Returns the maximum bytes uploaded by one complete replacement.
178    pub const fn max_upload_bytes(self) -> usize {
179        self.max_upload_bytes
180    }
181}
182
183impl Default for DynamicMeshBudget {
184    fn default() -> Self {
185        Self {
186            max_vertices: 1_000_000,
187            max_retained_bytes: 64 * 1024 * 1024,
188            max_upload_bytes: 64 * 1024 * 1024,
189        }
190    }
191}
192
193/// Mutable GPU triangle-list geometry for high-frequency simulation visuals.
194///
195/// A mesh retains its CPU vertices for validation and recreates its GPU buffer
196/// only when a replacement exceeds its current capacity. Use
197/// [`WgpuRenderer::update_dynamic_mesh_range`] for in-place partial updates.
198/// Its bounded camera-validation cache is cleared by every successful mutation.
199pub struct DynamicMesh2d {
200    pub(super) renderer_identity: Arc<()>,
201    pub(super) vertex_buffer: Arc<wgpu::Buffer>,
202    pub(super) vertices: Vec<DynamicGpu>,
203    pub(super) vertex_capacity: usize,
204    pub(super) geometry_extents: GeometryExtents,
205    pub(super) geometry_validation_cache: GeometryValidationCache,
206    pub(super) budget: Option<DynamicMeshBudget>,
207}
208
209impl DynamicMesh2d {
210    /// Returns the number of triangle-list vertices currently stored.
211    pub fn vertex_count(&self) -> usize {
212        self.vertices.len()
213    }
214
215    /// Returns the number of vertices that fit without reallocating its GPU buffer.
216    pub fn vertex_capacity(&self) -> usize {
217        self.vertex_capacity
218    }
219
220    /// Returns retained CPU memory used for validation and future updates.
221    pub fn recovery_memory_bytes(&self) -> usize {
222        self.vertices
223            .capacity()
224            .saturating_mul(std::mem::size_of::<DynamicGpu>())
225    }
226
227    /// Returns explicit limits, or `None` for the compatibility constructor.
228    pub const fn budget(&self) -> Option<DynamicMeshBudget> {
229        self.budget
230    }
231}
232
233/// CPU-side outcome of one dynamic mesh update.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct DynamicMeshUpdateReport {
236    pub(super) vertex_count: usize,
237    pub(super) upload: Duration,
238    pub(super) reallocated: bool,
239}
240
241impl DynamicMeshUpdateReport {
242    /// Returns the current triangle-list vertex count after the update.
243    pub fn vertex_count(self) -> usize {
244        self.vertex_count
245    }
246
247    /// Returns CPU time spent validating, allocating when needed, and writing GPU data.
248    pub fn upload(self) -> Duration {
249        self.upload
250    }
251
252    /// Returns whether this update grew and replaced the mesh GPU buffer.
253    pub fn reallocated(self) -> bool {
254        self.reallocated
255    }
256}
257
258/// Failure while rendering a [`DynamicMesh2d`].
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum DynamicMeshRenderError {
261    /// The mesh belongs to another renderer and GPU device.
262    RendererMismatch,
263    /// The clear color is not normalized linear RGBA.
264    InvalidBackground,
265    /// Frame rendering failed after dynamic-mesh ownership validation.
266    Frame(RendererFrameError),
267}
268
269impl fmt::Display for DynamicMeshRenderError {
270    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
271        match self {
272            Self::RendererMismatch => {
273                write!(formatter, "dynamic mesh belongs to a different renderer")
274            }
275            Self::InvalidBackground => {
276                write!(formatter, "dynamic mesh background must be normalized")
277            }
278            Self::Frame(error) => write!(formatter, "dynamic mesh frame failed: {error}"),
279        }
280    }
281}
282
283impl Error for DynamicMeshRenderError {}
284
285impl WgpuRenderer {
286    /// Recreates a dynamic mesh on this renderer from its retained CPU vertices.
287    ///
288    /// Use this after recreating a renderer following device loss. The returned
289    /// mesh belongs to this renderer and preserves the source mesh's capacity so
290    /// subsequent updates retain the same allocation behavior.
291    pub fn restore_dynamic_mesh(
292        &self,
293        source: &DynamicMesh2d,
294    ) -> Result<DynamicMesh2d, DynamicMeshError> {
295        restore_dynamic_mesh_resources(
296            &self.device,
297            &self.queue,
298            Arc::clone(&self.renderer_identity),
299            source,
300        )
301    }
302
303    /// Creates mutable triangle-list geometry for a frequently changing visual.
304    ///
305    /// The vertex count must be divisible by three. The mesh is owned by this
306    /// renderer and may only be updated or drawn through it.
307    pub fn create_dynamic_mesh(
308        &self,
309        vertices: &[DynamicVertex2d],
310    ) -> Result<DynamicMesh2d, DynamicMeshError> {
311        self.create_dynamic_mesh_inner(vertices, None)
312    }
313
314    /// Creates bounded mutable colored triangles for composition in a frame.
315    ///
316    /// Validation and CPU reservation complete before any GPU allocation. The
317    /// retained budget is also enforced by every later full or partial update.
318    pub fn create_dynamic_mesh_with_budget(
319        &self,
320        vertices: &[DynamicVertex2d],
321        budget: DynamicMeshBudget,
322    ) -> Result<DynamicMesh2d, DynamicMeshError> {
323        self.create_dynamic_mesh_inner(vertices, Some(budget))
324    }
325
326    fn create_dynamic_mesh_inner(
327        &self,
328        vertices: &[DynamicVertex2d],
329        budget: Option<DynamicMeshBudget>,
330    ) -> Result<DynamicMesh2d, DynamicMeshError> {
331        if let Some(budget) = budget {
332            validate_dynamic_mesh_budget(budget, vertices.len())?;
333        }
334        let vertex_capacity = dynamic_vertex_capacity(vertices.len())
335            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
336            .ok_or(DynamicMeshError::CapacityTooLarge)?;
337        let vertices = dynamic_vertices_to_gpu(vertices)?;
338        if let Some(budget) = budget {
339            validate_dynamic_retained_capacity(budget, &vertices)?;
340        }
341        let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(&self.device, vertex_capacity));
342        if !vertices.is_empty() {
343            self.queue
344                .write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
345            submit_pending_uploads(&self.queue);
346        }
347        Ok(DynamicMesh2d {
348            renderer_identity: Arc::clone(&self.renderer_identity),
349            geometry_extents: GeometryExtents::from_dynamic_vertices(&vertices),
350            geometry_validation_cache: GeometryValidationCache::default(),
351            vertex_buffer,
352            vertices,
353            vertex_capacity,
354            budget,
355        })
356    }
357
358    /// Replaces all dynamic mesh vertices, growing GPU capacity only when needed.
359    pub fn update_dynamic_mesh(
360        &self,
361        mesh: &mut DynamicMesh2d,
362        vertices: &[DynamicVertex2d],
363    ) -> Result<(), DynamicMeshError> {
364        self.update_dynamic_mesh_with_metrics(mesh, vertices)
365            .map(|_| ())
366    }
367
368    /// Replaces all dynamic mesh vertices and returns CPU-side update metrics.
369    pub fn update_dynamic_mesh_with_metrics(
370        &self,
371        mesh: &mut DynamicMesh2d,
372        vertices: &[DynamicVertex2d],
373    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
374        self.validate_dynamic_mesh(mesh)?;
375        replace_dynamic_mesh_resources(&self.device, &self.queue, mesh, vertices)
376    }
377
378    /// Replaces a contiguous vertex range without reallocating the mesh buffer.
379    ///
380    /// The range must stay inside the current triangle list and its length must
381    /// preserve triangle alignment, so callers cannot create partial triangles.
382    pub fn update_dynamic_mesh_range(
383        &self,
384        mesh: &mut DynamicMesh2d,
385        first_vertex: usize,
386        vertices: &[DynamicVertex2d],
387    ) -> Result<(), DynamicMeshError> {
388        self.update_dynamic_mesh_range_with_metrics(mesh, first_vertex, vertices)
389            .map(|_| ())
390    }
391
392    /// Replaces a triangle-aligned range and returns CPU-side update metrics.
393    pub fn update_dynamic_mesh_range_with_metrics(
394        &self,
395        mesh: &mut DynamicMesh2d,
396        first_vertex: usize,
397        vertices: &[DynamicVertex2d],
398    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
399        let update_started_at = Instant::now();
400        self.validate_dynamic_mesh(mesh)?;
401        let end = first_vertex
402            .checked_add(vertices.len())
403            .ok_or(DynamicMeshError::UpdateRangeOutOfBounds)?;
404        if !first_vertex.is_multiple_of(3)
405            || !vertices.len().is_multiple_of(3)
406            || end > mesh.vertices.len()
407        {
408            return Err(DynamicMeshError::UpdateRangeOutOfBounds);
409        }
410        if let Some(budget) = mesh.budget {
411            validate_dynamic_mesh_budget(budget, mesh.vertices.len())?;
412            let upload_bytes = dynamic_mesh_bytes(vertices.len())?;
413            if upload_bytes > budget.max_upload_bytes {
414                return Err(DynamicMeshError::BudgetExceeded {
415                    resource: DynamicMeshBudgetResource::UploadBytes,
416                    limit: budget.max_upload_bytes,
417                    actual: upload_bytes,
418                });
419            }
420        }
421        let vertices = dynamic_vertices_to_gpu(vertices)?;
422        if !vertices.is_empty() {
423            let offset = (first_vertex * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress;
424            self.queue
425                .write_buffer(&mesh.vertex_buffer, offset, bytemuck::cast_slice(&vertices));
426            submit_pending_uploads(&self.queue);
427            mesh.vertices[first_vertex..end].copy_from_slice(&vertices);
428            mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&mesh.vertices);
429            mesh.geometry_validation_cache.clear();
430        }
431        Ok(DynamicMeshUpdateReport {
432            vertex_count: mesh.vertices.len(),
433            upload: update_started_at.elapsed(),
434            reallocated: false,
435        })
436    }
437
438    /// Draws dynamic triangle-list geometry with a normalized clear color.
439    ///
440    /// Every potentially visible triangle must remain fully inside the full
441    /// surface clip volume and have a portable projected orientation. A
442    /// hardware-clipped or ambiguous triangle returns
443    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
444    pub fn render_dynamic_mesh(
445        &mut self,
446        mesh: &DynamicMesh2d,
447        background: Color,
448        camera: &Camera2d,
449    ) -> Result<RenderStatus, DynamicMeshRenderError> {
450        self.render_dynamic_mesh_with_metrics(mesh, background, camera)
451            .map(RenderReport::status)
452    }
453
454    /// Draws dynamic triangle-list geometry and returns per-frame CPU metrics.
455    ///
456    /// Full-surface clip-volume crossing and association-dependent projected
457    /// topology are rejected as
458    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
459    pub fn render_dynamic_mesh_with_metrics(
460        &mut self,
461        mesh: &DynamicMesh2d,
462        background: Color,
463        camera: &Camera2d,
464    ) -> Result<RenderReport, DynamicMeshRenderError> {
465        self.validate_dynamic_mesh(mesh)
466            .map_err(|_| DynamicMeshRenderError::RendererMismatch)?;
467        if !background.is_normalized() {
468            return Err(DynamicMeshRenderError::InvalidBackground);
469        }
470        let draw_batches = (!mesh.vertices.is_empty()).then_some(PreparedDrawBatch {
471            vertex_range: 0..mesh.vertices.len() as u32,
472            screen_clip: None,
473        });
474        self.draw_geometry(
475            background,
476            &mesh.vertex_buffer,
477            mesh.vertices.len(),
478            mesh.geometry_extents,
479            GeometryValidationSource::Dynamic(&mesh.vertices),
480            Some(&mesh.geometry_validation_cache),
481            draw_batches.as_slice(),
482            *camera,
483            Duration::ZERO,
484            Duration::ZERO,
485            false,
486            true,
487            true,
488            None,
489            TessellationStats::default(),
490            Instant::now(),
491            None,
492        )
493        .map_err(DynamicMeshRenderError::Frame)
494    }
495
496    pub(super) fn validate_dynamic_mesh(
497        &self,
498        mesh: &DynamicMesh2d,
499    ) -> Result<(), DynamicMeshError> {
500        prepared_scene_belongs_to(&self.renderer_identity, &mesh.renderer_identity)
501            .then_some(())
502            .ok_or(DynamicMeshError::RendererMismatch)
503    }
504}