BREP_blend 0.34.0

Rust B-rep CAD kernel (next.BREP.io): fillets, chamfers and blends.
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
//! THE PINNED BALL: a selection that
//! holds the seam of a two-edge miter between two earlier rounds of the
//! fillet's own radius `r`, together with the edge the seam runs on into.
//!
//! A box corner whose two edges on one face were rounded at `r` (the third
//! edge left sharp) carries a miter: the two round walls, cylinders of radius
//! `r`, meet on a seam that leaves the sharp edge tangentially and closes
//! where the walls turn tangent, at the shared face. Rounding the third edge
//! at the same `r` with its tangent chain followed takes in that seam. A ball
//! of radius `r` rolling on two cylinders of radius `r` has its centre on both
//! axes: it is PINNED at the point `P` where they cross, and the seam's
//! blend is the sphere of radius `r` about `P` — the rounded box corner, what
//! the three edges rounded at once build. The march cannot step a ball that
//! does not move (its station Newton is singular), so the selection refused.
//!
//! Built here, after that refusal: the selection without the seam is rounded
//! (the third edge's wall runs through the corner as a third cylinder, the
//! three walls meeting pairwise on fitted seams at one point), then each
//! cylinder's run of corner seams is replaced by its exact section arc
//! through `P` and the sphere triangle those three arcs bound is added. The
//! arcs are the three cylinders' circles of contact with the ball, so every
//! new edge is G1 and the corner is the three-at-once rounded corner.
//!
//! The lane admits only what it can certify: both seam walls cylinders of
//! radius `r` whose axes cross at `P`, the seam's tangent end at `P + r·n`
//! with `n` normal to both axes, its other end on a selected edge between
//! two planes `r` from `P` running along `n` (the third wall's axis), and a
//! body that validates. Anything else keeps the refusal it came with.
//! `BREP_FILLET_PINNED_BALL=0` turns the lane off.

use super::*;
use crate::topology::{CoedgeRecord, LoopRecord};
use crate::{AnalyticSurface, NurbsSurface};

pub(super) fn pinned_ball_on() -> bool {
    crate::switch!("BREP_FILLET_PINNED_BALL", true)
}

/// One selected seam whose ball is pinned.
struct Pinned {
    index: usize,
    /// The ball's one centre.
    pin: Vec3,
    /// Unit direction from the pin to the seam's tangent end (the pole).
    polar: Vec3,
    /// The two seam walls' axes.
    axes: [Vec3; 2],
    /// The seam's other end, on the selected edge it runs on into.
    sharp_end: Vec3,
}

/// The axis point, unit axis and radius of a cylindrical carrier.
fn cylinder_of(surface: &NurbsSurface) -> Option<(Vec3, Vec3, f64)> {
    match surface.analytic()? {
        AnalyticSurface::RuledRevolution { frame, rho0, rho1, .. } => {
            ((rho0 - rho1).abs() <= 1e-9 * rho0.abs().max(1.0)).then_some((frame.origin, frame.axis, *rho0))
        }
        AnalyticSurface::Revolution { frame, generatrix, .. } => {
            if generatrix.degree != 1 {
                return None;
            }
            let [t0, t1] = generatrix.domain().ok()?;
            let radial = |point: Vec3| {
                let off = point.sub(frame.origin);
                off.sub(frame.axis.scale(off.dot(frame.axis))).length()
            };
            let (a, b) = (generatrix.evaluate(t0).ok()?, generatrix.evaluate(t1).ok()?);
            let along = b.sub(a);
            if along.length() < 1e-12 || along.cross(frame.axis).length() > 1e-9 * along.length() {
                return None;
            }
            let rho = radial(a);
            (0..=4)
                .all(|k| generatrix.evaluate(t0 + (t1 - t0) * k as f64 / 4.0).is_ok_and(|p| (radial(p) - rho).abs() <= 1e-9 * rho.max(1.0)))
                .then_some((frame.origin, frame.axis, rho))
        }
        _ => None,
    }
}

fn same_radius(rho: f64, radius: f64) -> bool {
    (rho - radius).abs() <= 1e-7 * radius.max(1.0)
}

/// The point where two axes cross, when they do (closest points within
/// `tol`) and are not parallel.
fn crossing(o1: Vec3, a1: Vec3, o2: Vec3, a2: Vec3, tol: f64) -> Option<Vec3> {
    let n = a1.cross(a2);
    let nn = n.dot(n);
    if nn < 1e-12 {
        return None;
    }
    let d = o2.sub(o1);
    let s = d.cross(a2).dot(n) / nn;
    let t = d.cross(a1).dot(n) / nn;
    let (p1, p2) = (o1.add(a1.scale(s)), o2.add(a2.scale(t)));
    (p1.sub(p2).length() <= tol).then(|| p1.add(p2).scale(0.5))
}

