BREP_boolean 0.35.0

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! `body − drill`, where the drill is a whole cylinder and every body face it
//! reaches is a plane square to its axis that contains the drill's whole
//! section with room to spare: a through hole (or a hole through several
//! walls). Each crossed face gains a circular hole loop and each stretch of
//! material the drill passes gains one cylindrical face on the drill's own
//! side surface, bounded by two of that surface's own circles and its seam.
//!
//! The rule answers only when it can show, in closed form, that the drill
//! touches nothing else:
//! - every other face is clear of the drill by more than the decline margin
//!   (beyond an end along the axis, across a separating direction in the
//!   plane square to the axis, or a parallel cylinder nested with or apart
//!   from the drill);
//! - on a crossed face, every boundary edge stays more than the drill radius
//!   plus the margin from the drill's axis, and the axis point is inside the
//!   face;
//! - the crossed faces alternate entering and leaving material along the
//!   axis, starting and ending outside it.
//! Everything else is declined, including every near-tangent or flush
//! configuration inside the margin.
use super::{Built, Decline};
use crate::classification::{parameter_point_in_face, PolygonClass};
use crate::topology::{
    BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, HashMap, HashSet, LoopRecord, VertexRecord,
};
use crate::curve::parameter_line;
use crate::{make_line, AnalyticSurface, KernelTolerances, NurbsCurve, Vec2, Vec3, Vec4};

/// A whole cylinder as a primitive builds it: one side face on a ruled
/// revolution between two flat caps.
struct Drill<'a> {
    side: &'a FaceRecord,
    /// The name of the side's seam edge.
    seam_name: Option<&'a str>,
    /// The axis point at the side surface's `v = 0` end.
    base: Vec3,
    /// Unit, from the `v = 0` end to the `v = 1` end.
    axis: Vec3,
    radius: f64,
    height: f64,
}

impl Drill<'_> {
    fn axial(&self, point: Vec3) -> f64 {
        point.sub(self.base).dot(self.axis)
    }

    fn radial(&self, point: Vec3) -> Vec3 {
        let offset = point.sub(self.base);
        offset.sub(self.axis.scale(offset.dot(self.axis)))
    }
}

pub(super) fn unit_domain(knots: &[f64], degree: usize) -> bool {
    knots.len() > 2 * degree + 1 && knots[degree] == 0.0 && knots[knots.len() - 1 - degree] == 1.0
}

