Skip to main content

sim_engine/renderer/mesh3d/
report.rs

1//! Public retained 3D errors and submission/recovery diagnostics.
2
3use super::{
4    Duration, Error, GpuTimingId, Mesh3dPreflightReport, Mesh3dSurfaceError,
5    Mesh3dUploadBudgetResource, Object3dId, RenderTargetError, Texture3dError, fmt,
6};
7
8/// Resource creation or ownership failure for retained 3D rendering.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Mesh3dResourceError {
11    /// Texture creation, restoration or material validation failed.
12    Texture(Texture3dError),
13    /// A retained UV is subnormal and outside the portable shader envelope.
14    NonPortableTextureCoordinate,
15    /// Explicit mesh upload limits must be nonzero.
16    InvalidBudget,
17    /// The replaced resource belongs to another logical renderer generation.
18    RendererMismatch,
19    /// Upload limits rejected bytes before caller-scale allocation.
20    BudgetExceeded {
21        /// Rejected byte category.
22        resource: Mesh3dUploadBudgetResource,
23        /// Configured maximum.
24        limit: usize,
25        /// Required bytes.
26        actual: usize,
27    },
28    /// Vertex, index, or edge data exceeds the active device's buffer-size limit.
29    CapacityTooLarge,
30    /// At least one retained model-space vertex is outside the portable shader envelope.
31    NonPortableVertex,
32    /// Host staging memory could not be reserved after capacity preflight.
33    HostAllocationFailed {
34        /// Bytes requested for the rejected staging buffer.
35        requested_bytes: u64,
36    },
37    /// Color/depth target creation failed.
38    Target(RenderTargetError),
39    /// Physical texture and logical viewport aspect ratios differ.
40    InvalidViewportAspect,
41}
42
43impl fmt::Display for Mesh3dResourceError {
44    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::Texture(error) => write!(formatter, "{error}"),
47            Self::NonPortableTextureCoordinate => write!(
48                formatter,
49                "3D texture coordinate is outside the portable shader envelope"
50            ),
51            Self::InvalidBudget => write!(formatter, "3D mesh upload limits must be nonzero"),
52            Self::RendererMismatch => {
53                write!(formatter, "3D mesh belongs to another renderer generation")
54            }
55            Self::BudgetExceeded {
56                resource,
57                limit,
58                actual,
59            } => write!(
60                formatter,
61                "3D mesh {resource:?} budget exceeded: {actual} > {limit}"
62            ),
63            Self::CapacityTooLarge => write!(formatter, "3D mesh exceeds GPU buffer limits"),
64            Self::NonPortableVertex => write!(
65                formatter,
66                "3D mesh contains a vertex outside the portable shader envelope"
67            ),
68            Self::HostAllocationFailed { requested_bytes } => write!(
69                formatter,
70                "3D mesh could not reserve a {requested_bytes}-byte host staging buffer"
71            ),
72            Self::Target(error) => write!(formatter, "3D target creation failed: {error}"),
73            Self::InvalidViewportAspect => write!(
74                formatter,
75                "3D target texture and logical viewport must have one aspect ratio"
76            ),
77        }
78    }
79}
80
81impl Error for Mesh3dResourceError {}
82
83/// Failure while encoding a depth-tested 3D scene.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum Mesh3dRenderError {
86    /// Transient Blend ordering capacity exceeded its explicit byte ceiling.
87    SortingBudgetExceeded {
88        /// Configured sorting-array byte limit.
89        limit: usize,
90        /// Required or actually reserved bytes.
91        actual: usize,
92    },
93    /// A mesh or target belongs to another renderer/device identity.
94    RendererMismatch,
95    /// Model/camera inputs or their arithmetic leave the portable GPU envelope.
96    InvalidGeometryTransform,
97    /// A surface triangle has clipping topology or a projected orientation
98    /// that is not stable across portable shader arithmetic.
99    UnportableSurfaceTopology,
100    /// The visible per-frame object buffers exceed a GPU or host capacity.
101    InstanceCapacityTooLarge,
102    /// Camera projection aspect does not match the target logical viewport.
103    CameraTargetAspectMismatch,
104    /// Edge clipping, projection, or style arithmetic is not portable for this target.
105    InvalidEdgeProjection,
106    /// A visible object's transform, surface or edge proof failed. The stable
107    /// handle identifies that exact object even when several share one mesh.
108    ObjectFailure {
109        /// Complete scene-provenance-bearing object handle.
110        object_id: Object3dId,
111        /// Source-context or object-level numerical validation failure.
112        reason: Mesh3dObjectError,
113    },
114    /// Generated clipping topology exceeds a caller budget or device capacity.
115    GeneratedGeometryCapacityTooLarge,
116    /// Exact retained plus generated surface submissions exceed the caller limit.
117    SurfaceTriangleBudgetExceeded {
118        /// Configured maximum surface submissions for this frame.
119        limit: usize,
120        /// Submitted count reached by authoritative preflight before rejection.
121        actual: usize,
122    },
123}
124
125/// Instance-local numerical rejection category from authoritative 3D preflight.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum Mesh3dObjectError {
128    /// Model/camera arithmetic cannot be represented portably.
129    InvalidGeometryTransform,
130    /// Clipped surface topology or projected orientation remains ambiguous.
131    UnportableSurfaceTopology,
132    /// Display-edge clipping or extrusion cannot be represented portably.
133    InvalidEdgeProjection,
134    /// A source surface triangle failed authoritative validation. The index is
135    /// zero-based in the source mesh, not in a generated clipping fan.
136    SurfaceTriangle {
137        /// Original index into `Mesh3d::triangle_indices().chunks_exact(3)`.
138        triangle_index: usize,
139        /// Specific arithmetic or topology proof that failed.
140        reason: Mesh3dSurfaceError,
141    },
142    /// A source vertex not referenced by any surface triangle failed validation.
143    Vertex {
144        /// Zero-based position in the source mesh vertex array.
145        vertex_index: usize,
146        /// Specific arithmetic or clip-classification failure.
147        reason: Mesh3dSurfaceError,
148    },
149}
150
151impl Mesh3dRenderError {
152    pub(super) fn for_object(self, object_id: Object3dId) -> Self {
153        let reason = match self {
154            Self::InvalidGeometryTransform => Mesh3dObjectError::InvalidGeometryTransform,
155            Self::UnportableSurfaceTopology => Mesh3dObjectError::UnportableSurfaceTopology,
156            Self::InvalidEdgeProjection => Mesh3dObjectError::InvalidEdgeProjection,
157            _ => return self,
158        };
159        Self::ObjectFailure { object_id, reason }
160    }
161
162    /// Returns an offending object when the failure is uniquely instance-local.
163    /// Ownership, camera/target mismatch and aggregate capacity errors return
164    /// `None`; they must not be attributed to an arbitrary visible object.
165    pub const fn object_id(self) -> Option<Object3dId> {
166        match self {
167            Self::ObjectFailure { object_id, .. } => Some(object_id),
168            _ => None,
169        }
170    }
171
172    /// Returns the original source triangle index for a surface-local failure.
173    /// Unused-vertex, edge, scene capacity and resource ownership failures have
174    /// no source triangle and return `None`.
175    pub const fn source_triangle_index(self) -> Option<usize> {
176        match self {
177            Self::ObjectFailure {
178                reason: Mesh3dObjectError::SurfaceTriangle { triangle_index, .. },
179                ..
180            } => Some(triangle_index),
181            _ => None,
182        }
183    }
184
185    /// Returns the source vertex index for failures without a surface triangle.
186    /// A referenced vertex is attributed to its first source triangle instead.
187    pub const fn source_vertex_index(self) -> Option<usize> {
188        match self {
189            Self::ObjectFailure {
190                reason: Mesh3dObjectError::Vertex { vertex_index, .. },
191                ..
192            } => Some(vertex_index),
193            _ => None,
194        }
195    }
196
197    /// Returns the specific source-surface or vertex rejection reason, when available.
198    pub const fn surface_reason(self) -> Option<Mesh3dSurfaceError> {
199        match self {
200            Self::ObjectFailure {
201                reason:
202                    Mesh3dObjectError::SurfaceTriangle { reason, .. }
203                    | Mesh3dObjectError::Vertex { reason, .. },
204                ..
205            } => Some(reason),
206            _ => None,
207        }
208    }
209}
210
211impl fmt::Display for Mesh3dRenderError {
212    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
213        match self {
214            Self::SortingBudgetExceeded { limit, actual } => write!(
215                formatter,
216                "3D sorting storage {actual} exceeds {limit} bytes"
217            ),
218            Self::RendererMismatch => {
219                write!(formatter, "3D scene resource belongs to another renderer")
220            }
221            Self::InvalidGeometryTransform => {
222                write!(
223                    formatter,
224                    "3D transform is outside the portable GPU geometry envelope"
225                )
226            }
227            Self::UnportableSurfaceTopology => write!(
228                formatter,
229                "3D surface clipping or projected triangle topology is outside the portable GPU envelope"
230            ),
231            Self::InstanceCapacityTooLarge => write!(
232                formatter,
233                "visible 3D objects exceed per-frame GPU or host buffer capacity"
234            ),
235            Self::CameraTargetAspectMismatch => write!(
236                formatter,
237                "3D camera aspect does not match the target logical viewport"
238            ),
239            Self::InvalidEdgeProjection => write!(
240                formatter,
241                "3D edge clipping or screen-space arithmetic is outside the portable GPU envelope"
242            ),
243            Self::ObjectFailure { object_id, reason } => write!(
244                formatter,
245                "3D object {} failed preflight: {reason:?}",
246                object_id.get()
247            ),
248            Self::GeneratedGeometryCapacityTooLarge => write!(
249                formatter,
250                "generated 3D surface topology exceeds frame or device capacity"
251            ),
252            Self::SurfaceTriangleBudgetExceeded { limit, actual } => write!(
253                formatter,
254                "3D surface submissions {actual} exceed frame triangle limit {limit}"
255            ),
256        }
257    }
258}
259
260impl Error for Mesh3dRenderError {}
261
262/// CPU-side result of one depth-tested offscreen 3D draw.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct Mesh3dRenderReport {
265    pub(super) object_count: usize,
266    pub(super) triangle_count: usize,
267    pub(super) edge_count: usize,
268    pub(super) render_pass_count: usize,
269    pub(super) draw_call_count: usize,
270    pub(super) upload: Duration,
271    pub(super) preflight_duration: Duration,
272    pub(super) staging_upload_duration: Duration,
273    pub(super) encode_submit: Duration,
274    pub(super) preflight: Mesh3dPreflightReport,
275    pub(super) gpu_timing_id: Option<GpuTimingId>,
276    pub(super) uploaded_bytes: usize,
277    pub(super) upload_calls: usize,
278    pub(super) buffer_allocation_count: usize,
279    pub(super) retained_frame_cpu_bytes: usize,
280    pub(super) retained_frame_gpu_bytes: usize,
281    pub(super) staging_capacity_bytes: usize,
282    pub(super) peak_frame_cpu_bytes: usize,
283    pub(super) peak_frame_gpu_bytes: usize,
284}
285
286impl Mesh3dRenderReport {
287    /// Returns exact clipping/generated-work counts from authoritative preflight.
288    pub const fn preflight(self) -> Mesh3dPreflightReport {
289        self.preflight
290    }
291    /// Returns independently transformed visible objects submitted for drawing.
292    ///
293    /// Outside objects count unless optional Native surface culling proves and
294    /// omits them. See `preflight()` for separate culled-object and CPU clipping
295    /// counts. This is not a visible-fragment or host-visibility count.
296    pub const fn object_count(self) -> usize {
297        self.object_count
298    }
299
300    /// Returns indexed and generated triangles submitted across every object.
301    pub const fn triangle_count(self) -> usize {
302        self.triangle_count
303    }
304
305    /// Returns explicit mathematical edges submitted for depth classification.
306    pub const fn edge_count(self) -> usize {
307        self.edge_count
308    }
309
310    /// Returns GPU render passes encoded for the retained scene.
311    ///
312    /// A successful draw always encodes one pass because clearing the color
313    /// and depth attachments is observable even when the scene is empty.
314    pub const fn render_pass_count(self) -> usize {
315        self.render_pass_count
316    }
317
318    /// Returns surface, hidden-edge, and visible-edge draw calls actually
319    /// encoded for the retained scene.
320    pub const fn draw_call_count(self) -> usize {
321        self.draw_call_count
322    }
323
324    /// Returns CPU time spent validating, staging, growing reusable buffers,
325    /// and enqueuing camera/instance uploads.
326    pub const fn upload(self) -> Duration {
327        self.upload
328    }
329
330    /// CPU time in authoritative source validation, clipping and draw ordering.
331    pub const fn preflight_duration(self) -> Duration {
332        self.preflight_duration
333    }
334
335    /// CPU time after preflight spent preparing/growing staging and GPU buffers
336    /// and enqueueing writes. Together with preflight this forms `upload()`;
337    /// none of these CPU measurements represents GPU execution time.
338    pub const fn staging_upload_duration(self) -> Duration {
339        self.staging_upload_duration
340    }
341
342    /// Correlation key for optional asynchronous GPU pass timing. `None` means
343    /// disabled/unavailable timing or a full ring, not a zero-duration pass.
344    pub const fn gpu_timing_id(self) -> Option<GpuTimingId> {
345        self.gpu_timing_id
346    }
347
348    /// Actual camera, instance, edge-uniform and generated-stream bytes written
349    /// for this draw. Retained topology/texture updates and diagnostic timestamp
350    /// resolution/readback are separate operations and are excluded.
351    /// Exact unchanged camera/instance/edge bytes are not rewritten. A zero
352    /// count still performs full preflight, target clearing and submission.
353    pub const fn uploaded_bytes(self) -> usize {
354        self.uploaded_bytes
355    }
356
357    /// Number of nonempty queue buffer writes corresponding to `uploaded_bytes`.
358    pub const fn upload_calls(self) -> usize {
359        self.upload_calls
360    }
361
362    /// Reusable frame GPU buffers newly allocated by this draw. Excludes renderer
363    /// initialization, immutable scene resources, bind groups and driver internals.
364    pub const fn buffer_allocation_count(self) -> usize {
365        self.buffer_allocation_count
366    }
367
368    /// Retained CPU instance, edge-uniform, object, generated-stream and sorting
369    /// array capacity after the draw, including idle high-water storage. Excludes
370    /// scene sources, dynamic-update scratch and backend memory.
371    pub const fn retained_frame_cpu_bytes(self) -> usize {
372        self.retained_frame_cpu_bytes
373    }
374
375    /// Nominal reusable camera/instance/edge/generated GPU buffer bytes after this
376    /// draw. Render targets, scene resources and timestamp diagnostics are excluded.
377    pub const fn retained_frame_gpu_bytes(self) -> usize {
378        self.retained_frame_gpu_bytes
379    }
380
381    /// Live CPU frame-array capacities during encoding. All arrays are reusable,
382    /// so this equals `retained_frame_cpu_bytes` after a successful draw.
383    /// Fixed-size numerical proof stack storage is not included.
384    pub const fn staging_capacity_bytes(self) -> usize {
385        self.staging_capacity_bytes
386    }
387
388    /// Conservative upper bound on old/new frame-array capacity during preparation.
389    /// Reused arrays count once; capacity changes count both old and new storage,
390    /// even if the allocator could grow in place. This is not measured process RSS.
391    /// Excludes caller data, fixed-size numerical proof stack storage, backend
392    /// allocations and allocator metadata.
393    pub const fn peak_frame_cpu_bytes(self) -> usize {
394        self.peak_frame_cpu_bytes
395    }
396
397    /// Old reusable GPU buffers plus newly allocated replacements for this draw;
398    /// driver retirement/in-flight allocations are not inferred from this count.
399    pub const fn peak_frame_gpu_bytes(self) -> usize {
400        self.peak_frame_gpu_bytes
401    }
402
403    /// Returns CPU time spent encoding and submitting the pass.
404    pub const fn encode_submit(self) -> Duration {
405        self.encode_submit
406    }
407}
408
409/// Result of atomically migrating a retained 3D scene to the active renderer device.
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub struct Scene3dRestoreReport {
412    pub(super) object_count: usize,
413    pub(super) migrated_object_count: usize,
414    pub(super) restored_mesh_count: usize,
415    pub(super) restored_gpu_bytes: usize,
416    pub(super) restored_texture_count: usize,
417    pub(super) restored_texture_bytes: usize,
418}
419
420impl Scene3dRestoreReport {
421    /// Returns distinct shared textures recreated on the active device.
422    pub const fn restored_texture_count(self) -> usize {
423        self.restored_texture_count
424    }
425    /// Returns nominal texel bytes recreated across distinct shared textures.
426    pub const fn restored_texture_bytes(self) -> usize {
427        self.restored_texture_bytes
428    }
429    /// Returns all scene objects whose stable IDs and visual state were preserved.
430    pub const fn object_count(self) -> usize {
431        self.object_count
432    }
433
434    /// Returns objects whose stale mesh reference was replaced in this call.
435    pub const fn migrated_object_count(self) -> usize {
436        self.migrated_object_count
437    }
438
439    /// Returns distinct retained mesh resources recreated on the active device.
440    pub const fn restored_mesh_count(self) -> usize {
441        self.restored_mesh_count
442    }
443
444    /// Returns total GPU bytes represented by the recreated distinct meshes.
445    pub const fn restored_gpu_bytes(self) -> usize {
446        self.restored_gpu_bytes
447    }
448}