fn vertex_point(solid: &BrepSolid, id: u64) -> Option<Vec3> {
    solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point)
}

/// The selected seam at `index`, when its ball is pinned (see the module).
fn pinned_seam(solid: &BrepSolid, ids: &[u64], index: usize, radius: f64) -> Option<Pinned> {
    let tol = 1e-7 * radius.max(1.0);
    let (edge, faces) = super::analyze::edge_and_faces(solid, ids[index]).ok()?;
    if faces.len() != 2 || edge.degenerate || edge.start_vertex_id == edge.end_vertex_id {
        return None;
    }
    let (o1, a1, r1) = cylinder_of(&faces[0].surface)?;
    let (o2, a2, r2) = cylinder_of(&faces[1].surface)?;
    if !same_radius(r1, radius) || !same_radius(r2, radius) {
        return None;
    }
    let pin = crossing(o1, a1, o2, a2, tol)?;
    let (start, end) = (vertex_point(solid, edge.start_vertex_id)?, vertex_point(solid, edge.end_vertex_id)?);
    let on_ball = |p: Vec3| (p.sub(pin).length() - radius).abs() <= tol;
    let (pole, sharp_end, sharp_vertex) = match (on_ball(start), on_ball(end)) {
        (false, true) => (end, start, edge.start_vertex_id),
        (true, false) => (start, end, edge.end_vertex_id),
        _ => return None,
    };
    let polar = pole.sub(pin).normalized().ok()?;
    if polar.dot(a1).abs() > 1e-7 || polar.dot(a2).abs() > 1e-7 {
        return None;
    }
    // The seam's tangent at its sharp end, pointing into the seam.
    let at_start = edge.start_vertex_id == sharp_vertex;
    let tangent = edge.curve.unit_tangent(if at_start { edge.t0 } else { edge.t1 }, edge.t0, edge.t1).ok()?;
    let into_seam = if at_start { tangent } else { tangent.scale(-1.0) };
    // The selected edge the seam runs on into: between two planes `r` from
    // the pin, along the polar direction, tangent to the seam there.
    let runs_on = ids.iter().enumerate().any(|(other, &id)| {
        if other == index || id == ids[index] {
            return false;
        }
        let Ok((next, next_faces)) = super::analyze::edge_and_faces(solid, id) else { return false };
        if (next.start_vertex_id != sharp_vertex && next.end_vertex_id != sharp_vertex) || next_faces.len() != 2 {
            return false;
        }
        let next_at_start = next.start_vertex_id == sharp_vertex;
        let Ok(next_tangent) = next.curve.unit_tangent(if next_at_start { next.t0 } else { next.t1 }, next.t0, next.t1) else { return false };
        let away = if next_at_start { next_tangent } else { next_tangent.scale(-1.0) };
        if away.dot(into_seam) > -1.0 + 1e-6 || away.cross(polar).length() > 1e-7 {
            return false;
        }
        next_faces.iter().all(|face| {
            super::analyze::face_plane_normal(face, sharp_end).is_ok_and(|(on, normal)| (pin.sub(on).dot(normal).abs() - radius).abs() <= tol)
        })
    });
    runs_on.then_some(Pinned { index, pin, polar, axes: [a1, a2], sharp_end })
}

