ifc_lite_geometry/mesh_check/
ledger.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//! The edge ledger: one hash walk over a triangle soup that every closure,
6//! pairing and multiplicity question is answered from.
7//!
8//! Each undirected edge `{a, b}` owns one slot `(fwd, rev)`: the number of
9//! triangle uses running `lo -> hi` and `hi -> lo`, where `lo < hi` in the key
10//! order. Every walk this crate used to hand-roll is a query on that pair:
11//!
12//! | Question | Query |
13//! |---|---|
14//! | signed directed tally of `(a, b)` | `fwd - rev` ([`EdgeLedger::net`]) |
15//! | undirected use count | `fwd + rev` ([`EdgeLedger::undirected_defects`]) |
16//! | strictly paired (one use each way) | `(1, 1)` ([`EdgeLedger::strictly_paired`]) |
17//!
18//! The vertex key and the degenerate-triangle rule are the caller's choice and
19//! stay the caller's: [`VertexKey`] and [`Degenerate`] name the spellings the
20//! gates already used. The ledger never unifies them (two quantiser spellings
21//! disagree at `.5` ties, and that is tolerance work, not refactoring).
22
23use super::closure::EdgeMultiplicityDefects;
24use crate::mesh::Mesh;
25use rustc_hash::FxHashMap;
26
27/// A quantised or bit-exact vertex identity.
28pub type Key3 = [i64; 3];
29
30/// How a vertex becomes a hash key.
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub enum VertexKey {
33    /// The raw `f32` bits of the position. `-0.0` and `+0.0` are two points.
34    Bits,
35    /// The raw `f32` bits with `-0.0` folded to `+0.0`.
36    BitsZeroFolded,
37    /// `(v as f64 / q).round() as i64`: a grid of pitch `q` (world units).
38    GridDiv(f64),
39    /// `(v as f64 * k).round() as i64`: a grid of `k` cells per unit.
40    GridMul(f64),
41    /// The vertex index itself, for a mesh the caller already welded.
42    Index,
43}
44
45#[inline]
46fn bits(p: [f32; 3]) -> Key3 {
47    p.map(|c| i64::from(c.to_bits()))
48}
49
50#[inline]
51fn bits_zero_folded(p: [f32; 3]) -> Key3 {
52    p.map(|c| i64::from((if c == 0.0 { 0.0f32 } else { c }).to_bits()))
53}
54
55#[inline]
56fn grid_div(p: [f32; 3], q: f64) -> Key3 {
57    p.map(|c| (f64::from(c) / q).round() as i64)
58}
59
60#[inline]
61fn grid_mul(p: [f32; 3], k: f64) -> Key3 {
62    p.map(|c| (f64::from(c) * k).round() as i64)
63}
64
65impl VertexKey {
66    /// The key of position `p`, or `None` for [`VertexKey::Index`], which has
67    /// no meaning without a vertex index.
68    #[inline]
69    pub fn point(self, p: [f32; 3]) -> Option<Key3> {
70        match self {
71            Self::Bits => Some(bits(p)),
72            Self::BitsZeroFolded => Some(bits_zero_folded(p)),
73            Self::GridDiv(q) => Some(grid_div(p, q)),
74            Self::GridMul(k) => Some(grid_mul(p, k)),
75            Self::Index => None,
76        }
77    }
78}
79
80/// What the walk does with a triangle whose corners collapse onto one key.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Degenerate {
83    /// Ignore the whole triangle (it bounds no area).
84    SkipTriangle,
85    /// Ignore only the zero-length edge; the other two edges still count.
86    SkipEdge,
87    /// Stop: the ledger is [`rejected`](EdgeLedger::rejected) and every
88    /// all-edges predicate on it is `false`.
89    Reject,
90}
91
92/// Per-undirected-edge directed use counts of a triangle soup.
93pub struct EdgeLedger {
94    /// `(lo, hi) -> (uses lo->hi, uses hi->lo)`, `lo < hi`.
95    uses: FxHashMap<(Key3, Key3), (u32, u32)>,
96    rejected: bool,
97}
98
99#[inline]
100fn position(positions: &[f32], i: u32) -> [f32; 3] {
101    let b = i as usize * 3;
102    [positions[b], positions[b + 1], positions[b + 2]]
103}
104
105impl EdgeLedger {
106    /// Walk `mesh` once. An out-of-range index panics, as every old walk did.
107    pub fn build(mesh: &Mesh, key: VertexKey, degenerate: Degenerate) -> Self {
108        Self::build_raw(&mesh.positions, &mesh.indices, key, degenerate)
109    }
110
111    /// [`build`](Self::build) over raw `positions` (xyz triples) and `indices`.
112    pub fn build_raw(positions: &[f32], indices: &[u32], key: VertexKey, degenerate: Degenerate) -> Self {
113        // One monomorphised walk per key spelling: the key is a closure, not a
114        // branch in the loop.
115        let at = |i: u32| position(positions, i);
116        match key {
117            VertexKey::Bits => Self::walk(indices, degenerate, |i| bits(at(i))),
118            VertexKey::BitsZeroFolded => Self::walk(indices, degenerate, |i| bits_zero_folded(at(i))),
119            VertexKey::GridDiv(q) => Self::walk(indices, degenerate, |i| grid_div(at(i), q)),
120            VertexKey::GridMul(k) => Self::walk(indices, degenerate, |i| grid_mul(at(i), k)),
121            VertexKey::Index => Self::walk(indices, degenerate, |i| [i64::from(i), 0, 0]),
122        }
123    }
124
125    #[inline]
126    fn walk(indices: &[u32], degenerate: Degenerate, key: impl Fn(u32) -> Key3) -> Self {
127        let mut ledger = Self { uses: FxHashMap::default(), rejected: false };
128        for t in indices.chunks_exact(3) {
129            let (ka, kb, kc) = (key(t[0]), key(t[1]), key(t[2]));
130            if degenerate != Degenerate::SkipEdge && (ka == kb || kb == kc || kc == ka) {
131                if degenerate == Degenerate::Reject {
132                    ledger.rejected = true;
133                    break;
134                }
135                continue;
136            }
137            for (x, y) in [(ka, kb), (kb, kc), (kc, ka)] {
138                // The other policies already checked all three pairs above.
139                if degenerate == Degenerate::SkipEdge && x == y {
140                    continue;
141                }
142                ledger.record_edge(x, y);
143            }
144        }
145        ledger
146    }
147
148    #[inline]
149    fn record_edge(&mut self, from: Key3, to: Key3) -> &(u32, u32) {
150        let (lo, hi, forward) = if from < to { (from, to, true) } else { (to, from, false) };
151        let slot = self.uses.entry((lo, hi)).or_insert((0, 0));
152        if forward {
153            slot.0 += 1;
154        } else {
155            slot.1 += 1;
156        }
157        slot
158    }
159
160    /// Recover consecutive, strictly paired shells from a merged triangle stream.
161    /// A face order without complete closed runs is ineligible for this recovery.
162    pub(crate) fn closed_shell_ranges(mesh: &Mesh) -> Option<Vec<std::ops::Range<usize>>> {
163        if !mesh.indices.len().is_multiple_of(3) {
164            return None;
165        }
166        let vertex_count = mesh.positions.len() / 3;
167        let mut ledger = Self { uses: FxHashMap::default(), rejected: false };
168        let mut ranges = Vec::new();
169        let mut pending = 0usize;
170        let mut start = 0;
171        for (triangle, indices) in mesh.indices.chunks_exact(3).enumerate() {
172            if indices.iter().any(|&index| index as usize >= vertex_count) {
173                return None;
174            }
175            let keys = [indices[0], indices[1], indices[2]].map(|index| {
176                let point = position(&mesh.positions, index);
177                point.iter().all(|value| value.is_finite()).then(|| bits_zero_folded(point))
178            });
179            let [Some(a), Some(b), Some(c)] = keys else { return None };
180            for (from, to) in [(a, b), (b, c), (c, a)] {
181                if from == to {
182                    return None;
183                }
184                match ledger.record_edge(from, to) {
185                    (1, 0) | (0, 1) => pending += 1,
186                    (1, 1) => pending -= 1,
187                    _ => return None,
188                }
189            }
190            if pending == 0 {
191                let end = (triangle + 1) * 3;
192                ranges.push(start..end);
193                start = end;
194                ledger.uses.clear();
195            }
196        }
197        (start == mesh.indices.len() && !ranges.is_empty()).then_some(ranges)
198    }
199
200    /// No edge was recorded (no triangle survived the degenerate rule).
201    pub fn is_empty(&self) -> bool {
202        self.uses.is_empty()
203    }
204
205    /// The walk stopped at a degenerate triangle under [`Degenerate::Reject`].
206    pub fn rejected(&self) -> bool {
207        self.rejected
208    }
209
210    /// Every edge is used as often forward as backward. Vacuously true on an
211    /// empty ledger; false on a rejected one.
212    pub fn directed_closed(&self) -> bool {
213        !self.rejected && self.uses.values().all(|&(f, r)| f == r)
214    }
215
216    /// Every edge is used exactly once each way. Vacuously true on an empty
217    /// ledger; false on a rejected one.
218    pub fn strictly_paired(&self) -> bool {
219        !self.rejected && self.uses.values().all(|&u| u == (1, 1))
220    }
221
222    /// Edges whose total use count is not two (open or non-manifold).
223    pub fn undirected_defects(&self) -> usize {
224        self.uses.values().filter(|&&(f, r)| f + r != 2).count()
225    }
226
227    /// The signed tally of directed edge `a -> b`: uses `a->b` minus uses
228    /// `b->a`. Zero for an edge never seen.
229    pub fn net(&self, a: Key3, b: Key3) -> i64 {
230        let (lo, hi, sign) = if a < b { (a, b, 1) } else { (b, a, -1) };
231        self.uses.get(&(lo, hi)).map_or(0, |&(f, r)| sign * (i64::from(f) - i64::from(r)))
232    }
233
234    /// Edges with a net directed tally, oriented so the tally is positive.
235    /// Iteration order is the map's: callers that need an order sort.
236    pub fn unbalanced(&self) -> impl Iterator<Item = (Key3, Key3, i64)> + '_ {
237        self.uses.iter().filter_map(|(&(lo, hi), &(f, r))| {
238            let net = i64::from(f) - i64::from(r);
239            match net {
240                0 => None,
241                n if n > 0 => Some((lo, hi, n)),
242                n => Some((hi, lo, -n)),
243            }
244        })
245    }
246
247    /// Whether an edge now has more than two uses and its use count grew.
248    pub(crate) fn overuse_increased_from(&self, before: &Self) -> bool {
249        self.uses.iter().any(|(edge, &(forward, reverse))| {
250            let uses = forward + reverse;
251            uses > 2 && before.uses.get(edge).is_none_or(|&(f, r)| f + r < uses)
252        })
253    }
254
255    /// The two defects a signed tally cannot represent: more than two uses,
256    /// and exactly two uses running the same way. An edge used once is an open
257    /// boundary, not a multiplicity defect.
258    pub fn multiplicity_defects(&self) -> EdgeMultiplicityDefects {
259        let mut defects = EdgeMultiplicityDefects::default();
260        for &(f, r) in self.uses.values() {
261            match f + r {
262                0 | 1 => {}
263                2 if f == 1 && r == 1 => {}
264                2 => defects.same_direction += 1,
265                _ => defects.over_used += 1,
266            }
267        }
268        defects
269    }
270}