Skip to main content

brep_construction/construction/
mill_envelope.rs

1//! The lower envelope of a ball-end mill's moves: the surface it leaves on
2//! the stock's top.
3//!
4//! A ball-end mill's ball of radius `r` whose centre runs a straight segment
5//! sweeps a CAPSULE: every point within `r` of the segment. Wherever the mill
6//! cuts down into the stock's top and nothing of its shank reaches lower than
7//! its ball (an upright mill, or one leaning away from the part as a
8//! five-axis finish holds it), what is left of the stock is the stock below
9//! the height field `h(x, y)`, the lowest point of any capsule above (x, y):
10//! the LOWER ENVELOPE of the capsules. Over each capsule the underside is
11//! exact: the lower half of its end balls, or the lower side of the cylinder
12//! of radius `r` about its segment, where that point's foot on the segment
13//! lies within it.
14//!
15//! This first piece reads the envelope exactly at a point ([`BallEnvelope::height`],
16//! with which capsule and which part of it is lowest there), and integrates the
17//! volume under it ([`BallEnvelope::volume_under`], the referee of the solid the
18//! construction builds). [`crate::mill_plan`] reads which surface is lowest
19//! where as a graph of exact boundary curves; the faces are built on it next.
20
21use crate::Vec3;
22
23/// The part of a capsule that is lowest at a point: its cylinder, or the ball
24/// about one end (`false` the start, `true` the end).
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Underside {
27    Tube,
28    Ball(bool),
29}
30
31/// Ball-end mill moves: balls of `radius` whose centres run the segments.
32#[derive(Clone, Debug)]
33pub struct BallEnvelope {
34    radius: f64,
35    /// Each move's ball centres, start to end.
36    segments: Vec<(Vec3, Vec3)>,
37    /// A uniform grid over the segments' plan boxes (each grown by the
38    /// radius): cell (i, j) lists the segments whose box meets it.
39    grid: Grid,
40}
41
42#[derive(Clone, Debug)]
43struct Grid {
44    origin: [f64; 2],
45    cell: f64,
46    size: [usize; 2],
47    cells: Vec<Vec<usize>>,
48}
49
50/// The underside of the ball of `radius` about `centre` over (x, y); None
51/// past its rim.
52pub fn ball_underside(centre: Vec3, radius: f64, x: f64, y: f64) -> Option<f64> {
53    let (dx, dy) = (x - centre.x, y - centre.y);
54    let d2 = dx * dx + dy * dy;
55    (d2 <= radius * radius).then(|| centre.z - (radius * radius - d2).sqrt())
56}
57
58impl BallEnvelope {
59    /// The balls' radius.
60    pub fn radius(&self) -> f64 {
61        self.radius
62    }
63
64    /// The moves' ball-centre segments, start to end.
65    pub fn segments(&self) -> &[(Vec3, Vec3)] {
66        &self.segments
67    }
68
69    /// The envelope of `segments` swept by balls of `radius`. Its envelope
70    /// (None outside it): a radius in [1e-100, 1e100], and every coordinate
71    /// within 1e6 radii of the origin. Within it a read is backward accurate:
72    /// the point it returns lies on the capsule's surface to about 1e-10 of
73    /// the radius. Its height alone can move further where the capsule's
74    /// wall stands near upright, since there the height itself turns on the
75    /// plan position that sharply.
76    pub fn new(radius: f64, segments: Vec<(Vec3, Vec3)>) -> Option<Self> {
77        if !(radius.is_finite() && (1e-100..=1e100).contains(&radius)) || segments.is_empty() {
78            return None;
79        }
80        let bound = 1e6 * radius;
81        let within = |p: &Vec3| [p.x, p.y, p.z].iter().all(|c| c.is_finite() && c.abs() <= bound);
82        if !segments.iter().all(|(a, b)| within(a) && within(b)) {
83            return None;
84        }
85        let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
86        for (a, b) in &segments {
87            for p in [a, b] {
88                lo = [lo[0].min(p.x - radius), lo[1].min(p.y - radius)];
89                hi = [hi[0].max(p.x + radius), hi[1].max(p.y + radius)];
90            }
91        }
92        // Cells about the radius across, at most 1024 a side.
93        let cell = radius.max((hi[0] - lo[0]).max(hi[1] - lo[1]) / 1024.0);
94        // One cell more than the span needs a side, so a point on the boxes' far
95        // edge (a capsule's outer reach) falls in a cell.
96        let size = [((hi[0] - lo[0]) / cell).floor() as usize + 1, ((hi[1] - lo[1]) / cell).floor() as usize + 1];
97        let mut cells = vec![Vec::new(); size[0] * size[1]];
98        for (index, (a, b)) in segments.iter().enumerate() {
99            let (x0, x1) = (a.x.min(b.x) - radius, a.x.max(b.x) + radius);
100            let (y0, y1) = (a.y.min(b.y) - radius, a.y.max(b.y) + radius);
101            let span = |v0: f64, v1: f64, axis: usize| {
102                let first = (((v0 - lo[axis]) / cell).floor().max(0.0) as usize).min(size[axis] - 1);
103                let last = (((v1 - lo[axis]) / cell).floor().max(0.0) as usize).min(size[axis] - 1);
104                first..=last
105            };
106            for i in span(x0, x1, 0) {
107                for j in span(y0, y1, 1) {
108                    cells[i * size[1] + j].push(index);
109                }
110            }
111        }
112        Some(BallEnvelope { radius, segments, grid: Grid { origin: lo, cell, size, cells } })
113    }
114
115    /// The lowest point of the capsule `index` above (x, y), and which part
116    /// of it that is; None where the capsule does not reach over (x, y).
117    pub fn capsule_underside(&self, index: usize, x: f64, y: f64) -> Option<(f64, Underside)> {
118        let [start, end, tube] = self.capsule_parts(index, x, y);
119        let mut best: Option<(f64, Underside)> = None;
120        for (z, part) in [(start, Underside::Ball(false)), (end, Underside::Ball(true)), (tube, Underside::Tube)] {
121            if let Some(z) = z {
122                if best.is_none_or(|(b, _)| z < b) {
123                    best = Some((z, part));
124                }
125            }
126        }
127        best
128    }
129
130    /// Each part of the capsule `index` over (x, y): the underside of its
131    /// start ball, of its end ball, and of its tube (None where that part
132    /// does not reach: past a ball's rim, or where the tube's foot leaves the
133    /// segment).
134    pub fn capsule_parts(&self, index: usize, x: f64, y: f64) -> [Option<f64>; 3] {
135        let (a, b) = self.segments[index];
136        let tube = self.tube_root(index, x, y).and_then(|(z, foot)| (0.0..=1.0).contains(&foot).then_some(z));
137        [ball_underside(a, self.radius, x, y), ball_underside(b, self.radius, x, y), tube]
138    }
139
140    /// The lower side of the whole line's cylinder about the capsule
141    /// `index`'s segment over (x, y), and the foot of that point on the line
142    /// (0 at the segment's start, 1 at its end); None where the line's
143    /// cylinder does not reach over (x, y) or the segment has no length.
144    pub fn tube_root(&self, index: usize, x: f64, y: f64) -> Option<(f64, f64)> {
145        let (a, b) = self.segments[index];
146        let r = self.radius;
147        // The cylinder about the segment: points P = (x, y, a.z + Z) with
148        // |(P − a)⊥| = r, the part square to the axis u. With v = (x − a.x,
149        // y − a.y, 0) and e = (0, 0, 1), (P − a)⊥ = v⊥ + Z e⊥, so
150        // |e⊥|² Z² + 2 (v⊥·e⊥) Z + |v⊥|² − r² = 0 (each part square to u
151        // formed directly, never as a difference of squares); its lower root.
152        let d = b.sub(a);
153        let length = d.length();
154        if !(length > 0.0) {
155            return None;
156        }
157        let u = d.scale(1.0 / length);
158        // Read about the axis point nearest the query's vertical line (in
159        // plan), so every term below stands at the radius's scale: `shift`
160        // along the axis from `a` (none for an axis near upright).
161        let plan = u.x * u.x + u.y * u.y;
162        let shift = if plan > 1e-24 { ((x - a.x) * u.x + (y - a.y) * u.y) / plan } else { 0.0 };
163        let base = a.add(u.scale(shift));
164        let v = Vec3::new(x - base.x, y - base.y, 0.0);
165        let vu = v.dot(u);
166        let v_perp = v.sub(u.scale(vu));
167        let e_perp = Vec3::new(-u.z * u.x, -u.z * u.y, 1.0 - u.z * u.z);
168        let qa = e_perp.dot(e_perp);
169        let qb = 2.0 * v_perp.dot(e_perp);
170        let qc = v_perp.dot(v_perp) - r * r;
171        // A tangent read negative by rounding alone (short of zero by
172        // under 1e-12 of 4·|e⊥|²·r², the radius's own scale) is a touch.
173        let disc = qb * qb - 4.0 * qa * qc;
174        let disc = if disc < 0.0 && -disc <= 1e-12 * 4.0 * qa * r * r { 0.0 } else { disc };
175        if !(qa > 0.0 && disc >= 0.0) {
176            return None;
177        }
178        // The two roots in the form that does not cancel, the lower one;
179        // a touch (the discriminant zero, or clamped to it) its double root.
180        let z_low = if disc == 0.0 {
181            -qb / (2.0 * qa)
182        } else {
183            let q = -0.5 * (qb + qb.signum() * disc.sqrt());
184            let (r1, r2) = (q / qa, if q != 0.0 { qc / q } else { q / qa });
185            r1.min(r2)
186        };
187        Some((base.z + z_low, (shift + vu + z_low * u.z) / length))
188    }
189
190    /// The capsules whose plan boxes hold (x, y) (a superset of those that
191    /// reach over it); none outside the grid.
192    pub fn candidates(&self, x: f64, y: f64) -> &[usize] {
193        let Grid { origin, cell, size, cells } = &self.grid;
194        let i = ((x - origin[0]) / cell).floor();
195        let j = ((y - origin[1]) / cell).floor();
196        if !(i >= 0.0 && j >= 0.0 && (i as usize) < size[0] && (j as usize) < size[1]) {
197            return &[];
198        }
199        &cells[i as usize * size[1] + j as usize]
200    }
201
202    /// The envelope at (x, y): the lowest point of any capsule above it, the
203    /// capsule's index and its part; None where no capsule reaches.
204    pub fn height(&self, x: f64, y: f64) -> Option<(f64, usize, Underside)> {
205        let mut best: Option<(f64, usize, Underside)> = None;
206        for &index in self.candidates(x, y) {
207            if let Some((z, part)) = self.capsule_underside(index, x, y) {
208                if best.is_none_or(|(b, _, _)| z < b) {
209                    best = Some((z, index, part));
210                }
211            }
212        }
213        best
214    }
215
216    /// The volume of the box `[x0, x1] × [y0, y1] × [bottom, top]` below the
217    /// envelope (the stock left where the capsules cut its top), by
218    /// Gauss-Legendre on square cells of size `cell`, four
219    /// points a side each. The envelope has creases (where two capsules meet),
220    /// so the rule converges as the cell's square at best: two sizes and
221    /// Richardson are the caller's.
222    ///
223    /// The box and the cell lie in the capsules' own envelope (None outside
224    /// it): every bound within 1e6 radii of the origin, the box of positive
225    /// extent, the cell at least 1e-6 radii.
226    pub fn volume_under(&self, x0: f64, x1: f64, y0: f64, y1: f64, bottom: f64, top: f64, cell: f64) -> Option<f64> {
227        let bound = 1e6 * self.radius;
228        if !(cell.is_finite() && cell >= 1e-6 * self.radius) || ![x0, x1, y0, y1, bottom, top].iter().all(|c| c.is_finite() && c.abs() <= bound) || !(x1 > x0 && y1 > y0 && top >= bottom) {
229            return None;
230        }
231
232        const X: [f64; 4] = [-0.861_136_311_594_052_6, -0.339_981_043_584_856_3, 0.339_981_043_584_856_3, 0.861_136_311_594_052_6];
233        const W: [f64; 4] = [0.347_854_845_137_453_9, 0.652_145_154_862_546_1, 0.652_145_154_862_546_1, 0.347_854_845_137_453_9];
234        // At most 1e8 cells, counted as they are iterated.
235        let (fx, fy) = (((x1 - x0) / cell).ceil().max(1.0), ((y1 - y0) / cell).ceil().max(1.0));
236        if !(fx * fy <= 1e8) {
237            return None;
238        }
239        let (nx, ny) = (fx as usize, fy as usize);
240        let (hx, hy) = ((x1 - x0) / nx as f64, (y1 - y0) / ny as f64);
241        let mut total = 0.0;
242        for i in 0..nx {
243            for j in 0..ny {
244                let (cx, cy) = (x0 + hx * (i as f64 + 0.5), y0 + hy * (j as f64 + 0.5));
245                for (a, wa) in X.iter().zip(W) {
246                    for (b, wb) in X.iter().zip(W) {
247                        let (x, y) = (cx + 0.5 * hx * a, cy + 0.5 * hy * b);
248                        let surface = self.height(x, y).map_or(top, |(z, _, _)| z.min(top)).max(bottom);
249                        // Each point's share scaled by its cell's area as it is summed.
250                        total += wa * wb * 0.25 * hx * hy * (surface - bottom);
251                    }
252                }
253            }
254        }
255        Some(total)
256    }
257}
258