/// The rescue: `None` when no selected seam's ball is pinned or the lane is
/// off; otherwise the body, or the refusal of the rest of the selection, or
/// a refusal naming why the corner was not closed.
pub(super) fn pinned_ball_corners(
    solid: &BrepSolid,
    edge_points: &[Vec3],
    edge_names: Option<&[String]>,
    radius: f64,
    build: &dyn Fn(&BrepSolid, &[Vec3], Option<&[String]>) -> Result<BrepSolid, KernelRefusal>,
) -> Option<Result<BrepSolid, KernelRefusal>> {
    if !pinned_ball_on() || edge_points.len() < 2 || !(radius > 0.0) {
        return None;
    }
    let ids: Vec<u64> = edge_points.iter().map(|point| super::edges::resolve_edge_by_point(solid, *point).ok()).collect::<Option<_>>()?;
    let pinned: Vec<Pinned> = (0..ids.len()).filter_map(|index| pinned_seam(solid, &ids, index, radius)).collect();
    if pinned.is_empty() {
        return None;
    }
    let seams: Vec<usize> = pinned.iter().map(|seam| seam.index).collect();
    let keep: Vec<usize> = (0..edge_points.len()).filter(|index| !seams.contains(index) && !seams.iter().any(|&s| ids[s] == ids[*index])).collect();
    let points: Vec<Vec3> = keep.iter().map(|&index| edge_points[index]).collect();
    let names: Option<Vec<String>> = edge_names.map(|names| keep.iter().map(|&index| names.get(index).cloned().unwrap_or_default()).collect());
    let mut body = match build(solid, &points, names.as_deref()) {
        Ok(body) => body,
        Err(refusal) => return Some(Err(refusal)),
    };
    for seam in &pinned {
        let name = edge_names.and_then(|names| names.get(seam.index)).cloned();
        match close_pinned_corner(&body, seam, radius, name) {
            Ok(closed) => body = closed,
            Err(why) => {
                return Some(Err(KernelRefusal::unsupported(
                    KernelStage::Fragment,
                    "pinned_ball_corner",
                    format!("fillet: the pinned ball's corner at ({:.6}, {:.6}, {:.6}) was not closed: {why}", seam.pin.x, seam.pin.y, seam.pin.z),
                )))
            }
        }
    }
    let errors: Vec<String> = body.validate().into_iter().filter(|issue| issue.severity == "error").map(|issue| issue.message).collect();
    if !errors.is_empty() {
        return Some(Err(KernelRefusal::unsupported(
            KernelStage::Validate,
            "pinned_ball_corner",
            format!("fillet: the pinned ball's corner does not validate: {}", errors.join("; ")),
        )));
    }
    Some(Ok(body))
}

/// Where a coedge starts and ends (its traversal).
fn coedge_ends(solid: &BrepSolid, coedge: &CoedgeRecord) -> Option<(u64, u64)> {
    let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
    Some(if coedge.forward { (edge.start_vertex_id, edge.end_vertex_id) } else { (edge.end_vertex_id, edge.start_vertex_id) })
}

/// The face, loop and coedge range `[first, first + count)` (cyclic) of the
/// run of corner seams on the cylinder about `axis` through `pin` that goes
/// between vertices `x` and `y`, and its direction (`true`: from `x` to `y`).
struct Run {
    face: usize,
    lp: usize,
    first: usize,
    count: usize,
    from_x: bool,
}

fn find_run(solid: &BrepSolid, walls: &[u64; 3], wall: u64, x: u64, y: u64) -> Result<Run, String> {
    let faces = &solid.shells[0].faces;
    let face_index = faces.iter().position(|face| face.id == wall).ok_or("wall face missing")?;
    let is_corner_seam = |edge_id: u64| {
        let users: Vec<u64> = faces
            .iter()
            .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| coedge.edge_id == edge_id))
            .map(|face| face.id)
            .collect();
        users.len() == 2 && users.iter().all(|id| walls.contains(id))
    };
    for (lp_index, lp) in faces[face_index].loops.iter().enumerate() {
        let n = lp.coedges.len();
        for first in 0..n {
            let (start, _) = coedge_ends(solid, &lp.coedges[first]).ok_or("coedge edge missing")?;
            if start != x && start != y {
                continue;
            }
            let target = if start == x { y } else { x };
            for count in 1..n {
                let coedge = &lp.coedges[(first + count - 1) % n];
                if !is_corner_seam(coedge.edge_id) {
                    break;
                }
                let (_, end) = coedge_ends(solid, coedge).ok_or("coedge edge missing")?;
                if end == target {
                    return Ok(Run { face: face_index, lp: lp_index, first, count, from_x: start == x });
                }
            }
        }
    }
    Err(format!("no run of corner seams on face {wall}"))
}

