Skip to main content

brep_kernel/feature_pipeline/
ports_contact.rs

1//! A connection point's CONTACT BODY: a pin that is a whole solid of the part
2//! (an XLR pin, a barrel jack's centre pin or sleeve, a JST crimp, a square
3//! header post, a spade blade, a pin bent along a curve), which a face pick
4//! cannot express ("A contact body").
5//!
6//! The body is one more SEAT source, below the explicit references: it
7//! supplies the origin when `pointRef` does not, and the direction when
8//! neither `directionRef` nor `pointRef` does. What it supplies is its two
9//! ENDS, each with the direction a wire leaves along there, found by the
10//! first rule that applies:
11//!
12//! * the AXIS rule: the body's axis-bearing analytic faces (cylinder, cone,
13//!   torus, general revolution) grouped by collinear axis, and exactly one
14//!   group. The ends are the axis points at the extremes of the body's extent
15//!   along it (its edges, and a sphere face centred on the axis, so a rounded
16//!   tip ends at its pole); the wire leaves along the axis, out of the body;
17//! * the END-CAP rule, for a body with no single axis (a square post, a
18//!   blade, a pin swept along a curve, a pin with a cross hole): its TERMINAL
19//!   faces are the planar faces the whole body lies behind, and the tip of a
20//!   rounded or pointed end (a sphere's pole, or the axis point at the end of
21//!   a fillet's torus or a cone). A flat end opposite a tip is read on the
22//!   tip's axis line, so a scooped solder cup's off-centre half-ring still
23//!   attaches on the pin's axis. The
24//!   two ends are the pair of terminal faces farthest apart, when no other
25//!   pair comes close (a cube has three such pairs and no distinct ends). A
26//!   body whose only planar faces are two caps (a pin swept round a bend of
27//!   more than a right angle) takes those two, unless both lie at one end (a
28//!   cup's floor behind its rim). A wire attaches at a cap's
29//!   centroid and leaves along its outward normal, which for a swept pin is
30//!   the path's end tangent; on a straight round pin the two rules agree;
31//! * the STRIP rule, for a body the end-cap rule finds no distinct ends on
32//!   and no Direction picks (a gull-wing lead: its end caps do not face each
33//!   other, and its flat sides lie at the extremes too): the end caps where
34//!   its longest path along its edges runs out, each seated on its SOLE (the
35//!   flat face beside the cap, square to it and facing away from the other
36//!   end: the foot's underside) when it has one, the wire leaving along the
37//!   sole's normal. A cube still has no distinct ends under it
38//!   (`BREP_CONTACT_STRIP_ENDS`, on; `0` turns it off). With
39//!   `BREP_CONTACT_STRIP_AXIS` (off) it also takes a body the axis rule would
40//!   read across: one whose only round face is a bend (a lead with one round
41//!   bend, a right-angle header pin), which reaches farther from that axis
42//!   than it runs along it;
43//! * the DIRECTION rule, for a body with no distinct ends (a cube, a block
44//!   terminal) when the point names a Direction (`directionRef`: a face's
45//!   normal, an edge, an axis, a datum): the end is the body's extreme along
46//!   that direction (the centroid of a face normal to it, else the middle of
47//!   the extreme points) and the wire leaves along it. With no Direction such
48//!   a body is refused by name, and the message says to pick one.
49//!
50//! The WIRE END is the end farther from the centre of the rest of the part,
51//! or the `+axis` end (the chord between the ends in its canonical sense:
52//! largest component positive) when the body is the only solid or the two
53//! are equally far (under the strip rule, the end with the longer sole: a
54//! lead's foot); under the direction rule it is the end the Direction
55//! points to. `reverseDirection` takes the other one. The wire leaves OUTWARD
56//! from the chosen end.
57//!
58//! [`contact_body_solid`] and [`contact_body_end`] are public so the board's
59//! pad check finds the same solid and the same end the router does.
60
61use serde::{Deserialize, Serialize};
62
63use super::{SceneMap, SelectionGeometry, Vec3};
64
65/// Samples per edge for the axial extent. The extremes of a cylinder, cone or
66/// planar face along the axis lie on its boundary, so the edges carry them; a
67/// circle's axial coordinate is constant, so any sample is exact for it.
68const EDGE_SAMPLES: usize = 16;
69/// Grid samples per direction over a sphere face's surface: a rounded tip's
70/// pole is at a domain boundary, which the grid includes exactly.
71const SPHERE_SAMPLES: usize = 16;
72/// Directions closer than this (|d1 x d2|) are parallel.
73const PARALLEL: f64 = 1e-6;
74/// A terminal face lies within this of the body's extreme along its normal,
75/// scaled by the body's size (edge samples are chords of curved edges).
76const TERMINAL_TOLERANCE: f64 = 1e-4;
77/// Two pairs of terminal faces whose distances are within this ratio are a
78/// tie: the body has no distinct ends.
79const DISTINCT_ENDS: f64 = 0.85;
80/// Lengths below this, scaled by the body's size, are the same point.
81const RELATIVE_TOLERANCE: f64 = 1e-6;
82
83/// Which rule found a contact body's ends (see the module docs).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum ContactRule {
86    /// The body's one axis.
87    Axis,
88    /// Its two terminal faces.
89    Caps,
90    /// The point's Direction, on a body with no distinct ends.
91    Direction,
92    /// The end caps at the ends of a bent strip's longest path, each seated
93    /// on its sole when it has one (`BREP_CONTACT_STRIP_ENDS`).
94    Strip,
95}
96
97impl ContactRule {
98    /// The word the report shows.
99    pub fn as_str(self) -> &'static str {
100        match self {
101            ContactRule::Axis => "axis",
102            ContactRule::Caps => "caps",
103            ContactRule::Direction => "direction",
104            ContactRule::Strip => "strip",
105        }
106    }
107}
108
109/// What a contact body derives: its two ends, the direction a wire leaves
110/// along at each, and the end a wire leaves from.
111#[derive(Debug, Clone, Copy)]
112pub struct ContactAxis {
113    /// The axis direction in its canonical sense (largest component
114    /// positive): the body's axis, or under the cap rule the chord from the
115    /// `-axis` end to the `+axis` end, or the Direction.
116    pub axis: Vec3,
117    /// The `+axis` end.
118    pub plus_end: Vec3,
119    /// The `-axis` end.
120    pub minus_end: Vec3,
121    /// The direction a wire leaves along at the `+axis` end (out of the body).
122    pub plus_outward: Vec3,
123    /// The direction a wire leaves along at the `-axis` end.
124    pub minus_outward: Vec3,
125    /// Whether the wire leaves from the `+axis` end.
126    pub wire_at_plus: bool,
127    /// The rule that found the ends.
128    pub rule: ContactRule,
129}
130
131impl ContactAxis {
132    /// The end a wire attaches at.
133    pub fn wire_end(&self) -> Vec3 {
134        if self.wire_at_plus {
135            self.plus_end
136        } else {
137            self.minus_end
138        }
139    }
140
141    /// The other end (the mating end, on a pin whose wire side is right).
142    pub fn other_end(&self) -> Vec3 {
143        if self.wire_at_plus {
144            self.minus_end
145        } else {
146            self.plus_end
147        }
148    }
149
150    /// The direction a wire leaves along: OUT of the body at the wire end.
151    pub fn outward(&self) -> Vec3 {
152        if self.wire_at_plus {
153            self.plus_outward
154        } else {
155            self.minus_outward
156        }
157    }
158}
159
160/// The contact body as the tail's report shows it, so a wrong default end is
161/// visible next to the one-click flip (`reverseDirection`).
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct PortContactRow {
165    /// The solid named by `contactBody`.
166    pub body: String,
167    /// `"+axis"` or `"-axis"`: which end the wire took, in the axis's
168    /// canonical sense.
169    pub end: String,
170    /// The canonical axis direction.
171    pub axis: [f64; 3],
172    /// Where the wire attaches.
173    pub wire_end: [f64; 3],
174    /// The other end.
175    pub other_end: [f64; 3],
176    /// Whether the body SEATED the origin (no `pointRef`). With a `pointRef`
177    /// the body is reported, but the origin is the reference's.
178    pub seats_origin: bool,
179    /// `"axis"`, `"caps"`, `"strip"` or `"direction"`: the rule that found
180    /// the ends.
181    #[serde(default)]
182    pub rule: String,
183}
184
185/// The resident solid a contact body names, by the same lookup every seat
186/// reference uses ([`SceneMap::resolve_solid`]): its handle, or `None` when
187/// the scene holds no solid of that name.
188pub fn contact_body_solid(scene: &SceneMap, name: &str) -> Option<u32> {
189    let name = name.trim();
190    if name.is_empty() {
191        return None;
192    }
193    scene.resolve_solid(name)
194}
195
196/// The ends and the wire end of the contact body `name`, by the axis or the
197/// end-cap rule. `reverse` (a point's `reverseDirection`) takes the other end.
198/// A body with no distinct ends is refused; [`contact_body_end`] takes a
199/// Direction for it.
200pub fn contact_body_axis(scene: &SceneMap, name: &str, reverse: bool) -> Result<ContactAxis, String> {
201    contact_body_end(scene, name, reverse, None)
202}
203
204/// The ends and the wire end of the contact body `name`. `reverse` (a point's
205/// `reverseDirection`) takes the other end; `direction` (the point's resolved
206/// `directionRef`) picks the end of a body that has no distinct ends.
207///
208/// `Err` names why nothing is derived: no such solid, a body with no length,
209/// or one with no distinct ends and no Direction to pick one by.
210pub fn contact_body_end(
211    scene: &SceneMap,
212    name: &str,
213    reverse: bool,
214    direction: Option<Vec3>,
215) -> Result<ContactAxis, String> {
216    let name = name.trim();
217    let handle = contact_body_solid(scene, name)
218        .ok_or_else(|| format!("contact body '{name}' is not a solid of this part"))?;
219    let (ends, scale) = crate::with_registered_solid_str(handle, |solid| body_ends(solid, name, direction))?;
220    let mut wire_at_plus = match ends.toward {
221        // The direction rule: the end the Direction points to.
222        Some(toward) => toward,
223        // Otherwise the end farther from the rest of the part.
224        None => {
225            let mut plus_side = ends.plus_by_default;
226            if let Some(centre) = rest_of_part_centre(scene, handle) {
227                let plus = ends.plus_end.sub(centre).length();
228                let minus = ends.minus_end.sub(centre).length();
229                if (plus - minus).abs() > RELATIVE_TOLERANCE * scale {
230                    plus_side = plus > minus;
231                }
232            }
233            plus_side
234        }
235    };
236    if reverse {
237        wire_at_plus = !wire_at_plus;
238    }
239    Ok(ContactAxis {
240        axis: ends.axis,
241        plus_end: ends.plus_end,
242        minus_end: ends.minus_end,
243        plus_outward: ends.plus_outward,
244        minus_outward: ends.minus_outward,
245        wire_at_plus,
246        rule: ends.rule,
247    })
248}
249
250/// A body's two ends before the wire side is chosen.
251struct Ends {
252    axis: Vec3,
253    plus_end: Vec3,
254    minus_end: Vec3,
255    plus_outward: Vec3,
256    minus_outward: Vec3,
257    rule: ContactRule,
258    /// Under the direction rule, whether the Direction points to the `+axis`
259    /// end; `None` leaves the side to the rest of the part.
260    toward: Option<bool>,
261    /// The wire end when the rest of the part does not decide (the body is
262    /// the only solid, or both ends are equally far): the `+axis` end, except
263    /// under the strip rule (the end with the longer sole, a lead's foot).
264    plus_by_default: bool,
265}
266
267/// The body's ends by the first rule that applies, and its size scale.
268fn body_ends(solid: &crate::BrepSolid, name: &str, direction: Option<Vec3>) -> Result<(Ends, f64), String> {
269    let scale = solid_scale(solid);
270    let points = body_points(solid);
271    if points.is_empty() {
272        return Err(format!("contact body '{name}' has no geometry to measure"));
273    }
274    let tolerance = RELATIVE_TOLERANCE * scale;
275
276    // Every axis-bearing face's axis, grouped by collinearity; planar faces
277    // and sphere faces for the end caps.
278    let mut groups: Vec<(Vec3, Vec3)> = Vec::new();
279    let mut spheres: Vec<(&crate::FaceRecord, Vec3, f64)> = Vec::new();
280    let mut planes: Vec<(&crate::FaceRecord, Vec3)> = Vec::new();
281    // Round faces that are not cylinders (a fillet's torus, a cone, a general
282    // revolution): a rounded or pointed tip, with its axis.
283    let mut round_tips: Vec<(&crate::FaceRecord, Vec3, Vec3)> = Vec::new();
284    for shell in &solid.shells {
285        for face in &shell.faces {
286            match crate::resolve_face_selection(solid, face.id) {
287                Ok(SelectionGeometry::Axis { origin, direction, radius }) => {
288                    let Ok(direction) = direction.normalized() else { continue };
289                    let direction = canonical(direction);
290                    if radius.is_none() {
291                        round_tips.push((face, origin, direction));
292                    }
293                    let known = groups
294                        .iter()
295                        .any(|(o, d)| collinear(*o, *d, origin, direction, tolerance));
296                    if !known {
297                        groups.push((origin, direction));
298                    }
299                }
300                Ok(SelectionGeometry::Sphere { center, radius }) => spheres.push((face, center, radius)),
301                Ok(SelectionGeometry::Plane { normal, .. }) => {
302                    if let Ok(normal) = normal.normalized() {
303                        planes.push((face, normal));
304                    }
305                }
306                _ => {}
307            }
308        }
309    }
310
311    if let [(origin, axis)] = groups.as_slice() {
312        let (origin, axis) = (*origin, *axis);
313        let (low, high) = axial_extent(&points, &spheres, origin, axis, tolerance);
314        if high - low <= RELATIVE_TOLERANCE * scale {
315            return Err(format!("contact body '{name}' has no length along its axis"));
316        }
317        // A body reaching farther from its one axis than it runs along it is
318        // no pin on that axis: a lead with one round bend, whose bend is its
319        // only round face. The strip rule takes it when it finds its ends.
320        let reach = points.iter().map(|p| off_axis(origin, axis, *p)).fold(0.0, f64::max);
321        if direction.is_none() && reach > high - low && strip_axis_enabled() {
322            if let Some(ends) = strip_body_ends(solid, &points, scale) {
323                return Ok((ends, scale));
324            }
325        }
326        let ends = Ends {
327            axis,
328            plus_end: origin.add(axis.scale(high)),
329            minus_end: origin.add(axis.scale(low)),
330            plus_outward: axis,
331            minus_outward: axis.scale(-1.0),
332            rule: ContactRule::Axis,
333            toward: None,
334            plus_by_default: true,
335        };
336        return Ok((ends, scale));
337    }
338
339    // The end caps: planar faces the whole body lies behind, and the tips of
340    // rounded or pointed ends. A tip carries its axis line, so the end at the
341    // other side can be read on the same line.
342    let slack = TERMINAL_TOLERANCE * scale;
343    let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
344    let body_centre = bbox_centre(&points);
345    let mut caps: Vec<Cap> = Vec::new();
346    for (face, normal) in &planes {
347        if let Some(centre) = boundary_centroid(solid, face) {
348            if behind(centre, *normal) {
349                caps.push(Cap { point: centre, outward: *normal, line: None });
350            }
351        }
352    }
353    for (face, center, _) in &spheres {
354        if let Some(pole) = sphere_tip(face, body_centre) {
355            if let Ok(outward) = pole.sub(*center).normalized() {
356                if behind(pole, outward) {
357                    caps.push(Cap { point: pole, outward, line: Some((*center, outward)) });
358                }
359            }
360        }
361    }
362    for (face, origin, axis) in &round_tips {
363        if let Some(tip) = axial_tip(face, *origin, *axis, body_centre) {
364            if behind(tip.point, tip.outward) {
365                caps.push(tip);
366            }
367        }
368    }
369    // One end found twice (a partly filleted tip: its torus's top and the
370    // flat disc left inside it are the same point) is one end.
371    let mut ends: Vec<Cap> = Vec::new();
372    for cap in caps {
373        match ends.iter_mut().find(|end| end.point.sub(cap.point).length() <= slack) {
374            Some(end) => {
375                if end.line.is_none() {
376                    end.line = cap.line;
377                }
378            }
379            None => ends.push(cap),
380        }
381    }
382    if ends.len() < 2 && planes.len() == 2 {
383        // A pin swept round a sharp bend: its two caps are its only planes,
384        // unless both lie at ONE end (a cup's floor behind its rim), which
385        // says nothing about where the other end is.
386        let two: Vec<Cap> = planes
387            .iter()
388            .filter_map(|(face, normal)| {
389                boundary_centroid(solid, face).map(|centre| Cap { point: centre, outward: *normal, line: None })
390            })
391            .collect();
392        if two.len() == 2 && !same_end(&two[0], &two[1]) {
393            ends = two;
394        }
395    }
396    if let Some((a, b)) = distinct_ends(&ends, tolerance) {
397        let (mut a, mut b) = (ends[a], ends[b]);
398        // A flat end opposite a tip is read on the tip's line: a scooped
399        // solder cup's half-ring has its centroid off the pin's axis.
400        a.point = on_line_of(a, &b);
401        b.point = on_line_of(b, &a);
402        if let Ok(chord) = a.point.sub(b.point).normalized() {
403            let axis = canonical(chord);
404            let (plus, minus) = if a.point.dot(axis) >= b.point.dot(axis) { (a, b) } else { (b, a) };
405            let ends = Ends {
406                axis,
407                plus_end: plus.point,
408                minus_end: minus.point,
409                plus_outward: plus.outward,
410                minus_outward: minus.outward,
411                rule: ContactRule::Caps,
412                toward: None,
413                plus_by_default: true,
414            };
415            return Ok((ends, scale));
416        }
417    }
418
419    // No distinct ends and no Direction: a bent strip (a gull-wing lead) still
420    // has two, at the ends of its longest path along its edges.
421    if direction.is_none() && strip_ends_enabled() {
422        if let Some(ends) = strip_body_ends(solid, &points, scale) {
423            return Ok((ends, scale));
424        }
425    }
426
427    // No distinct ends: the point's Direction picks one.
428    let Some(direction) = direction.and_then(|d| d.normalized().ok()) else {
429        return Err(format!(
430            "contact body '{name}' has no distinct ends to take a wire end from; pick a Direction (a face, an edge or an axis) to say which way the wire leaves"
431        ));
432    };
433    let axis = canonical(direction);
434    let extreme = |toward: Vec3| -> Vec3 {
435        // A terminal face normal to the direction: its centroid.
436        for (face, normal) in &planes {
437            if normal.dot(toward) >= 1.0 - PARALLEL {
438                if let Some(centre) = boundary_centroid(solid, face) {
439                    if behind(centre, *normal) {
440                        return centre;
441                    }
442                }
443            }
444        }
445        // Else the middle of the points at the extreme.
446        let top = points.iter().map(|p| p.dot(toward)).fold(f64::NEG_INFINITY, f64::max);
447        let at_top: Vec<Vec3> = points.iter().copied().filter(|p| top - p.dot(toward) <= slack).collect();
448        bbox_centre(&at_top)
449    };
450    let plus_end = extreme(axis);
451    let minus_end = extreme(axis.scale(-1.0));
452    if plus_end.sub(minus_end).dot(axis) <= RELATIVE_TOLERANCE * scale {
453        return Err(format!("contact body '{name}' has no length along its Direction"));
454    }
455    let ends = Ends {
456        axis,
457        plus_end,
458        minus_end,
459        plus_outward: axis,
460        minus_outward: axis.scale(-1.0),
461        rule: ContactRule::Direction,
462        toward: Some(direction.dot(axis) > 0.0),
463        plus_by_default: true,
464    };
465    Ok((ends, scale))
466}
467
468/// Whether the strip rule runs: `BREP_CONTACT_STRIP_ENDS`, on unless `0` or
469/// `off`. It only answers a body every earlier rule refused with no
470/// Direction, so turning it on moves no seat that resolved before.
471fn strip_ends_enabled() -> bool {
472    crate::switch!("BREP_CONTACT_STRIP_ENDS", true)
473}
474
475/// Whether the strip rule also takes a body the AXIS rule would seat, when
476/// it reaches farther from its one axis than it runs along it (a lead with
477/// one round bend): `BREP_CONTACT_STRIP_AXIS`, OFF unless set. It moves a
478/// seat that resolved before, so it waits for promotion.
479fn strip_axis_enabled() -> bool {
480    strip_ends_enabled() && crate::switch!("BREP_CONTACT_STRIP_AXIS", false)
481}
482
483/// The two ends of a bent strip (a gull-wing or J lead, a bent tab): the
484/// body every other rule finds no distinct ends on, because its flat end caps
485/// do not face each other and its long flat sides lie at the extremes too.
486///
487/// Its ends are where its longest path runs out. The path is measured along
488/// the body's EDGES (a strip's long edges follow its bends, and an edge
489/// never cuts across a face, so a bend cannot be short-cut): the two points
490/// farthest apart along them (a double sweep: the farthest point from any
491/// point, then the farthest from that) are corners of the two end caps. At
492/// each, the cap is the flat terminal face lying wholly at that end: the one
493/// whose NEAREST boundary point is farthest along the path from the other
494/// end (first from the far corner, then from the whole cap found there, so
495/// crossing the strip's width never counts; the caps found each way must
496/// agree). A side face running the strip's length reaches back to the other
497/// end, and a face of the last straight run reaches back to its bend, so a
498/// cap beats both by the run's length. The cap must beat every other face
499/// by at least half its own size, or the end is not distinct (a cube's three
500/// faces at a corner tie) and the body is still refused: so a strip's last
501/// straight run must be longer than half its cap's diagonal. A body whose
502/// edges are not one connected piece (a face with a hole: pins merged into a
503/// housing, a cross hole) is no strip and is refused too.
504///
505/// With no rest of the part to say which end the wire takes, it takes the
506/// end with the longer sole: a lead's foot is longer than the shoulder where
507/// it leaves the package.
508///
509/// Each end is then SEATED ON ITS SOLE when it has one: the flat terminal
510/// face beside the cap, square to it, facing away from the other end (a
511/// gull-wing foot's underside, which is what lands on the pad). The point is
512/// the sole's centroid and the wire leaves along its normal, INTO the board,
513/// as a through-hole pin's tail does; Align to footprint reads that
514/// direction as the seating plane. An end with no sole keeps its cap's
515/// centroid and outward normal, as a swept pin's end does.
516fn strip_ends(
517    solid: &crate::BrepSolid,
518    planes: &[(&crate::FaceRecord, Vec3)],
519    behind: &dyn Fn(Vec3, Vec3) -> bool,
520    slack: f64,
521) -> Option<((Cap, f64), (Cap, f64))> {
522    let graph = WireGraph::of(solid);
523    if graph.points.len() < 2 {
524        return None;
525    }
526    let from_start = graph.distances(0);
527    // One piece of wire, or no strip: a face with a hole (pins merged into a
528    // housing, a cross hole) leaves edges no path along the others reaches.
529    if from_start.iter().any(|d| !d.is_finite()) {
530        return None;
531    }
532    let p = farthest(&from_start)?;
533    let from_p = graph.distances(p);
534
535    // Terminal flat faces, with their boundary nodes.
536    let faces: Vec<(&crate::FaceRecord, Vec3, Vec3, Vec<usize>)> = planes
537        .iter()
538        .filter_map(|(face, normal)| {
539            let centre = boundary_centroid(solid, face)?;
540            if !behind(centre, *normal) {
541                return None;
542            }
543            let nodes = graph.face_nodes(face);
544            (!nodes.is_empty()).then(|| (*face, *normal, centre, nodes))
545        })
546        .collect();
547    // The cap at the end the field `from_other` is measured away from.
548    let cap_at = |from_other: &[f64]| -> Option<usize> {
549        let mut scored: Vec<(f64, usize)> = faces
550            .iter()
551            .enumerate()
552            .map(|(i, (_, _, _, nodes))| {
553                (nodes.iter().map(|n| from_other[*n]).fold(f64::INFINITY, f64::min), i)
554            })
555            .filter(|(score, _)| score.is_finite())
556            .collect();
557        scored.sort_by(|a, b| b.0.total_cmp(&a.0));
558        let &(best, i) = scored.first()?;
559        let size = graph.spread(&faces[i].3);
560        let distinct = scored.get(1).map_or(true, |&(second, _)| best - second >= 0.5 * size);
561        (distinct && size > slack).then_some(i)
562    };
563    // The cap at q's end, from p; then each end measured from the WHOLE cap
564    // at the other (a corner alone would favour the side face across the
565    // strip from it by the strip's width), and the two must agree.
566    let at_q = cap_at(&from_p)?;
567    let at_p = cap_at(&graph.distances_from(&faces[at_q].3))?;
568    if at_p == at_q || cap_at(&graph.distances_from(&faces[at_p].3))? != at_q {
569        return None;
570    }
571    let cap = |i: usize| Cap { point: faces[i].2, outward: faces[i].1, line: None };
572    let (a, b) = (cap(at_p), cap(at_q));
573    if same_end(&a, &b) || a.point.sub(b.point).length() <= slack {
574        return None;
575    }
576    // Each end on its sole, when it has one, with the sole's size (0 for
577    // none).
578    let soled = |end: usize, other: Vec3| -> (Cap, f64) {
579        let (cap_face, normal, centre, _) = &faces[end];
580        let Ok(away) = other.sub(*centre).normalized() else { return (cap(end), 0.0) };
581        let cap_edges: Vec<u64> = face_edges(cap_face);
582        faces
583            .iter()
584            .enumerate()
585            .filter(|(i, (face, n, _, _))| {
586                *i != end
587                    && n.dot(*normal).abs() <= SQUARE
588                    && n.dot(away) <= -SOLE_AWAY
589                    && face_edges(face).iter().any(|e| cap_edges.contains(e))
590            })
591            .min_by(|x, y| x.1 .1.dot(away).total_cmp(&y.1 .1.dot(away)))
592            .map(|(_, (_, n, c, nodes))| (Cap { point: *c, outward: *n, line: None }, graph.spread(nodes)))
593            .unwrap_or_else(|| (cap(end), 0.0))
594    };
595    Some((soled(at_p, b.point), soled(at_q, a.point)))
596}
597
598/// The strip rule's ends ([`strip_ends`]) as [`Ends`], over the body's flat
599/// faces.
600fn strip_body_ends(solid: &crate::BrepSolid, points: &[Vec3], scale: f64) -> Option<Ends> {
601    let slack = TERMINAL_TOLERANCE * scale;
602    let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
603    let planes: Vec<(&crate::FaceRecord, Vec3)> = solid
604        .shells
605        .iter()
606        .flat_map(|shell| &shell.faces)
607        .filter_map(|face| match crate::resolve_face_selection(solid, face.id) {
608            Ok(SelectionGeometry::Plane { normal, .. }) => normal.normalized().ok().map(|normal| (face, normal)),
609            _ => None,
610        })
611        .collect();
612    let ((a, a_sole), (b, b_sole)) = strip_ends(solid, &planes, &behind, slack)?;
613    let axis = canonical(a.point.sub(b.point).normalized().ok()?);
614    let ((plus, plus_sole), (minus, minus_sole)) =
615        if a.point.dot(axis) >= b.point.dot(axis) { ((a, a_sole), (b, b_sole)) } else { ((b, b_sole), (a, a_sole)) };
616    Some(Ends {
617        axis,
618        plus_end: plus.point,
619        minus_end: minus.point,
620        plus_outward: plus.outward,
621        minus_outward: minus.outward,
622        rule: ContactRule::Strip,
623        toward: None,
624        plus_by_default: plus_sole >= minus_sole,
625    })
626}
627
628/// Two flat faces whose normals are within this (|n1 . n2|) are square.
629const SQUARE: f64 = 1e-3;
630/// A sole faces away from the other end: its normal against the direction
631/// to it by at least this (cosine).
632const SOLE_AWAY: f64 = 0.25;
633
634/// The edge ids of a face's loops.
635fn face_edges(face: &crate::FaceRecord) -> Vec<u64> {
636    face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect()
637}
638
639/// The index of the largest finite distance.
640fn farthest(distances: &[f64]) -> Option<usize> {
641    distances
642        .iter()
643        .enumerate()
644        .filter(|(_, d)| d.is_finite())
645        .max_by(|a, b| a.1.total_cmp(b.1))
646        .map(|(i, _)| i)
647}
648
649/// The body's edges as a graph: each vertex one node, each edge sampled into
650/// a chain of nodes between its two vertices.
651struct WireGraph {
652    points: Vec<Vec3>,
653    links: Vec<Vec<(usize, f64)>>,
654    /// Each edge id's chain of nodes.
655    chains: std::collections::HashMap<u64, Vec<usize>>,
656}
657
658impl WireGraph {
659    fn of(solid: &crate::BrepSolid) -> Self {
660        let mut graph = WireGraph { points: Vec::new(), links: Vec::new(), chains: Default::default() };
661        let mut vertex_node: std::collections::HashMap<u64, usize> = Default::default();
662        for vertex in &solid.vertices {
663            vertex_node.insert(vertex.id, graph.node(vertex.point));
664        }
665        for edge in &solid.edges {
666            if edge.degenerate {
667                continue;
668            }
669            let (Some(&start), Some(&end)) = (vertex_node.get(&edge.start_vertex_id), vertex_node.get(&edge.end_vertex_id))
670            else {
671                continue;
672            };
673            let mut chain = vec![start];
674            for i in 1..EDGE_SAMPLES {
675                let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
676                if let Ok(point) = edge.curve.evaluate(t) {
677                    chain.push(graph.node(point));
678                }
679            }
680            chain.push(end);
681            for pair in chain.windows(2) {
682                let length = graph.points[pair[0]].sub(graph.points[pair[1]]).length();
683                graph.links[pair[0]].push((pair[1], length));
684                graph.links[pair[1]].push((pair[0], length));
685            }
686            graph.chains.insert(edge.id, chain);
687        }
688        graph
689    }
690
691    fn node(&mut self, point: Vec3) -> usize {
692        self.points.push(point);
693        self.links.push(Vec::new());
694        self.points.len() - 1
695    }
696
697    /// The nodes on a face's boundary.
698    fn face_nodes(&self, face: &crate::FaceRecord) -> Vec<usize> {
699        let mut nodes: Vec<usize> = face_edges(face)
700            .iter()
701            .filter_map(|e| self.chains.get(e))
702            .flatten()
703            .copied()
704            .collect();
705        nodes.sort_unstable();
706        nodes.dedup();
707        nodes
708    }
709
710    /// The largest distance between two of `nodes`: a face's size.
711    fn spread(&self, nodes: &[usize]) -> f64 {
712        let mut largest = 0.0_f64;
713        for (k, a) in nodes.iter().enumerate() {
714            for b in &nodes[k + 1..] {
715                largest = largest.max(self.points[*a].sub(self.points[*b]).length());
716            }
717        }
718        largest
719    }
720
721    /// The shortest distance along the edges from `source` to every node.
722    fn distances(&self, source: usize) -> Vec<f64> {
723        self.distances_from(&[source])
724    }
725
726    /// The shortest distance along the edges from the nearest of `sources`
727    /// to every node.
728    fn distances_from(&self, sources: &[usize]) -> Vec<f64> {
729        use std::cmp::Reverse;
730        let mut best = vec![f64::INFINITY; self.points.len()];
731        let mut heap = std::collections::BinaryHeap::new();
732        for &source in sources {
733            best[source] = 0.0;
734            heap.push(Reverse((Ordered(0.0), source)));
735        }
736        while let Some(Reverse((Ordered(d), node))) = heap.pop() {
737            if d > best[node] {
738                continue;
739            }
740            for &(next, length) in &self.links[node] {
741                let through = d + length;
742                if through < best[next] {
743                    best[next] = through;
744                    heap.push(Reverse((Ordered(through), next)));
745                }
746            }
747        }
748        best
749    }
750}
751
752/// An `f64` ordered by `total_cmp`, for the heap.
753#[derive(Clone, Copy, PartialEq)]
754struct Ordered(f64);
755impl Eq for Ordered {}
756impl PartialOrd for Ordered {
757    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
758        Some(self.cmp(other))
759    }
760}
761impl Ord for Ordered {
762    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
763        self.0.total_cmp(&other.0)
764    }
765}
766
767/// The body's extent `[low, high]` along an axis through `origin`, measured
768/// from it: its vertices, its edges, and any sphere face centred on the axis
769/// (a rounded tip, whose pole is the end).
770fn axial_extent(
771    points: &[Vec3],
772    spheres: &[(&crate::FaceRecord, Vec3, f64)],
773    origin: Vec3,
774    axis: Vec3,
775    tolerance: f64,
776) -> (f64, f64) {
777    let mut low = f64::INFINITY;
778    let mut high = f64::NEG_INFINITY;
779    let mut include = |point: Vec3| {
780        let t = point.sub(origin).dot(axis);
781        low = low.min(t);
782        high = high.max(t);
783    };
784    for point in points {
785        include(*point);
786    }
787    for (face, center, _) in spheres {
788        if off_axis(origin, axis, *center) > tolerance {
789            continue;
790        }
791        for point in sphere_samples(face) {
792            include(point);
793        }
794    }
795    (low, high)
796}
797
798/// The body's vertices and samples along its edges: the extremes of a
799/// cylinder, cone or planar face along any direction lie on its boundary.
800fn body_points(solid: &crate::BrepSolid) -> Vec<Vec3> {
801    let mut points: Vec<Vec3> = solid.vertices.iter().map(|vertex| vertex.point).collect();
802    for edge in &solid.edges {
803        if edge.degenerate {
804            continue;
805        }
806        for i in 0..=EDGE_SAMPLES {
807            let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
808            if let Ok(point) = edge.curve.evaluate(t) {
809                points.push(point);
810            }
811        }
812    }
813    points
814}
815
816/// A grid of points over a sphere face (its pole lies on a domain boundary,
817/// which the grid includes exactly).
818fn sphere_samples(face: &crate::FaceRecord) -> Vec<Vec3> {
819    let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return Vec::new() };
820    let mut out = Vec::new();
821    for i in 0..=SPHERE_SAMPLES {
822        for j in 0..=SPHERE_SAMPLES {
823            let s = u[0] + (u[1] - u[0]) * (i as f64 / SPHERE_SAMPLES as f64);
824            let t = v[0] + (v[1] - v[0]) * (j as f64 / SPHERE_SAMPLES as f64);
825            if let Ok(point) = face.surface.evaluate(s, t) {
826                out.push(point);
827            }
828        }
829    }
830    out
831}
832
833/// A rounded tip's pole: the sphere face's point farthest from the body's
834/// centre.
835fn sphere_tip(face: &crate::FaceRecord, body_centre: Vec3) -> Option<Vec3> {
836    sphere_samples(face)
837        .into_iter()
838        .max_by(|a, b| a.sub(body_centre).length().total_cmp(&b.sub(body_centre).length()))
839}
840
841/// The centroid of a face's boundary, each edge sample weighted by the length
842/// it stands for: the centre of a cap's rectangle, disc or ring.
843fn boundary_centroid(solid: &crate::BrepSolid, face: &crate::FaceRecord) -> Option<Vec3> {
844    let mut sum = Vec3::new(0.0, 0.0, 0.0);
845    let mut length = 0.0;
846    for edge_id in face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)) {
847        let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else { continue };
848        if edge.degenerate {
849            continue;
850        }
851        let samples: Vec<Vec3> = (0..=EDGE_SAMPLES)
852            .filter_map(|i| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64)).ok())
853            .collect();
854        for pair in samples.windows(2) {
855            let piece = pair[1].sub(pair[0]).length();
856            sum = sum.add(pair[0].add(pair[1]).scale(0.5 * piece));
857            length += piece;
858        }
859    }
860    (length > 0.0).then(|| sum.scale(1.0 / length))
861}
862
863/// The pair of caps farthest apart, when no other pair comes within
864/// [`DISTINCT_ENDS`] of it (a cube's three opposite pairs tie).
865fn distinct_ends(caps: &[Cap], tolerance: f64) -> Option<(usize, usize)> {
866    let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
867    for i in 0..caps.len() {
868        for j in i + 1..caps.len() {
869            pairs.push((caps[i].point.sub(caps[j].point).length(), i, j));
870        }
871    }
872    pairs.sort_by(|a, b| b.0.total_cmp(&a.0));
873    let &(best, i, j) = pairs.first()?;
874    if best <= tolerance {
875        return None;
876    }
877    let rival = pairs.iter().skip(1).any(|&(d, k, l)| (k, l) != (i, j) && d >= DISTINCT_ENDS * best);
878    (!rival).then_some((i, j))
879}
880
881/// One candidate end: where a wire attaches, the direction it leaves along,
882/// and for a tip its axis line (a point on it and its direction).
883#[derive(Debug, Clone, Copy)]
884pub(super) struct Cap {
885    pub(super) point: Vec3,
886    pub(super) outward: Vec3,
887    pub(super) line: Option<(Vec3, Vec3)>,
888}
889
890/// A round non-cylindrical face's tip (a fillet's torus, a cone), when it is
891/// at an end: the axis point at the face's extreme along its axis on the side
892/// away from the body's centre, leaving along the axis.
893fn axial_tip(face: &crate::FaceRecord, origin: Vec3, axis: Vec3, body_centre: Vec3) -> Option<Cap> {
894    let samples = sphere_samples(face);
895    if samples.is_empty() {
896        return None;
897    }
898    let along: Vec<f64> = samples.iter().map(|p| p.sub(origin).dot(axis)).collect();
899    let mean = along.iter().sum::<f64>() / along.len() as f64;
900    let centre = body_centre.sub(origin).dot(axis);
901    let (t, outward) = if mean >= centre {
902        (along.iter().copied().fold(f64::NEG_INFINITY, f64::max), axis)
903    } else {
904        (along.iter().copied().fold(f64::INFINITY, f64::min), axis.scale(-1.0))
905    };
906    Some(Cap { point: origin.add(axis.scale(t)), outward, line: Some((origin, axis)) })
907}
908
909/// `end`'s point, moved onto `other`'s tip line when `end` faces along that
910/// line (a flat end opposite a tip); unchanged otherwise.
911fn on_line_of(end: Cap, other: &Cap) -> Vec3 {
912    let (Some((origin, direction)), None) = (other.line, end.line) else { return end.point };
913    let Ok(direction) = direction.normalized() else { return end.point };
914    if end.outward.dot(direction).abs() < 1.0 - PARALLEL {
915        return end.point;
916    }
917    origin.add(direction.scale(end.point.sub(origin).dot(direction)))
918}
919
920/// Whether two flat caps lie at ONE end of a body: they face the same way and
921/// one stands behind the other along that way (a cup's floor behind its rim),
922/// rather than side by side (the two legs of a hairpin).
923pub(super) fn same_end(a: &Cap, b: &Cap) -> bool {
924    let apart = a.point.sub(b.point);
925    let length = apart.length();
926    a.outward.dot(b.outward) > 0.9 && (length == 0.0 || apart.dot(a.outward).abs() >= 0.9 * length)
927}
928
929/// The centre of the points' bounding box.
930fn bbox_centre(points: &[Vec3]) -> Vec3 {
931    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
932    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
933    for p in points {
934        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
935        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
936    }
937    low.add(high).scale(0.5)
938}
939
940/// The centre of the bounding box of every OTHER resident solid of the scene:
941/// what "the rest of the part" a pin sticks out of is. `None` when the body is
942/// the only solid.
943fn rest_of_part_centre(scene: &SceneMap, body: u32) -> Option<Vec3> {
944    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
945    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
946    let mut any = false;
947    let mut handles: Vec<u32> = scene.solids.values().copied().filter(|h| *h != body).collect();
948    handles.sort_unstable();
949    handles.dedup();
950    for handle in handles {
951        let Ok((a, b)) = crate::feature_pipeline::pmi::resolve::solid_bbox(handle) else { continue };
952        low = Vec3::new(low.x.min(a.x), low.y.min(a.y), low.z.min(a.z));
953        high = Vec3::new(high.x.max(b.x), high.y.max(b.y), high.z.max(b.z));
954        any = true;
955    }
956    any.then(|| low.add(high).scale(0.5))
957}
958
959/// The direction with its largest component positive: one sense for an axis,
960/// whichever way a face happens to report it.
961fn canonical(direction: Vec3) -> Vec3 {
962    let [x, y, z] = [direction.x, direction.y, direction.z];
963    let largest = if x.abs() >= y.abs() && x.abs() >= z.abs() {
964        x
965    } else if y.abs() >= z.abs() {
966        y
967    } else {
968        z
969    };
970    if largest < 0.0 {
971        direction.scale(-1.0)
972    } else {
973        direction
974    }
975}
976
977/// Whether two axes are one line.
978fn collinear(o1: Vec3, d1: Vec3, o2: Vec3, d2: Vec3, tolerance: f64) -> bool {
979    d1.cross(d2).length() <= PARALLEL && off_axis(o1, d1, o2) <= tolerance.max(1e-9)
980}
981
982/// How far `point` is from the line through `origin` along unit `axis`.
983fn off_axis(origin: Vec3, axis: Vec3, point: Vec3) -> f64 {
984    let offset = point.sub(origin);
985    offset.sub(axis.scale(offset.dot(axis))).length()
986}
987
988/// A size for the body: its vertex bounding-box diagonal, at least 1.
989fn solid_scale(solid: &crate::BrepSolid) -> f64 {
990    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
991    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
992    for vertex in &solid.vertices {
993        let p = vertex.point;
994        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
995        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
996    }
997    if solid.vertices.is_empty() {
998        return 1.0;
999    }
1000    high.sub(low).length().max(1.0)
1001}