fn recognise(tool: &BrepSolid) -> Result<Drill<'_>, Decline> {
    const NOT: Decline = "the tool is not a whole cylinder";
    let [shell] = tool.shells.as_slice() else { return Err(NOT) };
    if shell.faces.len() != 3 || tool.edges.len() != 3 || tool.vertices.len() != 2 || tool.genus != 0 {
        return Err(NOT);
    }
    let mut sides = shell.faces.iter().filter(|face| super::carrier_kind(&face.surface) == "cylinder");
    let (Some(side), None) = (sides.next(), sides.next()) else { return Err(NOT) };
    let Some(AnalyticSurface::RuledRevolution { frame, rho0, .. }) = side.surface.analytic() else { return Err(NOT) };
    let surface = &side.surface;
    if !side.same_sense
        || side.loops.len() != 1
        || side.loops[0].coedges.len() != 4
        || !unit_domain(&surface.knots_u, surface.degree_u)
        || !unit_domain(&surface.knots_v, surface.degree_v)
    {
        return Err(NOT);
    }
    let at = |u: f64, v: f64| surface.evaluate(u, v).map_err(|_| NOT);
    let (low, high) = (at(0.0, 0.0)?, at(0.0, 1.0)?);
    let generatrix = high.sub(low);
    let mut axis = frame.axis;
    let mut height = generatrix.dot(axis);
    if height < 0.0 {
        axis = axis.scale(-1.0);
        height = -height;
    }
    let base = frame.origin.add(axis.scale(low.sub(frame.origin).dot(axis)));
    let radius = low.sub(base).length();
    let scale = radius.max(height);
    let exact = 1e-10 * scale;
    if !(height > 0.0 && radius > 0.0)
        || generatrix.sub(axis.scale(height)).length() > exact
        || (radius - rho0).abs() > exact
    {
        return Err(NOT);
    }
    let seam_name = side.loops[0]
        .coedges
        .iter()
        .filter_map(|coedge| tool.edges.iter().find(|edge| edge.id == coedge.edge_id))
        .find(|edge| edge.start_vertex_id != edge.end_vertex_id)
        .ok_or(NOT)?
        .name
        .as_deref();
    let drill = Drill { side, seam_name, base, axis, radius, height };
    // The side's natural normal points away from the axis, so with
    // `same_sense` the material is the inside of the cylinder.
    let middle = at(0.0, 0.5)?;
    let around = at(1.0 / 64.0, 0.5)?.sub(middle);
    if around.cross(generatrix).dot(drill.radial(middle)) <= 0.0 {
        return Err(NOT);
    }
    // The two rims are the side surface's own end circles, each the whole
    // boundary of a flat cap square to the axis.
    let mut ends = [false; 2];
    for cap in shell.faces.iter().filter(|face| !std::ptr::eq(*face, side)) {
        let Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = cap.surface.analytic() else { return Err(NOT) };
        let normal = u_dir.cross(*v_dir).normalized().map_err(|_| NOT)?;
        let [ring] = cap.loops.as_slice() else { return Err(NOT) };
        let [coedge] = ring.coedges.as_slice() else { return Err(NOT) };
        let Some(rim) = tool.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return Err(NOT) };
        if normal.dot(axis).abs() < 1.0 - 1e-12 || rim.start_vertex_id != rim.end_vertex_id || rim.degenerate {
            return Err(NOT);
        }
        let level = drill.axial(*origin);
        let end = if level.abs() <= exact { 0 } else if (level - height).abs() <= exact { 1 } else { return Err(NOT) };
        if std::mem::replace(&mut ends[end], true) || !side.loops[0].coedges.iter().any(|side_coedge| side_coedge.edge_id == rim.id) {
            return Err(NOT);
        }
        for step in 0..8 {
            let point = rim.curve.evaluate(rim.t0 + (rim.t1 - rim.t0) * step as f64 / 8.0).map_err(|_| NOT)?;
            if (drill.axial(point) - level).abs() > exact || (drill.radial(point).length() - radius).abs() > exact {
                return Err(NOT);
            }
        }
    }
    Ok(drill)
}

/// A body face the drill passes through.
struct Crossing {
    shell: usize,
    face: usize,
    /// Along the drill's axis from its base.
    level: f64,
    /// Whether the face's outward normal points along the axis (the drill
    /// leaves material here) or against it (it enters).
    leaves: bool,
}

fn control_points(controls: impl Iterator<Item = Vec4>, into: &mut Vec<Vec3>) -> Result<(), Decline> {
    for control in controls {
        if !(control.w > 0.0) {
            return Err("a control point has no positive weight");
        }
        into.push(control.point().map_err(|_| "a control point is not finite")?);
    }
    Ok(())
}

