Skip to main content

sim_engine/renderer/mesh3d/validation/
mod.rs

1//! Surface rasterization policy and source-attributed numerical validation.
2
3use super::{
4    MAX_PORTABLE_SHADER_VALUE, Mesh3d, Mesh3dObjectError, Mesh3dRenderError, Object3dId, Vec3,
5    interval_products_f64, is_portable_shader_source, shader_clip_point_ranges,
6    validate_clip_classification,
7};
8
9mod bounds;
10
11#[cfg(test)]
12mod tests;
13
14pub(super) fn native_mesh_is_outside(
15    mesh: &Mesh3d,
16    model_rows: [[f32; 4]; 3],
17    camera_rows: [[f32; 4]; 4],
18) -> bool {
19    bounds::native_mesh_is_outside(mesh, model_rows, camera_rows)
20}
21
22pub(super) fn fog_transform_is_proven(
23    mesh: &Mesh3d,
24    model_rows: [[f32; 4]; 3],
25    depth_row: [f32; 4],
26) -> bool {
27    bounds::fog_transform_is_proven(mesh, model_rows, depth_row)
28}
29
30/// Selects the portability contract for filled 3D surfaces, not display edges.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum SurfaceRasterization3d {
34    /// Proves clip classification and projected orientation across the portable
35    /// shader arithmetic envelope, using canonical CPU clipping for crossings.
36    /// Ambiguous and edge-on triangles return a source-attributed error.
37    #[default]
38    StrictPortable,
39    /// Submits original indexed surfaces for native hardware clipping and
40    /// rasterization. Finite shader arithmetic is still validated, but grazing,
41    /// edge-on and camera-plane surfaces need no CPU topology proof.
42    ///
43    /// Coverage at numerical boundaries may differ across adapters. No uncertain
44    /// source triangles are dropped by the CPU. Hardware-clipped/zero-area
45    /// primitives may produce no fragments; preflight reports submissions, not
46    /// visibility, and does not claim CPU classification counts in this mode.
47    /// Mathematical display edges retain their independent strict validation.
48    Native,
49}
50
51/// Specific cause of failure for an original source surface triangle.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Mesh3dSurfaceError {
55    /// An active Lambert source normal loses a provably usable transformed direction.
56    NormalTransform,
57    /// Active fog camera-forward world-distance arithmetic leaves the finite envelope.
58    FogArithmetic,
59    /// Model/camera products or sums leave the finite portable shader envelope.
60    TransformArithmetic,
61    /// A vertex's side of a clipping plane cannot be proved consistently.
62    ClipPlaneClassification,
63    /// A clip intersection or its interpolated attributes cannot be proved safe.
64    ClipIntersection,
65    /// Rounded coincident endpoints cannot be proved to be the same vertex.
66    ClippedVertexIdentity,
67    /// The fixed clipping polygon capacity would be exceeded.
68    ClippedPolygonCapacity,
69    /// A nonempty clipped polygon has fewer than three proven vertices.
70    ClippedPolygonDegenerate,
71    /// A surviving vertex cannot be safely divided by its homogeneous W.
72    PerspectiveDivide,
73    /// A generated vertex cannot be proved inside the complete clip volume.
74    ClippedVertexOutside,
75    /// The projected signed area cannot be proved to have a nonzero sign.
76    ProjectedOrientation,
77}
78
79impl Mesh3dSurfaceError {
80    #[cfg(test)]
81    pub(super) fn legacy(self) -> Mesh3dRenderError {
82        match self {
83            Self::TransformArithmetic => Mesh3dRenderError::InvalidGeometryTransform,
84            _ => Mesh3dRenderError::UnportableSurfaceTopology,
85        }
86    }
87
88    pub(super) fn for_triangle(
89        self,
90        object_id: Object3dId,
91        triangle_index: usize,
92    ) -> Mesh3dRenderError {
93        Mesh3dRenderError::ObjectFailure {
94            object_id,
95            reason: Mesh3dObjectError::SurfaceTriangle {
96                triangle_index,
97                reason: self,
98            },
99        }
100    }
101}
102
103pub(super) fn validate_points_for_policy(
104    mesh: &Mesh3d,
105    model_rows: [[f32; 4]; 3],
106    camera_rows: [[f32; 4]; 4],
107    policy: SurfaceRasterization3d,
108    object_id: Object3dId,
109) -> Result<(), Mesh3dRenderError> {
110    if policy == SurfaceRasterization3d::Native
111        && bounds::native_transform_is_proven(mesh, model_rows, camera_rows)
112    {
113        return Ok(());
114    }
115    for (vertex_index, vertex) in mesh.vertices().iter().enumerate() {
116        let result = validate_point_for_policy(*vertex, model_rows, camera_rows, policy);
117        if let Err(reason) = result {
118            // Only failures search for a source owner; the ordinary path does
119            // not allocate an adjacency map or validate shared vertices twice.
120            return Err(Mesh3dRenderError::ObjectFailure {
121                object_id,
122                reason: source_point_error(mesh, vertex_index, reason),
123            });
124        }
125    }
126    Ok(())
127}
128
129fn source_point_error(
130    mesh: &Mesh3d,
131    vertex_index: usize,
132    reason: Mesh3dSurfaceError,
133) -> Mesh3dObjectError {
134    match mesh
135        .triangle_indices()
136        .iter()
137        .position(|index| *index as usize == vertex_index)
138    {
139        Some(index) => Mesh3dObjectError::SurfaceTriangle {
140            triangle_index: index / 3,
141            reason,
142        },
143        None => Mesh3dObjectError::Vertex {
144            vertex_index,
145            reason,
146        },
147    }
148}
149
150pub(super) fn validate_point_for_policy(
151    vertex: Vec3,
152    model_rows: [[f32; 4]; 3],
153    camera_rows: [[f32; 4]; 4],
154    policy: SurfaceRasterization3d,
155) -> Result<(), Mesh3dSurfaceError> {
156    let clip = shader_clip_point_ranges(vertex, model_rows, camera_rows)
157        .map_err(|_| Mesh3dSurfaceError::TransformArithmetic)?;
158    if policy == SurfaceRasterization3d::StrictPortable {
159        validate_clip_classification(clip)
160            .map_err(|_| Mesh3dSurfaceError::ClipPlaneClassification)?;
161    }
162    Ok(())
163}