Skip to main content

quiddity/features/
turned.rs

1//! What the turned-stock treatments share — a toroidal fillet and a conical chamfer are both
2//! proved by the coaxial external cylinders and the faces they meet (`quiddity.fillets`,
3//! `quiddity.chamfers`); countersinks read cone rims the same way. The turned-profile key
4//! (`quiddity.turned.profile_key_from_bands`) under which steps and grooves publish their
5//! body/profile join lives here too.
6
7use std::cmp::Ordering;
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12use super::Context;
13use super::body::BodyKey;
14use super::cylinders::{CylinderEvidence, coaxial_axis_lines};
15use super::placed::{Grid, Placed};
16use super::policy::{self, AXIS_ALIGNED_COS};
17use crate::kernel::brep::Part;
18use crate::kernel::geom::{self, Bounds, Curve, Surface, V3};
19use crate::kernel::py;
20
21/// Coaxial analytic axes may differ by modelling noise only (a fraction of the diameter).
22const COAXIAL_FRAC: f64 = 1e-4;
23
24internal_entry! {
25/// The run's external cylinders by face.
26pub fn external_cylinders<'c>(ctx: &'c Context<'_>) -> BTreeMap<usize, &'c CylinderEvidence> {
27    ctx.cylinders()
28        .iter()
29        .filter(|c| c.external)
30        .map(|c| (c.face, c))
31        .collect()
32}
33}
34
35internal_entry! {
36/// The external cylinders among *neighbours* that revolve about the line (*origin*, *axis*).
37pub fn coaxial_cylinders<'c>(
38    neighbours: &[usize],
39    external: &BTreeMap<usize, &'c CylinderEvidence>,
40    origin: V3,
41    axis: V3,
42) -> Vec<&'c CylinderEvidence> {
43    neighbours
44        .iter()
45        .filter_map(|n| external.get(n).copied())
46        .filter(|c| {
47            coaxial_axis_lines(
48                origin,
49                axis,
50                c.axis_point,
51                c.direction,
52                policy::length_tol(c.diameter, COAXIAL_FRAC),
53            )
54        })
55        .collect()
56}
57}
58
59internal_entry! {
60/// Whether the coaxial cylinders include two different bands (a shoulder between diameters).
61pub fn bridges_two_bands(coaxial: &[&CylinderEvidence]) -> bool {
62    coaxial.iter().any(|c| c.diameter != coaxial[0].diameter)
63}
64}
65
66internal_entry! {
67/// The planar faces among *neighbours* square to *axis* (a shoulder or end face).
68pub fn transverse_planes(part: &Part, neighbours: &[usize], axis: V3) -> Vec<usize> {
69    neighbours
70        .iter()
71        .copied()
72        .filter(|&n| match part.faces[n].surface {
73            Surface::Plane { frame } => geom::dot(frame.z, axis).abs() > AXIS_ALIGNED_COS,
74            _ => false,
75        })
76        .collect()
77}
78}
79
80/// A circular edge's radius and centre.
81fn circle(part: &Part, edge: usize) -> Option<(f64, V3)> {
82    match part.edges[edge].curve {
83        Curve::Circle { frame, radius } => Some((radius, frame.origin)),
84        _ => None,
85    }
86}
87
88/// A circular rim: its radius and centre.
89pub type Rim = (f64, V3);
90
91internal_entry! {
92/// `(minor, major, included angle°)` of a cone face: its smallest and largest circular rims and
93/// the full cone angle to 2 dp (`cone_rims`).
94pub fn cone_rims(part: &Part, face: usize) -> Option<(Rim, Rim, f64)> {
95    let Surface::Cone { semi_angle, .. } = part.faces[face].surface else {
96        return None;
97    };
98    let mut circles: Vec<(f64, V3)> = part
99        .face_edges(face)
100        .into_iter()
101        .filter_map(|e| circle(part, e))
102        .collect();
103    if circles.len() < 2 {
104        return None;
105    }
106    circles.sort_by(|a, b| py::order(a.0, b.0));
107    let included = py::round_to(2.0 * semi_angle.to_degrees().abs(), 2);
108    Some((circles[0], circles[circles.len() - 1], included))
109}
110}
111
112/// The body-local membership of one turned profile (`TurnedProfileKey`): the axis letter, the
113/// commonest band axis point with its axial coordinate zeroed, the body's box and its key.
114#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct TurnedProfileKey {
117    pub axis: char,
118    pub axis_origin: Placed<V3>,
119    pub body_bounds: Placed<[f64; 6]>,
120    pub body_key: Option<BodyKey>,
121}
122
123impl TurnedProfileKey {
124    /// Python's `_order_key` comparison.
125    pub fn order(&self, other: &Self) -> Ordering {
126        self.axis
127            .cmp(&other.axis)
128            .then_with(|| py::tuple_order(&self.axis_origin[..], &other.axis_origin[..]))
129            .then_with(|| py::tuple_order(&self.body_bounds[..], &other.body_bounds[..]))
130            .then(self.body_key.is_some().cmp(&other.body_key.is_some()))
131            .then_with(|| {
132                py::tuple_order(
133                    self.body_key.as_ref().map_or(&[][..], |k| k.as_slice()),
134                    other.body_key.as_ref().map_or(&[][..], |k| k.as_slice()),
135                )
136            })
137    }
138}
139
140internal_entry! {
141/// The axis letter of an axis index.
142pub fn axis_letter(axis: usize) -> char {
143    ['x', 'y', 'z'][axis]
144}
145}
146
147internal_entry! {
148/// `profile_key_from_bands`: the profile one body's coaxial bands prove. *bounds* is the body's
149/// box (the solid's, or the part's when it has none).
150pub fn profile_key_from_bands(
151    axis: usize,
152    bands: &[&CylinderEvidence],
153    bounds: &Bounds,
154    body_key: Option<BodyKey>,
155) -> TurnedProfileKey {
156    // Coaxial supports describe one transverse origin. Average their raw representatives
157    // before publication, instead of selecting a modal rounded coordinate lexicographically.
158    // Translation, axis interchange and reversal commute with this affine construction.
159    assert!(!bands.is_empty(), "a profile has bands");
160    let origin = [0, 1, 2].map(|i| {
161        if i == axis {
162            0.0
163        } else {
164            py::fsum(bands.iter().map(|b| b.axis_point[i])) / bands.len() as f64
165        }
166    });
167    TurnedProfileKey {
168        axis: axis_letter(axis),
169        axis_origin: Placed::new(origin, Grid::Decimals(8)),
170        body_bounds: Placed::new(
171            [
172                bounds.min[0],
173                bounds.max[0],
174                bounds.min[1],
175                bounds.max[1],
176                bounds.min[2],
177                bounds.max[2],
178            ],
179            Grid::Decimals(8),
180        ),
181        body_key,
182    }
183}
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn equally_supported_profile_origins_follow_motion_and_band_permutation() {
192        // Analytically coaxial bands can carry transverse modelling noise. Both rounded
193        // representatives occur once: the lower coordinate must not win the mode tie.
194        for [w, l, axis] in [[0, 1, 2], [1, 2, 0], [2, 0, 1]] {
195            for sign in [-1., 1.] {
196                for shift in [0., 123.456] {
197                    let point = |noise: f64| {
198                        let mut p = [0.; 3];
199                        p[w] = shift + sign * (1. + noise);
200                        p[l] = shift - sign * (2. - noise);
201                        p[axis] = shift;
202                        p
203                    };
204                    let mut direction = [0.; 3];
205                    direction[axis] = sign;
206                    let mut bands: Vec<_> = [-2e-8, 2e-8]
207                        .into_iter()
208                        .enumerate()
209                        .map(|(face, noise)| CylinderEvidence {
210                            face,
211                            solid: 0,
212                            diameter: 10.,
213                            axis,
214                            u_extent: std::f64::consts::TAU,
215                            axis_point: point(noise),
216                            direction,
217                            s_lo: 0.,
218                            s_hi: 10.,
219                            external: true,
220                        })
221                        .collect();
222                    let bounds = Bounds {
223                        min: [shift - 10.; 3],
224                        max: [shift + 10.; 3],
225                    };
226                    let mut expected = point(0.).map(|v| py::round_to(v, 8));
227                    expected[axis] = 0.;
228                    for _ in 0..2 {
229                        let refs: Vec<_> = bands.iter().collect();
230                        let key = profile_key_from_bands(axis, &refs, &bounds, None);
231                        assert_eq!(*key.axis_origin, expected);
232                        bands.reverse();
233                    }
234                }
235            }
236        }
237    }
238}