/// A lower bound on the distance from `centre` to the edge, both in one plane
/// square to `axis`.
fn edge_clearance(edge: &EdgeRecord, centre: Vec3, axis: Vec3, scale: f64) -> Result<f64, Decline> {
    const BAD: Decline = "an edge of a crossed face does not evaluate";
    let curve = &edge.curve;
    if curve.degree == 1 && curve.control_points.len() == 2 {
        let start = curve.evaluate(edge.t0).map_err(|_| BAD)?;
        let end = curve.evaluate(edge.t1).map_err(|_| BAD)?;
        return Ok(centre.distance_to_segment_squared(start, end).sqrt());
    }
    if let Some(circle) = crate::recognize_circle(curve, edge.t0, edge.t1, 1e-10 * scale) {
        if circle.axis.dot(axis).abs() > 1.0 - 1e-12 {
            // The whole circle, which the arc is part of.
            let offset = centre.sub(circle.centre);
            let in_plane = offset.sub(axis.scale(offset.dot(axis)));
            return Ok((in_plane.length() - circle.radius).abs());
        }
    }
    // Any other curve lies in the hull of its control points.
    let mut hull = Vec::new();
    control_points(curve.control_points.iter().copied(), &mut hull)?;
    let middle = hull.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, point| sum.add(*point)).scale(1.0 / hull.len() as f64);
    let reach = hull.iter().map(|point| point.sub(middle).length()).fold(0.0, f64::max);
    Ok(centre.sub(middle).length() - reach)
}

