ifc_lite_geometry/mesh_check/
closure.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Mesh-closure verdicts. Each one is a named [`EdgeLedger`] query; the vertex
6//! key and the degenerate rule stay the verdict's own.
7
8use super::hairline::{hairline_closed, Unmatched};
9use super::ledger::{Degenerate, EdgeLedger, VertexKey};
10use crate::mesh::Mesh;
11
12/// The 0.1 mm grid every directed closure verdict snaps to.
13const CLOSURE_GRID: VertexKey = VertexKey::GridDiv(1.0e-4);
14
15/// [`CLOSURE_GRID`]'s 0.1 mm pitch expressed in a caller unit, where
16/// `length_unit_scale` is metres per caller unit (`0.001` for millimetres).
17/// `1.0`, and any scale that is not a finite positive number, is the metre
18/// grid itself, bit for bit.
19fn closure_grid_in_units(length_unit_scale: f64) -> VertexKey {
20    if length_unit_scale.is_finite() && length_unit_scale > 0.0 && length_unit_scale != 1.0 {
21        VertexKey::GridDiv(1.0e-4 / length_unit_scale)
22    } else {
23        CLOSURE_GRID
24    }
25}
26
27/// Cached result of the shared 0.1 mm directed-edge walk.
28///
29/// Strict callers read the directed verdict without running the hairline
30/// matcher. Emit callers first accept strict closure and only then evaluate
31/// the bounded T-junction tolerance from the same edge counts (#4796).
32pub struct ClosureVerdict {
33    has_edges: bool,
34    bad: Vec<Unmatched>,
35}
36
37impl ClosureVerdict {
38    pub fn for_mesh(mesh: &Mesh) -> Self {
39        Self::for_mesh_in_units(mesh, 1.0)
40    }
41
42    /// The same walk with the 0.1 mm grid (and so the hairline matcher's
43    /// grid-unit slack) measured in the mesh's own length unit. A mesh still
44    /// in millimetre file units read on the metre grid is audited at 0.1 µm,
45    /// a thousand times finer than the tolerance this verdict documents (#7982).
46    pub fn for_mesh_in_units(mesh: &Mesh, length_unit_scale: f64) -> Self {
47        let grid = closure_grid_in_units(length_unit_scale);
48        let ledger = EdgeLedger::build(mesh, grid, Degenerate::SkipTriangle);
49        Self { has_edges: !ledger.is_empty(), bad: ledger.unbalanced().collect() }
50    }
51
52    pub fn is_directed_closed(&self) -> bool {
53        self.has_edges && self.bad.is_empty()
54    }
55
56    pub fn closed_enough_to_emit(&self) -> bool {
57        self.has_edges && (self.bad.is_empty() || hairline_closed(&self.bad))
58    }
59}
60
61/// DIRECTED quantized closed-surface audit (0.1 mm grid): every directed edge
62/// must be cancelled by its reverse. Strictly stronger than the undirected
63/// 2-manifold check: it catches inconsistent winding and doubled coincident
64/// surfaces (two triangles sharing an edge in the SAME direction), not just
65/// cracks. Triangles that collapse to a degenerate key on the grid are skipped.
66/// An empty mesh is not closed.
67pub fn directed_closed(mesh: &Mesh) -> bool {
68    let ledger = EdgeLedger::build(mesh, CLOSURE_GRID, Degenerate::SkipTriangle);
69    !ledger.is_empty() && ledger.directed_closed()
70}
71#[allow(dead_code, reason = "Shared test oracle alias")]
72/// Closed-surface audit with a HAIRLINE tolerance: the surface passes when
73/// every unpaired directed edge (0.1 mm grid) is collinearly COVERED by
74/// unpaired edges of the opposite net sign, the signature of two adjacent faces
75/// subdividing a shared boundary line differently (a T-junction chain, an
76/// invisible sub-grid gap), NOT of a missing surface. A genuine hole leaves a
77/// boundary loop whose edges have nothing opposite along them and fails. The
78/// exact kernel's own output is routinely NOT even undirected-watertight on
79/// these hosts, so this gate is still far stricter than the status quo.
80pub fn closed_or_hairline(mesh: &Mesh) -> bool {
81    ClosureVerdict::for_mesh(mesh).closed_enough_to_emit()
82}
83
84/// Named emit contract for callers that tolerate bounded T-junction hairlines.
85pub fn closed_enough_to_emit(mesh: &Mesh) -> bool {
86    ClosureVerdict::for_mesh(mesh).closed_enough_to_emit()
87}
88
89/// Per-undirected-edge MULTIPLICITY defects, the class the signed predicates
90/// above are structurally blind to.
91///
92/// Those predicates tally `+1` forward and `-1` reverse and pass when
93/// everything nets to zero. Cancellation is what makes a hairline T-junction
94/// chain forgivable, but it also erases multiplicity: an edge used by FOUR
95/// triangles, two each way, nets to zero and reads as closed. That is a
96/// doubled coincident surface, not a solid boundary.
97///
98/// * `over_used`: an undirected edge with MORE than two triangle uses
99///   (non-manifold: a fin, a doubled skin, or self-intersecting output).
100/// * `same_direction`: an undirected edge with exactly two uses running the
101///   SAME way round (inconsistent winding: one neighbour is flipped).
102///
103/// An edge used ONCE is deliberately NOT a defect here: that is an open
104/// boundary, which the closure predicates already measure and which
105/// T-junction tessellation trips constantly. Keeping it out is what lets a
106/// caller gate on this without inheriting that class's false-positive rate.
107#[cfg_attr(not(any(test, feature = "csg_manifold_gate", feature = "test-support")), allow(dead_code))]
108#[derive(Debug, Default, PartialEq, Eq)]
109pub struct EdgeMultiplicityDefects {
110    /// Undirected edges used by more than two triangles.
111    pub over_used: usize,
112    /// Undirected edges used exactly twice, both uses running the same way.
113    pub same_direction: usize,
114}
115
116#[cfg_attr(not(any(test, feature = "csg_manifold_gate", feature = "test-support")), allow(dead_code))]
117impl EdgeMultiplicityDefects {
118    /// True when the mesh carries neither defect.
119    pub fn is_clean(&self) -> bool {
120        self.over_used == 0 && self.same_direction == 0
121    }
122}
123
124/// Count the [`EdgeMultiplicityDefects`] of `mesh`, keyed EXACTLY.
125///
126/// The closure verdicts snap vertices to a 0.1 mm grid, which is right for
127/// them (two corners a hair apart should close) and wrong here: snapping merges
128/// two distinct vertices closer than a cell into one key, and the moment two
129/// distinct edges collapse onto one key their uses ADD, so two manifold
130/// surfaces 0.03 mm apart would report a four-use edge that exists in neither.
131/// For a REJECTION predicate that errs toward throwing away geometry that was
132/// never wrong. So the keys are the vertex coordinates bit for bit, with `-0.0`
133/// folded to `0.0` (one point). The cost is a miss, not a false positive: a
134/// non-manifold edge whose endpoints differ in the last bit reads as two edges.
135/// The kernel interns coincident corners, so a real shared edge in its output
136/// is bit-identical at both ends.
137///
138/// Non-finite coordinates cannot reach here (every caller runs `validate_mesh`
139/// first), so no NaN key can split a vertex from itself.
140#[cfg_attr(not(any(test, feature = "csg_manifold_gate", feature = "test-support")), allow(dead_code))]
141pub fn edge_multiplicity_defects(mesh: &Mesh) -> EdgeMultiplicityDefects {
142    EdgeLedger::build(mesh, VertexKey::BitsZeroFolded, Degenerate::SkipTriangle).multiplicity_defects()
143}
144
145/// Closed-surface check on exact f32 bit coords: every directed edge paired and
146/// no degenerate edge. The #2176 lesson: only per-component-watertight solid
147/// cutters may join a batched group; an open component poisons the whole
148/// group's ray parity (batch admission).
149pub fn directed_closed_exact(mesh: &Mesh) -> bool {
150    // `indices` non-empty, not "ledger non-empty": a lone partial triangle has
151    // no edges and has always passed.
152    let ledger = EdgeLedger::build(mesh, VertexKey::Bits, Degenerate::Reject);
153    !mesh.indices.is_empty() && ledger.directed_closed()
154}
155
156/// Number of 0.1 mm-welded undirected edges whose triangle multiplicity is not
157/// two; `usize::MAX` when no triangle survives the grid.
158pub fn undirected_defect_count(mesh: &Mesh) -> usize {
159    let ledger = EdgeLedger::build(mesh, CLOSURE_GRID, Degenerate::SkipTriangle);
160    if ledger.is_empty() {
161        return usize::MAX;
162    }
163    ledger.undirected_defects()
164}
165
166/// Every undirected edge is used exactly once each way on a grid of `per_unit`
167/// cells per world unit, collapsed triangles skipped. The strict directed-pair
168/// rule (#3397), not just a zero net balance (which a 2-forward/2-reverse seam
169/// or a duplicated sheet also satisfies). An empty mesh does not pass.
170pub fn strictly_paired_at(mesh: &Mesh, per_unit: f64) -> bool {
171    let ledger = EdgeLedger::build(mesh, VertexKey::GridMul(per_unit), Degenerate::SkipTriangle);
172    !ledger.is_empty() && ledger.strictly_paired()
173}
174
175/// The documented definition of "watertight" for new code and tests: vertices
176/// on the 0.1 mm grid, collapsed triangles skipped, every edge used exactly
177/// once each way, and at least one edge. Existing gates keep their own keys
178/// and rules (see [`super`]); this is the one to reach for when writing a new
179/// check.
180#[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
181pub fn is_watertight(mesh: &Mesh) -> bool {
182    let ledger = EdgeLedger::build(mesh, CLOSURE_GRID, Degenerate::SkipTriangle);
183    !ledger.is_empty() && ledger.strictly_paired()
184}