Skip to main content

brep_construction/construction/
mill_program.rs

1//! What a flat-bottomed upright end mill removes from the level it is moved at: the plane region
2//! its circle covers as its axis runs a program of level moves (straight lines and arcs about
3//! upright axes), extruded from that level up through the workpiece's top.
4//!
5//! The region is the union of the discs of the cutter's radius about every point of the moves.
6//! Its boundary lies on exact curves of three kinds: each straight move's two offset lines, each
7//! arc move's two offset arcs (about the arc's own centre), and the circle about every move's
8//! ends. Those carriers are made once each (coincident ones merged), cut where they cross or touch
9//! one another (in closed form: lines and circles), and a piece is kept where the region lies on
10//! exactly one side of it (two probes along it, read by the exact distance to the moves). The kept
11//! pieces chain into loops: counter-clockwise outer loops and clockwise holes, each hole in the
12//! smallest outer loop holding it. Each outer loop with its holes is one prism, its walls planes
13//! and cylinders, its ends planes: no boolean and no fitted curve.
14//!
15//! One call makes every depth band's prism at once only when the caller asks for one band: the
16//! moves given are at one level; a program at several depths is several calls (a deeper move
17//! covers a shallower one over the same ground, so the caller passes the deepest).
18use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
19use crate::{make_arc, make_line, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, OrRefuse, Vec3, Vec4};
20use std::f64::consts::TAU;
21
22/// A level move of the cutter's axis, in the plane of the level (x, y).
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub enum MillMove {
25    /// Straight from `from` to `to` (the same point: the cutter standing, a plunge seen from above).
26    Line { from: [f64; 2], to: [f64; 2] },
27    /// About `centre` at `radius`, from the angle `start` (radians, from +x toward +y) through
28    /// `sweep` (negative: clockwise).
29    Arc { centre: [f64; 2], radius: f64, start: f64, sweep: f64 },
30}
31
32/// The prefix of every refusal of this module.
33pub const MILL_REGION_REFUSAL: &str = "millRegion";
34
35fn refuse(what: &'static str, message: String) -> KernelRefusal {
36    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{MILL_REGION_REFUSAL}: {message}"))
37}
38
39fn input(what: &'static str, message: String) -> KernelRefusal {
40    KernelRefusal::input(KernelStage::Collect, what, format!("{MILL_REGION_REFUSAL}: {message}"))
41}
42
43fn frag<T>(result: Result<T, String>, what: &'static str) -> Result<T, KernelRefusal> {
44    result.or_refuse(KernelStage::Fragment, what)
45}
46
47type P = [f64; 2];
48
49fn sub(a: P, b: P) -> P {
50    [a[0] - b[0], a[1] - b[1]]
51}
52fn add(a: P, b: P) -> P {
53    [a[0] + b[0], a[1] + b[1]]
54}
55fn scale(a: P, k: f64) -> P {
56    [a[0] * k, a[1] * k]
57}
58fn dot(a: P, b: P) -> f64 {
59    a[0] * b[0] + a[1] * b[1]
60}
61fn cross(a: P, b: P) -> f64 {
62    a[0] * b[1] - a[1] * b[0]
63}
64fn norm(a: P) -> f64 {
65    a[0].hypot(a[1])
66}
67fn dist(a: P, b: P) -> f64 {
68    norm(sub(a, b))
69}
70
71/// A carrier of the region's boundary: a segment, or an arc counter-clockwise from `a0` through
72/// `span` (a whole circle when `span` is TAU). Parameter t in [0, 1].
73#[derive(Clone, Copy, Debug)]
74enum Carrier {
75    Seg { a: P, b: P },
76    Arc { c: P, r: f64, a0: f64, span: f64 },
77}
78
79impl Carrier {
80    fn at(&self, t: f64) -> P {
81        match *self {
82            Carrier::Seg { a, b } => add(a, scale(sub(b, a), t)),
83            Carrier::Arc { c, r, a0, span } => {
84                let angle = a0 + span * t;
85                [c[0] + r * angle.cos(), c[1] + r * angle.sin()]
86            }
87        }
88    }
89    /// The direction of increasing t (not unit).
90    fn tangent(&self, t: f64) -> P {
91        match *self {
92            Carrier::Seg { a, b } => sub(b, a),
93            Carrier::Arc { r, a0, span, .. } => {
94                let angle = a0 + span * t;
95                [-r * span * angle.sin(), r * span * angle.cos()]
96            }
97        }
98    }
99    fn whole_circle(&self) -> bool {
100        matches!(*self, Carrier::Arc { span, .. } if span >= TAU - 1e-12)
101    }
102    /// The parameter of `p`, where `p` lies on the carrier within `tol`.
103    fn param_of(&self, p: P, tol: f64) -> Option<f64> {
104        match *self {
105            Carrier::Seg { a, b } => {
106                let d = sub(b, a);
107                let length = norm(d);
108                let t = dot(sub(p, a), d) / (length * length);
109                let foot = add(a, scale(d, t));
110                let slack = tol / length;
111                (dist(foot, p) <= tol && t >= -slack && t <= 1.0 + slack).then(|| t.clamp(0.0, 1.0))
112            }
113            Carrier::Arc { c, r, a0, span } => {
114                if (dist(p, c) - r).abs() > tol {
115                    return None;
116                }
117                let angle = (p[1] - c[1]).atan2(p[0] - c[0]);
118                let mut t = (angle - a0).rem_euclid(TAU) / span;
119                if self.whole_circle() {
120                    return Some(t.rem_euclid(1.0));
121                }
122                let slack = tol / (r * span);
123                if t > 1.0 + slack {
124                    // past the end: near the start from below?
125                    let before = t - TAU / span;
126                    if before >= -slack {
127                        t = 0.0;
128                    } else {
129                        return None;
130                    }
131                }
132                Some(t.clamp(0.0, 1.0))
133            }
134        }
135    }
136}
137
138/// The distance from `q` to the move's path.
139fn move_distance(m: &MillMove, q: P) -> f64 {
140    match *m {
141        MillMove::Line { from, to } => {
142            let d = sub(to, from);
143            let ll = dot(d, d);
144            if ll == 0.0 {
145                return dist(q, from);
146            }
147            let t = (dot(sub(q, from), d) / ll).clamp(0.0, 1.0);
148            dist(q, add(from, scale(d, t)))
149        }
150        MillMove::Arc { centre, radius, start, sweep } => {
151            let (a0, span) = if sweep >= 0.0 { (start, sweep) } else { (start + sweep, -sweep) };
152            let angle = (q[1] - centre[1]).atan2(q[0] - centre[0]);
153            if span >= TAU || (angle - a0).rem_euclid(TAU) <= span {
154                (dist(q, centre) - radius).abs()
155            } else {
156                let end = |a: f64| [centre[0] + radius * a.cos(), centre[1] + radius * a.sin()];
157                dist(q, end(a0)).min(dist(q, end(a0 + span)))
158            }
159        }
160    }
161}
162
163/// Where the carriers `x` and `y` cross or touch (within `tol`).
164fn meetings(x: &Carrier, y: &Carrier, tol: f64) -> Vec<P> {
165    let line_circle = |a: P, b: P, c: P, r: f64| -> Vec<P> {
166        let d = sub(b, a);
167        let length = norm(d);
168        let u = scale(d, 1.0 / length);
169        let foot = add(a, scale(u, dot(sub(c, a), u)));
170        let h = dist(foot, c);
171        if h > r + tol {
172            Vec::new()
173        } else if (h - r).abs() <= tol {
174            vec![foot]
175        } else {
176            let k = (r * r - h * h).sqrt();
177            vec![add(foot, scale(u, k)), sub(foot, scale(u, k))]
178        }
179    };
180    match (*x, *y) {
181        (Carrier::Seg { a: p0, b: p1 }, Carrier::Seg { a: q0, b: q1 }) => {
182            let (d1, d2) = (sub(p1, p0), sub(q1, q0));
183            let det = cross(d1, d2);
184            if det.abs() < 1e-15 * norm(d1) * norm(d2) {
185                return Vec::new();
186            }
187            let r = sub(q0, p0);
188            let s = cross(r, d2) / det;
189            vec![add(p0, scale(d1, s))]
190        }
191        (Carrier::Seg { a, b }, Carrier::Arc { c, r, .. }) | (Carrier::Arc { c, r, .. }, Carrier::Seg { a, b }) => line_circle(a, b, c, r),
192        (Carrier::Arc { c: c1, r: r1, .. }, Carrier::Arc { c: c2, r: r2, .. }) => {
193            let d = dist(c1, c2);
194            if d <= tol {
195                return Vec::new();
196            }
197            let u = scale(sub(c2, c1), 1.0 / d);
198            if (d - (r1 + r2)).abs() <= tol {
199                return vec![add(c1, scale(u, r1))];
200            }
201            if (d - (r1 - r2).abs()).abs() <= tol {
202                let sign = if r1 >= r2 { 1.0 } else { -1.0 };
203                return vec![add(c1, scale(u, sign * r1))];
204            }
205            if d > r1 + r2 || d < (r1 - r2).abs() {
206                return Vec::new();
207            }
208            let along = (d * d + r1 * r1 - r2 * r2) / (2.0 * d);
209            let h = (r1 * r1 - along * along).max(0.0).sqrt();
210            let mid = add(c1, scale(u, along));
211            let n = [-u[1], u[0]];
212            vec![add(mid, scale(n, h)), sub(mid, scale(n, h))]
213        }
214    }
215}
216
217/// A piece of a carrier from t0 to t1 (t1 may pass 1 on a whole circle), traversed forward or back.
218#[derive(Clone, Copy, Debug)]
219struct Piece {
220    carrier: usize,
221    t0: f64,
222    t1: f64,
223    forward: bool,
224}
225
226/// The region an upright flat-bottomed cutter of `radius` covers as its axis runs `moves` (all at
227/// one level), extruded from `bottom` to `top`: one prism for each connected part of the region
228/// (its holes through it). The moves' order does not matter.
229pub fn flat_mill_region_prisms(moves: &[MillMove], radius: f64, bottom: f64, top: f64) -> Result<Vec<BrepSolid>, KernelRefusal> {
230    if moves.is_empty() {
231        return Err(input("moves", "no moves".into()));
232    }
233    if !(radius.is_finite() && radius > 0.0) {
234        return Err(input("radius", "the cutter's radius must be positive".into()));
235    }
236    if !(bottom.is_finite() && top.is_finite() && top > bottom) {
237        return Err(input("levels", "the top must lie above the bottom".into()));
238    }
239    // The moves' box: worked about its centre (exactly translated back in the prism), tolerances
240    // read from its size, so that the result does not depend on where the moves lie.
241    let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
242    let mut grow = |q: P, pad: f64| {
243        for k in 0..2 {
244            lo[k] = lo[k].min(q[k] - pad);
245            hi[k] = hi[k].max(q[k] + pad);
246        }
247    };
248    for m in moves {
249        match *m {
250            MillMove::Line { from, to } => {
251                if !(from.iter().chain(to.iter()).all(|v| v.is_finite())) {
252                    return Err(input("line", "a move's ends must be finite".into()));
253                }
254                grow(from, radius);
255                grow(to, radius);
256            }
257            MillMove::Arc { centre, radius: ar, start, sweep } => {
258                if !(ar.is_finite() && ar > 0.0 && sweep.is_finite() && sweep != 0.0 && start.is_finite() && centre.iter().all(|v| v.is_finite())) {
259                    return Err(input("arc", "an arc move needs a positive radius and a sweep".into()));
260                }
261                grow(centre, ar + radius);
262            }
263        }
264    }
265    let origin: P = [0.5 * (lo[0] + hi[0]), 0.5 * (lo[1] + hi[1])];
266    let scale_len = (hi[0] - lo[0]).hypot(hi[1] - lo[1]).max(radius);
267    let local: Vec<MillMove> = moves
268        .iter()
269        .map(|m| match *m {
270            MillMove::Line { from, to } => MillMove::Line { from: sub(from, origin), to: sub(to, origin) },
271            MillMove::Arc { centre, radius, start, sweep } => MillMove::Arc { centre: sub(centre, origin), radius, start, sweep },
272        })
273        .collect();
274    let moves = &local[..];
275    // Merging and meeting tolerance: the cutter's size, not the moves' spread (two circles a unit
276    // apart stay apart however far the program reaches), floored at what the coordinates resolve.
277    let tol = (1e-9 * radius).max(1e-14 * scale_len);
278    // Carriers.
279    let mut carriers: Vec<Carrier> = Vec::new();
280    let circle = |c: P, r: f64, a0: f64, span: f64, carriers: &mut Vec<Carrier>| carriers.push(Carrier::Arc { c, r, a0, span });
281    for m in moves {
282        match *m {
283            MillMove::Line { from, to } => {
284                let d = sub(to, from);
285                let length = norm(d);
286                circle(from, radius, 0.0, TAU, &mut carriers);
287                if length > tol {
288                    let n = [-d[1] / length * radius, d[0] / length * radius];
289                    carriers.push(Carrier::Seg { a: add(from, n), b: add(to, n) });
290                    carriers.push(Carrier::Seg { a: sub(from, n), b: sub(to, n) });
291                    circle(to, radius, 0.0, TAU, &mut carriers);
292                }
293            }
294            MillMove::Arc { centre, radius: ar, start, sweep } => {
295                let (a0, span) = if sweep >= 0.0 { (start, sweep.min(TAU)) } else { (start + sweep, (-sweep).min(TAU)) };
296                circle(centre, ar + radius, a0, span, &mut carriers);
297                if ar - radius > tol {
298                    circle(centre, ar - radius, a0, span, &mut carriers);
299                }
300                for a in [start, start + sweep] {
301                    circle([centre[0] + ar * a.cos(), centre[1] + ar * a.sin()], radius, 0.0, TAU, &mut carriers);
302                }
303            }
304        }
305    }
306    let carriers = merge_carriers(carriers, tol);
307    // Cuts: ends, crossings and touches.
308    let mut cuts: Vec<Vec<f64>> = carriers.iter().map(|c| if c.whole_circle() { Vec::new() } else { vec![0.0, 1.0] }).collect();
309    let boxes: Vec<[f64; 4]> = carriers
310        .iter()
311        .map(|c| match *c {
312            Carrier::Seg { a, b } => [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])],
313            Carrier::Arc { c, r, .. } => [c[0] - r, c[1] - r, c[0] + r, c[1] + r],
314        })
315        .collect();
316    for i in 0..carriers.len() {
317        for j in i + 1..carriers.len() {
318            let (bi, bj) = (boxes[i], boxes[j]);
319            if bi[0] > bj[2] + tol || bj[0] > bi[2] + tol || bi[1] > bj[3] + tol || bj[1] > bi[3] + tol {
320                continue;
321            }
322            for p in meetings(&carriers[i], &carriers[j], tol) {
323                if let (Some(ti), Some(tj)) = (carriers[i].param_of(p, 1e3 * tol), carriers[j].param_of(p, 1e3 * tol)) {
324                    cuts[i].push(ti);
325                    cuts[j].push(tj);
326                }
327            }
328        }
329    }
330    // Pieces on the boundary, the region on their left.
331    let depth = |q: P| moves.iter().map(|m| move_distance(m, q)).fold(f64::INFINITY, f64::min) - radius;
332    // Probes stand off a piece by far less than the smallest feature (the cutter, every arc, every
333    // segment), so that none jumps a narrow hole or sliver.
334    let feature = carriers.iter().fold(radius, |m, c| match *c {
335        Carrier::Seg { a, b } => m.min(dist(a, b)),
336        Carrier::Arc { r, .. } => m.min(r),
337    });
338    // (The exact distance to the moves resolves far below this, about the box's centre; a gap or
339    // hole narrower than it is below the coordinates' resolution at this size.)
340    let probe = (1e-3 * feature).min(1e-10 * scale_len).max(1e-13 * scale_len);
341    let mut pieces: Vec<Piece> = Vec::new();
342    for (index, carrier) in carriers.iter().enumerate() {
343        let c = &mut cuts[index];
344        c.sort_by(f64::total_cmp);
345        c.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
346        let mut spans: Vec<(f64, f64)> = c.windows(2).map(|w| (w[0], w[1])).collect();
347        if carrier.whole_circle() {
348            match c.len() {
349                0 => spans.push((0.0, 1.0)),
350                _ => spans.push((c[c.len() - 1], c[0] + 1.0)),
351            }
352        }
353        for (t0, t1) in spans {
354            if t1 - t0 < 1e-12 || dist(carrier.at(t0), carrier.at(t1)) < tol && !(carrier.whole_circle() && (t1 - t0) > 0.5) {
355                continue;
356            }
357            let mut sides = Vec::new();
358            for f in [1.0 / 3.0, 2.0 / 3.0] {
359                let t = t0 + (t1 - t0) * f;
360                let (p, d) = (carrier.at(t), carrier.tangent(t));
361                let n = scale([-d[1], d[0]], probe / norm(d));
362                let (left, right) = (depth(add(p, n)) < 0.0, depth(sub(p, n)) < 0.0);
363                sides.push(match (left, right) {
364                    (true, false) => Some(true),
365                    (false, true) => Some(false),
366                    _ => None,
367                });
368            }
369            match (sides[0], sides[1]) {
370                (Some(a), Some(b)) if a == b => pieces.push(Piece { carrier: index, t0, t1, forward: a }),
371                (None, None) => {}
372                _ => return Err(refuse("mill_region_piece", "a piece of the region's boundary is on the boundary only in part".into())),
373            }
374        }
375    }
376    if pieces.is_empty() {
377        return Err(refuse("mill_region_empty", "no boundary found".into()));
378    }
379    let start_of = |p: &Piece| carriers[p.carrier].at(if p.forward { p.t0 } else { p.t1 });
380    let end_of = |p: &Piece| carriers[p.carrier].at(if p.forward { p.t1 } else { p.t0 });
381    let dir_at = |p: &Piece, at_start: bool| -> P {
382        let t = if at_start == p.forward { p.t0 } else { p.t1 };
383        let d = carriers[p.carrier].tangent(t);
384        if p.forward { d } else { scale(d, -1.0) }
385    };
386    // Loops: at a junction take the piece turning furthest right (keeps touching parts apart).
387    let join = 1e3 * tol;
388    let mut used = vec![false; pieces.len()];
389    let mut loops: Vec<Vec<usize>> = Vec::new();
390    while let Some(first) = (0..pieces.len()).find(|&k| !used[k]) {
391        used[first] = true;
392        let mut order = vec![first];
393        let origin = start_of(&pieces[first]);
394        loop {
395            let last = &pieces[*order.last().unwrap()];
396            let end = end_of(last);
397            if dist(end, origin) < join && order.len() > 0 && (order.len() > 1 || carriers[last.carrier].whole_circle() || dist(start_of(last), end) < join) {
398                break;
399            }
400            let incoming = dir_at(last, false);
401            let next = (0..pieces.len())
402                .filter(|&k| !used[k] && dist(start_of(&pieces[k]), end) < join)
403                .min_by(|&x, &y| {
404                    let turn = |k: usize| {
405                        let out = dir_at(&pieces[k], true);
406                        cross(incoming, out).atan2(dot(incoming, out))
407                    };
408                    turn(x).total_cmp(&turn(y))
409                });
410            let Some(next) = next else {
411                return Err(refuse("mill_region_open", "the region's boundary does not close".into()));
412            };
413            used[next] = true;
414            order.push(next);
415        }
416        loops.push(order);
417    }
418    // Sampled polygons: orientation and nesting.
419    let polygon = |order: &Vec<usize>| -> Vec<P> {
420        let mut points = Vec::new();
421        for &k in order {
422            let p = &pieces[k];
423            for i in 0..32 {
424                let f = i as f64 / 32.0;
425                let t = if p.forward { p.t0 + (p.t1 - p.t0) * f } else { p.t1 - (p.t1 - p.t0) * f };
426                points.push(carriers[p.carrier].at(t));
427            }
428        }
429        points
430    };
431    let polygons: Vec<Vec<P>> = loops.iter().map(polygon).collect();
432    let area = |poly: &Vec<P>| (0..poly.len()).map(|i| cross(poly[i], poly[(i + 1) % poly.len()])).sum::<f64>() * 0.5;
433    let areas: Vec<f64> = polygons.iter().map(area).collect();
434    let inside = |poly: &Vec<P>, q: P| {
435        let mut inside = false;
436        for i in 0..poly.len() {
437            let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
438            if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
439                inside = !inside;
440            }
441        }
442        inside
443    };
444    let outers: Vec<usize> = (0..loops.len()).filter(|&k| areas[k] > 0.0).collect();
445    let mut holes_of: Vec<Vec<usize>> = vec![Vec::new(); loops.len()];
446    for hole in (0..loops.len()).filter(|&k| areas[k] <= 0.0) {
447        let q = polygons[hole][0];
448        let host = outers.iter().copied().filter(|&o| inside(&polygons[o], q)).min_by(|&x, &y| areas[x].total_cmp(&areas[y]));
449        let Some(host) = host else {
450            return Err(refuse("mill_region_hole", "a hole of the region lies in no outer loop".into()));
451        };
452        holes_of[host].push(hole);
453    }
454    let mut solids = Vec::with_capacity(outers.len());
455    for &outer in &outers {
456        let mut part = vec![loops[outer].clone()];
457        part.extend(holes_of[outer].iter().map(|&h| loops[h].clone()));
458        solids.push(prism(&carriers, &pieces, &part, bottom, top, origin)?);
459    }
460    Ok(solids)
461}
462
463/// Carriers on one line (segments) or one circle (arcs) merged: overlapping segments into one, arcs
464/// into the circle's covered arcs (a whole circle where any is whole).
465fn merge_carriers(carriers: Vec<Carrier>, tol: f64) -> Vec<Carrier> {
466    let mut out: Vec<Carrier> = Vec::new();
467    // Circles.
468    let mut circles: Vec<(P, f64, Vec<(f64, f64)>)> = Vec::new();
469    let mut lines: Vec<(P, P, Vec<(f64, f64)>)> = Vec::new(); // (point on line, unit direction, intervals)
470    for c in carriers {
471        match c {
472            Carrier::Arc { c, r, a0, span } => {
473                let found = circles.iter_mut().find(|(cc, rr, _)| dist(*cc, c) <= tol && (rr - r).abs() <= tol);
474                let a0 = a0.rem_euclid(TAU);
475                match found {
476                    Some(entry) => entry.2.push((a0, span)),
477                    None => circles.push((c, r, vec![(a0, span)])),
478                }
479            }
480            Carrier::Seg { a, b } => {
481                let d = sub(b, a);
482                let l = norm(d);
483                let mut u = scale(d, 1.0 / l);
484                if u[0] < -1e-12 || (u[0].abs() <= 1e-12 && u[1] < 0.0) {
485                    u = scale(u, -1.0);
486                }
487                let found = lines.iter_mut().find(|(o, uu, _)| (cross(*uu, u)).abs() <= 1e-12 && cross(*uu, sub(a, *o)).abs() <= tol);
488                let (sa, sb) = match &found {
489                    Some((o, uu, _)) => (dot(sub(a, *o), *uu), dot(sub(b, *o), *uu)),
490                    None => (0.0, dot(sub(b, a), u)),
491                };
492                let iv = (sa.min(sb), sa.max(sb));
493                match found {
494                    Some(entry) => entry.2.push(iv),
495                    None => lines.push((a, u, vec![iv])),
496                }
497            }
498        }
499    }
500    for (c, r, arcs) in circles {
501        if arcs.iter().any(|&(_, s)| s >= TAU - 1e-12) {
502            out.push(Carrier::Arc { c, r, a0: 0.0, span: TAU });
503            continue;
504        }
505        // Union of arcs on the circle: each cut at TAU into pieces within [0, TAU], merged on the
506        // line, then the piece ending at TAU joined to the one starting at 0 (one arc across 0).
507        let mut pieces: Vec<(f64, f64)> = Vec::new();
508        for (a0, span) in arcs {
509            let (s0, e0) = (a0.rem_euclid(TAU), a0.rem_euclid(TAU) + span);
510            if e0 > TAU {
511                pieces.push((s0, TAU));
512                pieces.push((0.0, e0 - TAU));
513            } else {
514                pieces.push((s0, e0));
515            }
516        }
517        pieces.sort_by(|x, y| x.0.total_cmp(&y.0));
518        let mut merged: Vec<(f64, f64)> = Vec::new();
519        for (s, e) in pieces {
520            if let Some(last) = merged.last_mut() {
521                if s <= last.1 + 1e-12 {
522                    last.1 = last.1.max(e);
523                    continue;
524                }
525            }
526            merged.push((s, e));
527        }
528        if merged.len() == 1 && merged[0].0 <= 1e-12 && merged[0].1 >= TAU - 1e-12 {
529            out.push(Carrier::Arc { c, r, a0: 0.0, span: TAU });
530            continue;
531        }
532        if merged.len() > 1 && merged[0].0 <= 1e-12 && merged[merged.len() - 1].1 >= TAU - 1e-12 {
533            let first = merged.remove(0);
534            merged.last_mut().unwrap().1 = first.1 + TAU;
535        }
536        for (s, e) in merged {
537            let span = (e - s).min(TAU);
538            out.push(Carrier::Arc { c, r, a0: s, span });
539        }
540    }
541    for (o, u, mut ivs) in lines {
542        ivs.sort_by(|x, y| x.0.total_cmp(&y.0));
543        let mut merged: Vec<(f64, f64)> = Vec::new();
544        for (s, e) in ivs {
545            if let Some(last) = merged.last_mut() {
546                if s <= last.1 + tol {
547                    last.1 = last.1.max(e);
548                    continue;
549                }
550            }
551            merged.push((s, e));
552        }
553        for (s, e) in merged {
554            out.push(Carrier::Seg { a: add(o, scale(u, s)), b: add(o, scale(u, e)) });
555        }
556    }
557    out
558}
559
560/// One prism: `loops` (the outer loop first) of pieces, from `bottom` to `top`.
561fn prism(carriers: &[Carrier], pieces: &[Piece], loops: &[Vec<usize>], bottom: f64, top: f64, origin: P) -> Result<BrepSolid, KernelRefusal> {
562    let (ex, ey, ez) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
563    let world = |q: P, h: f64| Vec3::new(q[0] + origin[0], q[1] + origin[1], h);
564    // The piece's curve at height h, in its direction of travel.
565    let curve = |piece: &Piece, h: f64| -> Result<NurbsCurve, KernelRefusal> {
566        let carrier = &carriers[piece.carrier];
567        let (p0, p1) = (carrier.at(piece.t0), carrier.at(piece.t1));
568        match *carrier {
569            Carrier::Seg { .. } => {
570                let (a, b) = if piece.forward { (p0, p1) } else { (p1, p0) };
571                frag(make_line(world(a, h), world(b, h)), "mill_line")
572            }
573            Carrier::Arc { c, r, a0, span } => {
574                let (s, e) = (a0 + span * piece.t0, a0 + span * piece.t1);
575                let arc = frag(make_arc(world(c, h), ex, ey, r, s, e), "mill_arc")?;
576                if piece.forward { Ok(arc) } else { frag(arc.reversed(), "mill_arc") }
577            }
578        }
579    };
580    let mut shell = Shell::new();
581    let mut top_loops = Vec::new();
582    let mut bottom_loops = Vec::new();
583    let mut extent: Vec<P> = Vec::new();
584    for order in loops {
585        let count = order.len();
586        let corners: Vec<P> = order
587            .iter()
588            .map(|&k| {
589                let p = &pieces[k];
590                carriers[p.carrier].at(if p.forward { p.t0 } else { p.t1 })
591            })
592            .collect();
593        extent.extend(corners.iter().copied());
594        for &k in order {
595            if let Carrier::Arc { c, r, .. } = carriers[pieces[k].carrier] {
596                extent.extend([[c[0] - r, c[1] - r], [c[0] + r, c[1] + r]]);
597            }
598        }
599        let (bottom_v, top_v): (Vec<u64>, Vec<u64>) = corners.iter().map(|&q| (shell.vertex(world(q, bottom)), shell.vertex(world(q, top)))).unzip();
600        let mut bottom_e = Vec::with_capacity(count);
601        let mut top_e = Vec::with_capacity(count);
602        let mut curves = Vec::with_capacity(count);
603        for (slot, &k) in order.iter().enumerate() {
604            let next = (slot + 1) % count;
605            let (cb, ct) = (curve(&pieces[k], bottom)?, curve(&pieces[k], top)?);
606            bottom_e.push(shell.edge(cb.clone(), bottom_v[slot], bottom_v[next])?);
607            top_e.push(shell.edge(ct.clone(), top_v[slot], top_v[next])?);
608            curves.push((cb, ct));
609        }
610        let verticals: Vec<u64> = (0..count)
611            .map(|k| shell.edge(frag(make_line(world(corners[k], bottom), world(corners[k], top)), "mill_vertical")?, bottom_v[k], top_v[k]))
612            .collect::<Result<_, _>>()?;
613        top_loops.push((0..count).map(|k| Ok((top_e[k], true, plane_pcurve(world([0.0, 0.0], top), ex, ey, &curves[k].1, true)?))).collect::<Result<Vec<_>, KernelRefusal>>()?);
614        bottom_loops.push((0..count).rev().map(|k| Ok((bottom_e[k], false, plane_pcurve(world([0.0, 0.0], bottom), ey, ex, &curves[k].0, false)?))).collect::<Result<Vec<_>, KernelRefusal>>()?);
615        for k in 0..count {
616            let next = (k + 1) % count;
617            let cb = &curves[k].0;
618            let rows: Vec<Vec<Vec4>> = cb
619                .control_points
620                .iter()
621                .map(|p| {
622                    let x = p.point().expect("a control point");
623                    vec![Vec4::from_point(x, p.w), Vec4::from_point(x.add(ez.scale(top - bottom)), p.w)]
624                })
625                .collect();
626            let surface = frag(NurbsSurface::new(cb.degree, 1, cb.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows), "mill_wall")?;
627            let [u0, u1] = frag(cb.domain(), "mill_domain")?;
628            shell.face(
629                surface,
630                vec![
631                    (bottom_e[k], true, uv_line([u0, 0.0], [u1, 0.0])?),
632                    (verticals[next], true, uv_line([u1, 0.0], [u1, 1.0])?),
633                    (top_e[k], false, uv_line([u1, 1.0], [u0, 1.0])?),
634                    (verticals[k], false, uv_line([u0, 1.0], [u0, 0.0])?),
635                ],
636            );
637        }
638    }
639    let (lo, hi) = extent.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), q| ([lo[0].min(q[0]), lo[1].min(q[1])], [hi[0].max(q[0]), hi[1].max(q[1])]));
640    shell.face_loops(plane_patch(world([0.0, 0.0], top), ex, ey, lo, hi)?, top_loops);
641    shell.face_loops(plane_patch(world([0.0, 0.0], bottom), ey, ex, [lo[1], lo[0]], [hi[1], hi[0]])?, bottom_loops);
642    let body = shell.solid();
643    if let Some(issue) = body.validate().first() {
644        return Err(refuse("mill_region_assembly", format!("the region's prism is not valid: {}", issue.message)));
645    }
646    Ok(body)
647}
648
649fn uv_line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
650    frag(make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)), "pcurve")
651}
652
653/// The plane through `origin` spanned by unit `u`, `v`, over the box `lo`..`hi` of (u, v).
654fn plane_patch(origin: Vec3, u: Vec3, v: Vec3, lo: [f64; 2], hi: [f64; 2]) -> Result<NurbsSurface, KernelRefusal> {
655    let (lo, hi) = ([lo[0] - 1.0, lo[1] - 1.0], [hi[0] + 1.0, hi[1] + 1.0]);
656    let at = |s: f64, t: f64| Vec4::from_point(origin.add(u.scale(s)).add(v.scale(t)), 1.0);
657    frag(
658        NurbsSurface::new(
659            1,
660            1,
661            vec![lo[0], lo[0], hi[0], hi[0]],
662            vec![lo[1], lo[1], hi[1], hi[1]],
663            vec![vec![at(lo[0], lo[1]), at(lo[0], hi[1])], vec![at(hi[0], lo[1]), at(hi[0], hi[1])]],
664        ),
665        "mill_plane",
666    )
667}
668
669fn plane_pcurve(origin: Vec3, u: Vec3, v: Vec3, curve: &NurbsCurve, forward: bool) -> Result<NurbsCurve, KernelRefusal> {
670    let mut points = Vec::with_capacity(curve.control_points.len());
671    for p in &curve.control_points {
672        let x = frag(p.point(), "control_point")?.sub(origin);
673        points.push(Vec4::from_point(Vec3::new(x.dot(u), x.dot(v), 0.0), p.w));
674    }
675    let pcurve = frag(NurbsCurve::new(curve.degree, curve.knots.clone(), points), "plane_pcurve")?;
676    if forward { Ok(pcurve) } else { frag(pcurve.reversed(), "plane_pcurve") }
677}
678
679struct Shell {
680    vertices: Vec<VertexRecord>,
681    edges: Vec<EdgeRecord>,
682    faces: Vec<FaceRecord>,
683    next: u64,
684    holes: usize,
685}
686
687impl Shell {
688    fn new() -> Self {
689        Self { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 1, holes: 0 }
690    }
691    fn id(&mut self) -> u64 {
692        self.next += 1;
693        self.next
694    }
695    fn vertex(&mut self, point: Vec3) -> u64 {
696        let id = self.id();
697        self.vertices.push(VertexRecord { id, point });
698        id
699    }
700    fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64) -> Result<u64, KernelRefusal> {
701        let domain = frag(curve.domain(), "edge_domain")?;
702        let id = self.id();
703        self.edges.push(EdgeRecord { id, curve, t0: domain[0], t1: domain[1], start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
704        Ok(id)
705    }
706    fn face(&mut self, surface: NurbsSurface, coedges: Vec<(u64, bool, NurbsCurve)>) {
707        self.face_loops(surface, vec![coedges]);
708    }
709    fn face_loops(&mut self, surface: NurbsSurface, loops: Vec<Vec<(u64, bool, NurbsCurve)>>) {
710        let mut records = Vec::with_capacity(loops.len());
711        for coedges in loops {
712            let mut list = Vec::with_capacity(coedges.len());
713            for (edge, forward, pcurve) in coedges {
714                let id = self.id();
715                list.push(CoedgeRecord { id, edge_id: edge, forward, pcurve });
716            }
717            let id = self.id();
718            records.push(LoopRecord { id, coedges: list });
719        }
720        self.holes += records.len().saturating_sub(1);
721        let id = self.id();
722        self.faces.push(FaceRecord { id, surface, same_sense: true, loops: records, name: None });
723    }
724    fn solid(mut self) -> BrepSolid {
725        let shell = self.id();
726        let id = self.id();
727        let euler = self.vertices.len() as i64 - self.edges.len() as i64 + self.faces.len() as i64 - self.holes as i64;
728        BrepSolid {
729            mass_properties_cache: Default::default(),
730            id,
731            vertices: self.vertices,
732            edges: self.edges,
733            shells: vec![ShellRecord { id: shell, faces: self.faces }],
734            genus: (2 - euler) / 2,
735            kind: Default::default(),
736            cells: Default::default(),
737        }
738    }
739}
740