/// The faces of `body` the drill passes through, lowest first. An error
/// where the drill touches the body in any way the rule does not cover.
///
/// `tool_bounds`: an untouched face whose control-net box reaches these is
/// one the soundness scan must read with the wall (the pipeline leaves such
/// a face out only where its imprint proved the pair apart, which nothing
/// here can stand in for). With such a face the scan is no cheaper than the
/// pipeline's and can be dearer, so the rule declines.
fn crossings(body: &BrepSolid, drill: &Drill, margin: f64, policy: &KernelTolerances, tool_bounds: crate::Aabb) -> Result<Vec<Crossing>, Decline> {
    const REACHES: Decline = "an untouched face's box reaches the drill";
    let edges: HashMap<u64, &EdgeRecord> = body.edges.iter().map(|edge| (edge.id, edge)).collect();
    let reach = drill.radius + margin;
    let scale = drill.radius.max(drill.height);
    let mut found = Vec::new();
    let mut hull = Vec::new();
    for (shell_index, shell) in body.shells.iter().enumerate() {
        for (face_index, face) in shell.faces.iter().enumerate() {
            let analytic = face.surface.analytic();
            let reaches = !crate::Aabb::from_surface_controls(&face.surface).is_ok_and(|own| !own.intersects(tool_bounds, policy.sew_search));
            let plane = match analytic {
                Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
                    Some((*origin, *u_dir, *v_dir, u_dir.cross(*v_dir).normalized().map_err(|_| "a degenerate plane")?))
                }
                _ => None,
            };
            // A parallel cylinder apart from the drill, around it or inside
            // it by more than the margin does not touch it.
            if let Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, .. }) = analytic {
                if (rho0 - rho1).abs() <= 1e-12 * rho0.abs() && frame.axis.dot(drill.axis).abs() > 1.0 - 1e-12 {
                    let apart = drill.radial(frame.origin).length();
                    if apart > reach + rho0 || apart + reach < *rho0 {
                        if reaches {
                            return Err(REACHES);
                        }
                        continue;
                    }
                }
            }
            // The face lies in the hull of these points: a flat face in the
            // hull of its edges' control points, any other in its patch's.
            hull.clear();
            if plane.is_some() {
                for coedge in face.loops.iter().flat_map(|ring| &ring.coedges) {
                    let edge = edges.get(&coedge.edge_id).ok_or("a coedge names no edge")?;
                    control_points(edge.curve.control_points.iter().copied(), &mut hull)?;
                }
            } else {
                control_points(face.surface.control_points.iter().flatten().copied(), &mut hull)?;
            }
            if hull.is_empty() {
                return Err("a face without geometry");
            }
            if hull.iter().all(|point| drill.axial(*point) > drill.height + margin)
                || hull.iter().all(|point| drill.axial(*point) < -margin)
            {
                if reaches {
                    return Err(REACHES);
                }
                continue;
            }
            let radials: Vec<Vec3> = hull.iter().map(|point| drill.radial(*point)).collect();
            let mean = radials.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, radial| sum.add(*radial));
            let nearest = radials.iter().copied().min_by(|a, b| a.length_squared().total_cmp(&b.length_squared()));
            let wall = plane.map(|(_, _, _, normal)| normal).filter(|normal| normal.dot(drill.axis).abs() < 1e-12);
            let separated = [Some(mean), nearest, wall, wall.map(|normal| normal.scale(-1.0))].into_iter().flatten().any(|direction| {
                direction.normalized().is_ok_and(|direction| radials.iter().all(|radial| radial.dot(direction) > reach))
            });
            if separated {
                if reaches {
                    return Err(REACHES);
                }
                continue;
            }
            // Not shown clear: it must be a flat face square to the axis,
            // strictly between the drill's ends, holding the whole section.
            let Some((origin, u_dir, v_dir, normal)) = plane else { return Err("the drill reaches a face that is not flat") };
            let along = normal.dot(drill.axis);
            if along.abs() < 1.0 - 1e-12 {
                return Err("the drill reaches a flat face not square to its axis");
            }
            let level = drill.axial(origin);
            if !(level > margin && level < drill.height - margin) {
                return Err("a drill end is flush with or near a face");
            }
            let centre = drill.base.add(drill.axis.scale(level));
            for coedge in face.loops.iter().flat_map(|ring| &ring.coedges) {
                let edge = edges.get(&coedge.edge_id).ok_or("a coedge names no edge")?;
                if !(edge_clearance(edge, centre, drill.axis, scale)? > reach) {
                    return Err("the hole reaches or nears the boundary of a face");
                }
            }
            // No boundary point is within the drill's reach of the centre, so
            // the whole section is on the side of the boundary the centre is.
            let offset = centre.sub(origin);
            let (uu, uv, vv) = (u_dir.dot(u_dir), u_dir.dot(v_dir), v_dir.dot(v_dir));
            let determinant = uu * vv - uv * uv;
            if !(determinant > 0.0) {
                return Err("a degenerate plane");
            }
            let (pu, pv) = (offset.dot(u_dir), offset.dot(v_dir));
            let parameter = Vec2 { x: (pu * vv - pv * uv) / determinant, y: (pv * uu - pu * uv) / determinant };
            match parameter_point_in_face(face, parameter, policy.model) {
                Ok(PolygonClass::Inside) => {}
                Ok(PolygonClass::Outside) if !reaches => continue,
                Ok(PolygonClass::Outside) => return Err(REACHES),
                _ => return Err("the drill's axis is not clearly inside or outside a face"),
            }
            found.push(Crossing { shell: shell_index, face: face_index, level, leaves: (along > 0.0) == face.same_sense });
        }
    }
    found.sort_by(|a, b| a.level.total_cmp(&b.level));
    if found.is_empty() {
        return Err("the drill crosses no face");
    }
    if found.len() % 2 != 0 {
        return Err("a drill end is inside the body");
    }
    for (index, crossing) in found.iter().enumerate() {
        // A hole joining two shells (through a void) changes the shells.
        if crossing.shell != found[0].shell {
            return Err("the crossed faces are on different shells");
        }
        if crossing.leaves != (index % 2 == 1) {
            return Err("the crossed faces do not alternate");
        }
        if index > 0 && !(crossing.level - found[index - 1].level > margin) {
            return Err("two crossed faces are within the margin");
        }
    }
    Ok(found)
}

/// `curve` (on the plane `origin + u·u_dir + v·v_dir`) in the plane's
/// parameters: an affine map, so the control points map exactly.
pub(super) fn in_plane(curve: &NurbsCurve, origin: Vec3, u_dir: Vec3, v_dir: Vec3) -> Result<NurbsCurve, Decline> {
    let (uu, uv, vv) = (u_dir.dot(u_dir), u_dir.dot(v_dir), v_dir.dot(v_dir));
    let determinant = uu * vv - uv * uv;
    let mut controls = Vec::with_capacity(curve.control_points.len());
    for control in &curve.control_points {
        let offset = control.point().map_err(|_| "a control point is not finite")?.sub(origin);
        let (pu, pv) = (offset.dot(u_dir), offset.dot(v_dir));
        controls.push(Vec4 {
            x: (pu * vv - pv * uv) / determinant * control.w,
            y: (pv * uu - pu * uv) / determinant * control.w,
            z: 0.0,
            w: control.w,
        });
    }
    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).map_err(|_| "a plane pcurve does not build")
}

