Skip to main content

sim_engine/renderer/
mesh3d_validation.rs

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