Skip to main content

brep_kernel/io/parasolid/
check.rs

1//! Structural invariants of a manifold body's XT data (§4.3, §5.3), checked
2//! over the links the importer never follows: fin rings and pairs, the fin
3//! chains at vertices, back-pointers, the face, shell, region, edge, vertex
4//! and geometry chains, owners and node ids. A writer's output must satisfy
5//! everything Parasolid's own files do; the check is first run over real
6//! files, where it finds nothing.
7
8use super::reader::{Node, XtFile};
9
10/// Every invariant a solid or sheet body breaks, as messages; empty when it
11/// keeps them all.
12pub fn check_xt_body(file: &XtFile, body: &Node) -> Vec<String> {
13    let mut bad = Vec::new();
14    let mut say = |m: String| {
15        if bad.len() < 50 {
16            bad.push(m);
17        }
18    };
19    let get = |i: u32| file.node(i);
20    let kind = |i: u32| get(i).map_or("null", |n| n.type_name());
21    // Chains: walk `next` from a head, stopping on a repeat or at a node the
22    // file does not hold (so every index walked names a node); a chain that
23    // reaches a missing node is reported below.
24    let missing = std::cell::RefCell::new(Vec::new());
25    let walk = |head: u32, next: &'static str| {
26        let mut out = Vec::new();
27        let mut seen = rustc_hash::FxHashSet::default();
28        let mut at = head;
29        while at != 0 && seen.insert(at) {
30            let Some(node) = get(at) else {
31                missing.borrow_mut().push((out.last().copied(), next, at));
32                break;
33            };
34            out.push(at);
35            at = node.ptr(next);
36        }
37        out
38    };
39    let body_index = body.index;
40    // Regions.
41    let regions = walk(body.ptr("region"), "next");
42    if regions.is_empty() {
43        say("the body has no regions".into());
44    }
45    if let Some(&first) = regions.first() {
46        if get(first).and_then(|r| r.char("type")) != Some(b'V') {
47            say("the body's first region (the infinite one) is not void".into());
48        }
49    }
50    for pair in regions.windows(2) {
51        if get(pair[1]).map_or(0, |r| r.ptr("previous")) != pair[0] {
52            say(format!("region {} does not point back at {}", pair[1], pair[0]));
53        }
54    }
55    let mut shells = Vec::new();
56    for &r in &regions {
57        let region = get(r).unwrap();
58        if region.ptr("body") != body_index {
59            say(format!("region {r} does not name the body"));
60        }
61        for s in walk(region.ptr("shell"), "next") {
62            if kind(s) != "SHELL" {
63                say(format!("region {r}'s shell chain reaches a {}", kind(s)));
64                continue;
65            }
66            if get(s).unwrap().ptr("region") != r {
67                say(format!("shell {s} does not name its region {r}"));
68            }
69            shells.push(s);
70        }
71    }
72    // Faces: each a back face of exactly one shell and a front face of
73    // exactly one (manifold solid), with back-pointers.
74    let mut back_of = rustc_hash::FxHashMap::default();
75    let mut front_of = rustc_hash::FxHashMap::default();
76    for &s in &shells {
77        let shell = get(s).unwrap();
78        let back = walk(shell.ptr("face"), "next");
79        for pair in back.windows(2) {
80            if get(pair[1]).map_or(0, |f| f.ptr("previous")) != pair[0] {
81                say(format!("face {} does not point back at {} in shell {s}", pair[1], pair[0]));
82            }
83        }
84        for f in back {
85            if get(f).map_or(0, |n| n.ptr("shell")) != s {
86                say(format!("face {f} in shell {s}'s back chain names shell {}", get(f).map_or(0, |n| n.ptr("shell"))));
87            }
88            if back_of.insert(f, s).is_some() {
89                say(format!("face {f} is a back face of two shells"));
90            }
91        }
92        let front = walk(shell.ptr("front_face"), "next_front");
93        for pair in front.windows(2) {
94            if get(pair[1]).map_or(0, |f| f.ptr("previous_front")) != pair[0] {
95                say(format!("face {} does not point back at {} in shell {s}'s front chain", pair[1], pair[0]));
96            }
97        }
98        for f in front {
99            if get(f).map_or(0, |n| n.ptr("front_shell")) != s {
100                say(format!("face {f} in shell {s}'s front chain names front shell {}", get(f).map_or(0, |n| n.ptr("front_shell"))));
101            }
102            if front_of.insert(f, s).is_some() {
103                say(format!("face {f} is a front face of two shells"));
104            }
105        }
106    }
107    let solid = body.int("body_type") == Some(1);
108    let mut faces: Vec<u32> = back_of.keys().chain(front_of.keys()).copied().collect();
109    faces.sort_unstable();
110    faces.dedup();
111    if solid {
112        for &f in &faces {
113            if !back_of.contains_key(&f) || !front_of.contains_key(&f) {
114                say(format!("face {f} of a solid is not both a back and a front face"));
115            }
116        }
117    }
118    // Loops and fins.
119    let mut fins = Vec::new();
120    for &f in &faces {
121        let face = get(f).unwrap();
122        if get(face.ptr("surface")).is_none() {
123            say(format!("face {f} has no surface"));
124        }
125        for l in walk(face.ptr("loop"), "next") {
126            let lp = get(l).unwrap();
127            if lp.ptr("face") != f {
128                say(format!("loop {l} does not name its face {f}"));
129            }
130            let ring = walk(lp.ptr("halfedge"), "forward");
131            for (k, &h) in ring.iter().enumerate() {
132                let fin = get(h).unwrap();
133                if fin.ptr("loop") != l {
134                    say(format!("fin {h} does not name its loop {l}"));
135                }
136                let next = ring[(k + 1) % ring.len()];
137                if fin.ptr("forward") != next {
138                    say(format!("loop {l}'s ring does not close at fin {h}"));
139                }
140                if get(next).map_or(0, |n| n.ptr("backward")) != h {
141                    say(format!("fin {next} does not point back at {h}"));
142                }
143                // A fin runs to its vertex, and the next fin starts there:
144                // the next fin's start is its other fin's vertex.
145                let start_of_next = get(next).and_then(|n| get(n.ptr("other"))).map_or(0, |o| o.ptr("vertex"));
146                if fin.ptr("edge") != 0 && get(next).map_or(0, |n| n.ptr("edge")) != 0 && fin.ptr("vertex") != start_of_next {
147                    say(format!("fin {h} ends at vertex {} but the next fin {next} starts at {start_of_next}", fin.ptr("vertex")));
148                }
149                fins.push(h);
150            }
151        }
152    }
153    // Edges: two fins, opposite senses, paired; the positive one heads the
154    // edge's fin chain and points at the vertex the edge runs to.
155    let edges = walk(body.ptr("edge"), "next");
156    for pair in edges.windows(2) {
157        if get(pair[1]).map_or(0, |e| e.ptr("previous")) != pair[0] {
158            say(format!("edge {} does not point back at {}", pair[1], pair[0]));
159        }
160    }
161    let mut primary_secondary = rustc_hash::FxHashSet::default();
162    for &e in &edges {
163        let edge = get(e).unwrap();
164        if edge.ptr("owner") != body_index {
165            say(format!("edge {e} is not owned by the body"));
166        }
167        let first = edge.ptr("halfedge");
168        let Some(a) = get(first) else {
169            say(format!("edge {e} has no fin"));
170            continue;
171        };
172        let second = a.ptr("other");
173        let Some(b) = get(second) else {
174            say(format!("edge {e}'s fin {first} has no other"));
175            continue;
176        };
177        if a.char("sense") != Some(b'+') {
178            say(format!("edge {e}'s first fin {first} is not positive"));
179        }
180        if solid && b.ptr("other") != first {
181            say(format!("edge {e}'s fins {first} and {second} are not each other's other"));
182        }
183        if solid && b.char("sense") != Some(b'-') {
184            say(format!("edge {e}'s second fin {second} is not negative"));
185        }
186        for h in [first, second] {
187            if get(h).map_or(0, |n| n.ptr("edge")) != e {
188                say(format!("fin {h} does not name its edge {e}"));
189            }
190        }
191        if edge.ptr("curve") == 0 && edge.real("tolerance").is_none() {
192            say(format!("edge {e} has no curve and is not tolerant"));
193        }
194        primary_secondary.insert(first);
195        primary_secondary.insert(second);
196    }
197    for &h in &fins {
198        let fin = get(h).unwrap();
199        if fin.ptr("edge") != 0 && !edges.contains(&fin.ptr("edge")) {
200            say(format!("fin {h}'s edge {} is not in the body's edge chain", fin.ptr("edge")));
201        }
202    }
203    // Vertices: their fin chains hold exactly the primary and secondary fins
204    // that run to them.
205    let vertices = walk(body.ptr("vertex"), "next");
206    for pair in vertices.windows(2) {
207        if get(pair[1]).map_or(0, |v| v.ptr("previous")) != pair[0] {
208            say(format!("vertex {} does not point back at {}", pair[1], pair[0]));
209        }
210    }
211    let mut chained = rustc_hash::FxHashSet::default();
212    for &v in &vertices {
213        let vertex = get(v).unwrap();
214        if vertex.ptr("owner") != body_index {
215            say(format!("vertex {v} is not owned by the body"));
216        }
217        match get(vertex.ptr("point")) {
218            Some(p) if p.type_name() == "POINT" => {
219                if p.ptr("owner") != v {
220                    say(format!("vertex {v}'s point does not name it"));
221                }
222            }
223            _ => say(format!("vertex {v} has no point")),
224        }
225        for h in walk(vertex.ptr("halfedge"), "next_at_vx") {
226            if get(h).map_or(0, |n| n.ptr("vertex")) != v {
227                say(format!("fin {h} in vertex {v}'s chain runs to vertex {}", get(h).map_or(0, |n| n.ptr("vertex"))));
228            }
229            // An isolated loop's fin (no edge) is chained at its vertex too
230            // (§5.3.8.1).
231            let isolated = get(h).is_some_and(|n| n.ptr("edge") == 0 && n.ptr("forward") == h);
232            if !isolated && !primary_secondary.contains(&h) {
233                say(format!("fin {h} in vertex {v}'s chain is neither an edge's primary nor secondary fin"));
234            }
235            chained.insert(h);
236        }
237    }
238    for &h in &primary_secondary {
239        // A dummy fin (a sheet's laminar edge: no loop) is in no chain
240        // (§5.3.9.1).
241        let dummy = get(h).is_some_and(|n| n.ptr("loop") == 0);
242        if !dummy && get(h).map_or(0, |n| n.ptr("vertex")) != 0 && !chained.contains(&h) {
243            say(format!("fin {h} is an edge's primary or secondary fin but no vertex chains it"));
244        }
245    }
246    // Geometry: each surface, curve and point of the body in its boundary
247    // chain, owned by what uses it (or by another geometry node).
248    for (head, what) in [("boundary_surface", "surface"), ("boundary_curve", "curve"), ("boundary_point", "point")] {
249        let chain = walk(body.ptr(head), "next");
250        for pair in chain.windows(2) {
251            if get(pair[1]).map_or(0, |g| g.ptr("previous")) != pair[0] {
252                say(format!("{what} {} does not point back at {} in the body's {head} chain", pair[1], pair[0]));
253            }
254        }
255        for g in chain {
256            if get(g).map_or(0, |n| n.ptr("owner")) == 0 && get(g).map_or(0, |n| n.ptr("geometric_owner")) == 0 {
257                say(format!("{what} {g} in the body's chain has no owner"));
258            }
259        }
260    }
261    for (from, field, to) in missing.borrow().iter() {
262        match from {
263            Some(from) => say(format!("node {from}'s {field} points at node {to}, which the file does not hold")),
264            None => say(format!("a chain's head is node {to}, which the file does not hold")),
265        }
266    }
267    // Node ids: distinct, positive, at most the body's highest.
268    let highest = body.int("highest_node_id").unwrap_or(0);
269    let mut ids = rustc_hash::FxHashMap::default();
270    for n in file.nodes() {
271        let Some(id) = n.int("node_id") else { continue };
272        if id == 0 || n.layout.fields.iter().all(|f| f.name != "node_id") {
273            continue;
274        }
275        if id > highest {
276            say(format!("{} {} has node id {id} above the body's highest {highest}", n.type_name(), n.index));
277        }
278        if let Some(other) = ids.insert(id, n.index) {
279            say(format!("node id {id} is on nodes {other} and {}", n.index));
280        }
281    }
282    bad
283}