pub(super) fn subtract(body: &BrepSolid, tool: &BrepSolid, policy: &KernelTolerances) -> Result<Built, Decline> {
    let drill = recognise(tool)?;
    // The decline band: well above every band the pipeline snaps within, so
    // a configuration it could read as touching is never answered here.
    let margin = (1e3 * policy.sew_search).max(1e-4 * drill.radius);
    let tool_bounds = super::super::operand_bounds(tool);
    crossings(body, &drill, margin, policy, tool_bounds)?;
    // The operands as the pipeline would read them (healed, band seams
    // normalised), and the crossings again on that body.
    let (mut result, _) = super::super::prepared_operands(body, tool, policy).map_err(|_| "operand preparation refuses")?;
    let found = crossings(&result, &drill, margin, policy, tool_bounds)?;
    const BUILD: Decline = "the hole's geometry does not build";
    let surface = &drill.side.surface;
    let mut next_vertex = result.vertices.iter().map(|vertex| vertex.id).max().unwrap_or(0) + 1;
    let mut next_edge = result.edges.iter().map(|edge| edge.id).max().unwrap_or(0) + 1;
    // Face, loop and coedge ids are renumbered below.
    let base_circle = surface.iso_curve_v(0.0).map_err(|_| BUILD)?;
    let base_start = surface.evaluate(0.0, 0.0).map_err(|_| BUILD)?;
    let base_quarter = surface.evaluate(0.25, 0.0).map_err(|_| BUILD)?;
    let mut walls = Vec::new();
    let mut touched_at: Vec<(usize, usize)> = found.iter().map(|crossing| (crossing.shell, crossing.face)).collect();
    for (wall, pair) in found.chunks(2).enumerate() {
        let mut rims = Vec::new();
        for crossing in pair {
            // The side's base circle moved along the axis into the face's
            // plane: the side's own circle at this level, without the last
            // digits an evaluation at `v` would cost.
            let v = crossing.level / drill.height;
            let shift = drill.axis.scale(crossing.level);
            let circle = moved(&base_circle, shift)?;
            let start = base_start.add(shift);
            let quarter = base_quarter.add(shift);
            let centre = drill.base.add(shift);
            // Whether the circle runs anticlockwise about the axis.
            let anticlockwise = start.sub(centre).cross(quarter.sub(centre)).dot(drill.axis) > 0.0;
            let (vertex_id, edge_id) = (next_vertex, next_edge);
            next_vertex += 1;
            next_edge += 1;
            result.vertices.push(VertexRecord { id: vertex_id, point: start });
            let face = &mut result.shells[crossing.shell].faces[crossing.face];
            let Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = face.surface.analytic() else { return Err(BUILD) };
            // A hole's loop runs clockwise about the face's outward normal.
            let forward = anticlockwise != crossing.leaves;
            let flat = in_plane(&circle, *origin, *u_dir, *v_dir)?;
            let pcurve = if forward { flat } else { flat.reversed().map_err(|_| BUILD)? };
            face.loops.push(LoopRecord { id: 0, coedges: vec![CoedgeRecord { id: 0, edge_id, forward, pcurve }] });
            // A section edge is named after the two faces it is between,
            // where both have a name.
            let name = match (&face.name, &drill.side.name) {
                // (in the order the two names sort).
                (Some(a), Some(b)) => Some(if a <= b { format!("{a}|{b}") } else { format!("{b}|{a}") }),
                _ => None,
            };
            result.edges.push(EdgeRecord {
                id: edge_id,
                curve: circle,
                t0: 0.0,
                t1: 1.0,
                start_vertex_id: vertex_id,
                end_vertex_id: vertex_id,
                degenerate: false,
                name,
            });
            rims.push((vertex_id, edge_id, v, start));
        }
        let [(low_vertex, low_edge, low_v, low_point), (high_vertex, high_edge, high_v, high_point)] = rims[..] else { return Err(BUILD) };
        let seam_id = next_edge;
        next_edge += 1;
        result.edges.push(EdgeRecord {
            id: seam_id,
            curve: make_line(low_point, high_point).map_err(|_| BUILD)?,
            t0: 0.0,
            t1: 1.0,
            start_vertex_id: low_vertex,
            end_vertex_id: high_vertex,
            degenerate: false,
            // The crossings cut the drill's seam into pieces numbered from
            // its base; this wall's piece is the one after its lower rim.
            name: drill.seam_name.map(|seam| format!("{seam}_{}", 2 * wall + 1)),
        });
        let line = |u0: f64, v0: f64, u1: f64, v1: f64| parameter_line(u0, v0, u1, v1).map_err(|_| BUILD);
        // The drill's side with its sense turned: the mirror of the loop a
        // cylinder primitive's side carries.
        walls.push(FaceRecord {
            id: 0,
            surface: surface.clone(),
            same_sense: false,
            loops: vec![LoopRecord {
                id: 0,
                coedges: vec![
                    CoedgeRecord { id: 0, edge_id: low_edge, forward: false, pcurve: line(1.0, low_v, 0.0, low_v)? },
                    CoedgeRecord { id: 0, edge_id: seam_id, forward: true, pcurve: line(0.0, low_v, 0.0, high_v)? },
                    CoedgeRecord { id: 0, edge_id: high_edge, forward: true, pcurve: line(0.0, high_v, 1.0, high_v)? },
                    CoedgeRecord { id: 0, edge_id: seam_id, forward: false, pcurve: line(1.0, high_v, 1.0, low_v)? },
                ],
            }],
            // Pieces of one face after the first are numbered.
            name: drill.side.name.as_ref().map(|side| if wall == 0 { side.clone() } else { format!("{side}_{wall}") }),
        });
    }
    let Some(shell) = result.shells.get_mut(found[0].shell) else { return Err(BUILD) };
    let from_body: usize = body.shells.iter().map(|shell| shell.faces.len()).sum();
    touched_at.extend((0..walls.len()).map(|wall| (found[0].shell, shell.faces.len() + wall)));
    shell.faces.extend(walls);
    super::renumber(&mut result);
    result.mass_properties_cache = Default::default();
    super::super::refresh_derived_genus(&mut result);
    let touched = touched_at.iter().map(|(shell, face)| result.shells[*shell].faces[*face].id).collect();
    // The walls were appended to one shell; every other face is the body's.
    let wall_ids: HashSet<u64> =
        result.shells[found[0].shell].faces.iter().rev().take(found.len() / 2).map(|face| face.id).collect();
    let operand_of = result
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .map(|face| (face.id, u8::from(wall_ids.contains(&face.id))))
        .collect();
    debug_assert_eq!(result.shells.iter().map(|shell| shell.faces.len()).sum::<usize>(), from_body + found.len() / 2);
    Ok(Built { solid: result, touched, operand_of })
}

/// `curve` moved by `shift`.
fn moved(curve: &NurbsCurve, shift: Vec3) -> Result<NurbsCurve, Decline> {
    let controls = curve
        .control_points
        .iter()
        .map(|control| Vec4 {
            x: control.x + shift.x * control.w,
            y: control.y + shift.y * control.w,
            z: control.z + shift.z * control.w,
            w: control.w,
        })
        .collect();
    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).map_err(|_| "a moved circle does not build")
}