fn close_pinned_corner(body: &BrepSolid, seam: &Pinned, radius: f64, name: Option<String>) -> Result<BrepSolid, String> {
    if body.shells.len() != 1 {
        return Err("the rounded body is not one shell".into());
    }
    let tol = 1e-6 * radius.max(1.0);
    let (pin, polar) = (seam.pin, seam.polar);
    // Each seam wall's contact circle with the ball lies in the plane through
    // the pin normal to its axis; it meets the third wall's (normal to the
    // polar direction) on the side of the sharp end.
    let toward = seam.sharp_end.sub(pin);
    let foot = |axis: Vec3| -> Result<Vec3, String> {
        let w = axis.cross(polar).normalized().map_err(|e| e.to_string())?;
        Ok(if w.dot(toward) >= 0.0 { w } else { w.scale(-1.0) })
    };
    let (w1, w2) = (foot(seam.axes[0])?, foot(seam.axes[1])?);
    let (point_a, point_b, point_q) = (pin.add(w1.scale(radius)), pin.add(w2.scale(radius)), pin.add(polar.scale(radius)));
    let vertex_at = |point: Vec3| -> Result<u64, String> {
        body.vertices
            .iter()
            .find(|vertex| vertex.point.sub(point).length() <= tol)
            .map(|vertex| vertex.id)
            .ok_or_else(|| format!("no vertex at ({:.6}, {:.6}, {:.6})", point.x, point.y, point.z))
    };
    let (va, vb, vq) = (vertex_at(point_a)?, vertex_at(point_b)?, vertex_at(point_q)?);
    // The three walls: cylinders of radius r about the two seam axes and the
    // polar direction, each through the pin, each touching the corner.
    let wall_about = |axis: Vec3, corners: [u64; 2]| -> Result<u64, String> {
        body.shells[0]
            .faces
            .iter()
            .filter(|face| {
                cylinder_of(&face.surface).is_some_and(|(origin, along, rho)| {
                    let off = pin.sub(origin);
                    same_radius(rho, radius) && along.cross(axis).length() <= 1e-7 && off.sub(along.scale(off.dot(along))).length() <= tol
                })
            })
            .find(|face| {
                let used: Vec<u64> = face.loops.iter().flat_map(|lp| &lp.coedges).filter_map(|coedge| coedge_ends(body, coedge)).map(|(start, _)| start).collect();
                corners.iter().all(|corner| used.contains(corner))
            })
            .map(|face| face.id)
            .ok_or_else(|| "a corner wall is missing".to_string())
    };
    let walls = [wall_about(seam.axes[0], [va, vq])?, wall_about(seam.axes[1], [vb, vq])?, wall_about(polar, [va, vb])?];
    let runs = [find_run(body, &walls, walls[0], va, vq)?, find_run(body, &walls, walls[1], vb, vq)?, find_run(body, &walls, walls[2], va, vb)?];

    let mut out = body.clone();
    let mut next_id = out
        .edges
        .iter()
        .map(|edge| edge.id)
        .chain(out.vertices.iter().map(|vertex| vertex.id))
        .chain(out.shells.iter().flat_map(|shell| shell.faces.iter().flat_map(|face| {
            std::iter::once(face.id).chain(face.loops.iter().flat_map(|lp| std::iter::once(lp.id).chain(lp.coedges.iter().map(|coedge| coedge.id))))
        })))
        .max()
        .unwrap_or(0)
        + 1;
    let mut fresh = || {
        next_id += 1;
        next_id - 1
    };
    // The sphere: pole at the seam's tangent end, its seam meridian opposite
    // the corner, so the triangle's azimuths do not wrap.
    let away = w1.add(w2).scale(-1.0);
    let sphere = crate::make_sphere_surface_framed(pin, radius, polar, Some(away)).map_err(|e| e.to_string())?;
    let uv = |point: Vec3| -> Result<[f64; 2], String> {
        let (uv, distance) = crate::pcurve::invert_checked(&sphere, point)?;
        if distance > tol {
            return Err("a corner point is off the ball".into());
        }
        Ok(uv)
    };
    let ([ua, v_a], [ub, v_b]) = (uv(point_a)?, uv(point_b)?);
    let v_pole = sphere.domain_v().map_err(|e| e.to_string())?[1];
    // An arc about the pin from one corner to another (a quarter of a great
    // circle or less).
    let arc = |from: Vec3, to: Vec3| -> Result<NurbsCurve, String> {
        let x = from.sub(pin).normalized().map_err(|e| e.to_string())?;
        let rel = to.sub(pin);
        let y = rel.sub(x.scale(rel.dot(x))).normalized().map_err(|e| e.to_string())?;
        let sweep = x.dot(rel.scale(1.0 / radius)).clamp(-1.0, 1.0).acos();
        make_arc(pin, x, y, radius, 0.0, sweep).map_err(|e| e.to_string())
    };
    // Each new edge runs the way the sphere's loop runs, the reverse of the
    // wall's run. The wall runs give the sphere loop's direction:
    // wall 2 (the third) runs A->B or B->A; the sphere goes the other way.
    let corner_of = |vertex: u64| if vertex == va { point_a } else if vertex == vb { point_b } else { point_q };
    let corner_uv = |vertex: u64, meridian_u: f64| -> [f64; 2] {
        if vertex == va {
            [ua, v_a]
        } else if vertex == vb {
            [ub, v_b]
        } else {
            [meridian_u, v_pole]
        }
    };
    let ends = |run: &Run, x: u64, y: u64| if run.from_x { (y, x) } else { (x, y) };
    let sphere_legs = [ends(&runs[2], va, vb), ends(&runs[0], va, vq), ends(&runs[1], vb, vq)];
    // Chain the three legs into one loop: (third wall leg) s->t, then the
    // leg from t to the pole, then the pole to s.
    let (s, t) = sphere_legs[0];
    let to_pole = sphere_legs.iter().skip(1).find(|leg| leg.0 == t && leg.1 == vq).ok_or("the walls' runs do not close one loop")?;
    let from_pole = sphere_legs.iter().skip(1).find(|leg| leg.0 == vq && leg.1 == s).ok_or("the walls' runs do not close one loop")?;
    let (u_t, u_s) = (corner_uv(t, 0.0)[0], corner_uv(s, 0.0)[0]);
    let loop_uv = [corner_uv(s, 0.0), corner_uv(t, 0.0), [u_t, v_pole], [u_s, v_pole]];
    let area: f64 = (0..4).map(|k| {
        let (p, q) = (loop_uv[k], loop_uv[(k + 1) % 4]);
        p[0] * q[1] - q[0] * p[1]
    }).sum();
    if area <= 0.0 {
        return Err("the corner's loop runs clockwise on the ball".into());
    }

    let legs = [(sphere_legs[0], 2usize), (*to_pole, if to_pole.0 == va { 0 } else { 1 }), (*from_pole, if from_pole.1 == va { 0 } else { 1 })];
    let mut sphere_coedges = Vec::new();
    let mut replacements: Vec<(usize, CoedgeRecord)> = Vec::new();
    for ((from, to), wall) in legs {
        let curve = arc(corner_of(from), corner_of(to))?;
        let edge_id = fresh();
        let (from_uv, to_uv) = if from == vq {
            ([u_s, v_pole], corner_uv(to, 0.0))
        } else if to == vq {
            (corner_uv(from, 0.0), [u_t, v_pole])
        } else {
            (corner_uv(from, 0.0), corner_uv(to, 0.0))
        };
        sphere_coedges.push(CoedgeRecord {
            id: fresh(),
            edge_id,
            forward: true,
            pcurve: crate::sweep_topology::parameter_line(from_uv[0], from_uv[1], to_uv[0], to_uv[1]).map_err(|e| e.to_string())?,
        });
        if to == vq {
            // The pole: a degenerate edge from the meridian through t to the one through s.
            let pole_edge = fresh();
            out.edges.push(crate::topology::EdgeRecord {
                id: pole_edge,
                curve: make_line(point_q, point_q).map_err(|e| e.to_string())?,
                t0: 0.0,
                t1: 1.0,
                start_vertex_id: vq,
                end_vertex_id: vq,
                degenerate: true,
                name: None,
            });
            sphere_coedges.push(CoedgeRecord {
                id: fresh(),
                edge_id: pole_edge,
                forward: true,
                pcurve: crate::sweep_topology::parameter_line(u_t, v_pole, u_s, v_pole).map_err(|e| e.to_string())?,
            });
        }
        let surface = &body.shells[0].faces[runs[wall].face].surface;
        let pcurve = crate::pcurve::build_pcurve_on_surface_range(surface, &curve, 0.0, 1.0, false, 1e-9 * (1.0 + radius)).map_err(|e| e.to_string())?;
        replacements.push((wall, CoedgeRecord { id: fresh(), edge_id, forward: false, pcurve }));
        out.edges.push(crate::topology::EdgeRecord { id: edge_id, curve, t0: 0.0, t1: 1.0, start_vertex_id: from, end_vertex_id: to, degenerate: false, name: None });
    }
    // Splice each wall's run out for its one arc.
    for (wall, coedge) in replacements {
        let run = &runs[wall];
        let coedges = &mut out.shells[0].faces[run.face].loops[run.lp].coedges;
        let n = coedges.len();
        let mut kept: Vec<CoedgeRecord> = Vec::with_capacity(n - run.count + 1);
        kept.push(coedge);
        for k in run.count..n {
            kept.push(coedges[(run.first + k) % n].clone());
        }
        *coedges = kept;
    }
    let face_id = fresh();
    let loop_id = fresh();
    out.shells[0].faces.push(crate::topology::FaceRecord {
        id: face_id,
        surface: sphere,
        same_sense: true,
        loops: vec![LoopRecord { id: loop_id, coedges: sphere_coedges }],
        name,
    });
    // Drop the seams the arcs replaced and the vertex where they met.
    let used: std::collections::HashSet<u64> = out.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges).map(|coedge| coedge.edge_id).collect();
    out.edges.retain(|edge| used.contains(&edge.id));
    let live: std::collections::HashSet<u64> = out.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
    out.vertices.retain(|vertex| live.contains(&vertex.id));
    out.mass_properties_cache = Default::default();
    Ok(out)
}