BREP_blend 0.33.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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! `BREP_FILLET_ROLLOVER_BUILD` (default off): a closed RING of convex lip
//! edges over one planar underside strip narrower than the ball's reach, the
//! strip's far loop bounded by tangent rounds (the "pads") on which the ball
//! rides instead. The strip is consumed whole.
//!
//! The pads' far edges are not abreast of the lip edges (a roof's corner arcs
//! and its cabin's rounded corners have different centres), and along one lip
//! edge the ball's pad contact can pass from one pad face to the next. So the
//! lane first reads the contact's ITINERARY: each lip edge is marched against
//! every pad carrier and the contact is classified against the pad faces'
//! trims; where it passes from one pad face to the next the lip edge is cut,
//! by bisection. Each cut piece then rides one wall face and one pad face, and
//! the pads' far edges are cut so that their pieces pair one to one with the
//! lip pieces in the same cyclic order.
//!
//! The group network then builds the ring on a SCRATCH copy of the body in
//! which the strip is gone: each pad piece's coedge becomes a coedge of its
//! lip piece (its pcurve only seeds the march, which solves the contacts by
//! Newton), the far loop's vertices are identified with the lip's, and the
//! mates' signed radii are supplied (`signed_radii` cannot probe a pad from
//! an edge that does not lie on it). The parts of the scratch that are out of
//! place are what the surgery replaces by the rails. The built body is
//! validated; anything else is `Ok(None)` or an error the caller drops.
use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
use crate::{KernelRefusal, KernelStage, NurbsCurve, OrRefuse, Vec3};
use super::stations::{locate_mate, signed_radii, BlendMate};

thread_local! {
    /// Per (edge, first face, second face), the signed radii the network
    /// takes instead of probing (`signed_radii`), while the ring lane drives
    /// it on its scratch body. `None` outside that call.
    static SIGNED_RADII: std::cell::RefCell<Option<rustc_hash::FxHashMap<(u64, u64, u64), (f64, f64)>>> =
        const { std::cell::RefCell::new(None) };
}

/// The signed radii supplied for this edge between these faces, if the ring
/// lane is driving the network.
pub(in crate::blend) fn signed_radii_override(edge: u64, first: u64, second: u64) -> Option<(f64, f64)> {
    SIGNED_RADII.with(|cell| cell.borrow().as_ref().and_then(|map| map.get(&(edge, first, second)).copied()))
}

struct Restore(Option<rustc_hash::FxHashMap<(u64, u64, u64), (f64, f64)>>);

impl Drop for Restore {
    fn drop(&mut self) {
        let previous = self.0.take();
        SIGNED_RADII.with(|cell| *cell.borrow_mut() = previous);
    }
}

/// One cut piece of a lip edge: its parameter range on the lip edge, in
/// edge order, and the pad face its contact rides.
#[derive(Clone, Copy, Debug)]
struct Piece {
    lip: u64,
    t: [f64; 2],
    pad: u64,
}

/// Try the consumed-ring build of the closed chain `edge_ids` at `radius`;
/// `Ok(None)` when the shape is not this case or the build does not stand.
pub(crate) fn blend_consumed_ring(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
    names: &[Option<String>],
    corner_name: &dyn Fn(&[usize]) -> Option<String>,
    wrap_concave: bool,
) -> Result<Option<BrepSolid>, KernelRefusal> {
    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
    let say = |what: &str| {
        if debug {
            eprintln!("consumed ring: {what}");
        }
    };
    say(&format!("trying {} edges at r {radius}", edge_ids.len()));
    let decline = |line: u32| {
        if debug {
            eprintln!("consumed ring: declines (consumed_ring.rs:{line})");
        }
        Ok(None)
    };
    if !(radius > 0.0) || !radius.is_finite() || edge_ids.len() < 2 {
        return decline(line!());
    }
    let edge_of = |id: u64| solid.edges.iter().find(|candidate| candidate.id == id);
    let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();

    // The strip: one planar face of two loops, one of which is exactly the
    // selected ring.
    let Some((strip, lip_loop)) = faces.iter().copied().find_map(|face| {
        if !matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) || face.loops.len() != 2 {
            return None;
        }
        let index = face.loops.iter().position(|loop_record| {
            loop_record.coedges.len() == edge_ids.len() && loop_record.coedges.iter().all(|coedge| edge_ids.contains(&coedge.edge_id))
        })?;
        Some((face, index))
    }) else {
        say("no planar strip of two loops has the selected ring for one loop");
        return decline(line!());
    };
    let far_loop = 1 - lip_loop;
    let lip_coedges = &strip.loops[lip_loop].coedges;
    let far_coedges = &strip.loops[far_loop].coedges;

    // Each lip edge: its wall and the signed radii from wall and strip.
    struct Lip<'a> {
        edge: &'a EdgeRecord,
        forward: bool,
        wall: &'a FaceRecord,
        wall_loop: usize,
        wall_coedge: &'a CoedgeRecord,
        rho_wall: f64,
        rho_strip: f64,
    }
    let mut lips = Vec::with_capacity(lip_coedges.len());
    for coedge in lip_coedges {
        let Some(edge) = edge_of(coedge.edge_id) else { return decline(line!()) };
        if edge.start_vertex_id == edge.end_vertex_id {
            say(&format!("lip edge {} is closed", edge.id));
            return decline(line!());
        }
        let first = locate_mate(solid, edge.id, None)?;
        let second = locate_mate(solid, edge.id, Some((first.0.id, first.1)))?;
        let (strip_first, wall) = if first.0.id == strip.id { (true, second) } else if second.0.id == strip.id { (false, first) } else {
            say(&format!("lip edge {} does not bound the strip", edge.id));
            return decline(line!());
        };
        let (rho_first, rho_second) = signed_radii(edge, first.0, first.2, second.0, second.2, radius)?;
        let (rho_wall, rho_strip) = if strip_first { (rho_second, rho_first) } else { (rho_first, rho_second) };
        lips.push(Lip { edge, forward: coedge.forward, wall: wall.0, wall_loop: wall.1, wall_coedge: wall.2, rho_wall, rho_strip });
    }
    let rho_strip = lips[0].rho_strip;
    let strip_sense = if strip.same_sense { 1.0 } else { -1.0 };
    if rho_strip * strip_sense >= 0.0 || lips.iter().any(|lip| lip.rho_strip != rho_strip) {
        say("the lip ring is not convex over the strip");
        return decline(line!());
    }

    // Each far edge: the pad across it, tangent to the strip, and its radius.
    struct Far<'a> {
        edge: &'a EdgeRecord,
        forward: bool,
        pad: &'a FaceRecord,
        pad_loop: usize,
        pad_coedge: &'a CoedgeRecord,
        rho_pad: f64,
    }
    let mut fars = Vec::with_capacity(far_coedges.len());
    for coedge in far_coedges {
        let Some(edge) = edge_of(coedge.edge_id) else { return decline(line!()) };
        if edge.start_vertex_id == edge.end_vertex_id {
            say(&format!("far edge {} is closed", edge.id));
            return decline(line!());
        }
        let (pad, pad_loop, pad_coedge) = locate_mate(solid, edge.id, Some((strip.id, far_loop)))?;
        let Some(rho_pad) = super::edge::consumed_pad_rho(strip, coedge, edge, pad, pad_coedge, rho_strip)? else {
            say(&format!("the pad {} does not continue the strip tangentially along edge {}", pad.id, edge.id));
            return decline(line!());
        };
        fars.push(Far { edge, forward: coedge.forward, pad, pad_loop, pad_coedge, rho_pad });
    }
    // One far edge per pad face, so a pad run pairs with one far edge.
    for (index, far) in fars.iter().enumerate() {
        if fars.iter().skip(index + 1).any(|other| other.pad.id == far.pad.id) {
            say("a pad face meets the strip along more than one edge");
            return decline(line!());
        }
    }
    let pad_rho = |pad: u64| fars.iter().find(|far| far.pad.id == pad).map(|far| far.rho_pad);
    let boundary: Vec<&EdgeRecord> = lips.iter().map(|lip| lip.edge).chain(fars.iter().map(|far| far.edge)).collect();

    // The itinerary: along each lip edge, which pad face carries the contact.
    let radius_at = |_: f64| radius;
    let mut pieces: Vec<Piece> = Vec::new();
    // The pad contact at each lip vertex, read where a piece ends.
    let mut contacts: Vec<(u64, f64, Vec3)> = Vec::new();
    for lip in &lips {
        let edge = lip.edge;
        let wall_mate = BlendMate { face: lip.wall, coedge: lip.wall_coedge, loop_index: lip.wall_loop, rho: lip.rho_wall };
        // The contact on `far`'s pad over [a, b]: per station, its point and
        // whether it lies on that pad face.
        let read = |far: &Far, ends: [f64; 2], count: usize| -> Option<Vec<(f64, Vec3, bool, Vec3)>> {
            let seed = projected_pcurve(edge, ends, &far.pad.surface)?;
            let pad_mate = BlendMate { face: far.pad, coedge: &seed, loop_index: far.pad_loop, rho: far.rho_pad };
            let sub = EdgeRecord { t0: ends[0], t1: ends[1], ..edge.clone() };
            let (stations, [low, high], _, _) = super::edge::support::march_open_stations_core(
                &sub, &wall_mate, &pad_mate, &radius_at, 0.0, ends, count, [false, false], [false, false], None, 0, true,
            )
            .map_err(|error| {
                if debug {
                    eprintln!("consumed ring: march of lip {} on pad {} over {ends:?}: {error}", edge.id, far.pad.id);
                }
            })
            .ok()?;
            let along = stations.get(low..=high)?;
            if debug && along.len() != count + 1 {
                eprintln!("consumed ring: march of lip {} over {ends:?} gave {} stations in [{low}, {high}] of {}, asked {count}", edge.id, along.len(), stations.len());
            }
            (along.len() == count + 1).then(|| {
                along
                    .iter()
                    .enumerate()
                    .map(|(index, station)| {
                        let t = ends[0] + (ends[1] - ends[0]) * index as f64 / count as f64;
                        let on = !super::edge::support_exits_at(far.pad, station.uv2);
                        (t, station.p2, on, station.center)
                    })
                    .collect()
            })
        };
        const COUNT: usize = 32;
        let readings: Vec<Option<Vec<(f64, Vec3, bool, Vec3)>>> = fars.iter().map(|far| read(far, [edge.t0, edge.t1], COUNT)).collect();
        // Per station, the one pad face whose trim holds the contact.
        // Per station, the pad faces whose trims hold the contact.
        let holding: Vec<Vec<usize>> = (0..=COUNT)
            .map(|station| (0..fars.len()).filter(|&far| readings[far].as_ref().is_some_and(|read| read[station].2)).collect())
            .collect();
        // A station held by no pad face is the ball off every pad: on the
        // strip, which this lane does not build. Only a single station on the
        // seam between two pads (held on both sides, by different pads) may
        // read as held by neither, or by both.
        let mut owner: Vec<usize> = Vec::with_capacity(COUNT + 1);
        for station in 0..=COUNT {
            let own = match holding[station].as_slice() {
                [one] => *one,
                _ => {
                    let single = |index: usize| match holding.get(index).map(Vec::as_slice) {
                        Some([one]) => Some(*one),
                        _ => None,
                    };
                    let before = station.checked_sub(1).and_then(single);
                    let after = single(station + 1);
                    match (before, after) {
                        (Some(before), Some(after)) if before != after && holding[station].iter().all(|far| *far == before || *far == after) => before,
                        _ => {
                            say(&format!("lip edge {}: station {station}'s contact lies on {} pad faces", edge.id, holding[station].len()));
                            return decline(line!());
                        }
                    }
                }
            };
            // The ball clears the strip it consumes, at every station.
            let Some(centre) = readings[own].as_ref().map(|read| read[station].3) else {
                return decline(line!());
            };
            if !super::edge::consumed_clears_strip(strip, &boundary, centre, radius)? {
                say(&format!("the ball at {centre:?} touches the strip {}", strip.id));
                return decline(line!());
            }
            owner.push(own);
        }
        // Cut where the owner changes, by bisection on the left owner's reading.
        let mut start = edge.t0;
        for index in 0..COUNT {
            let (here, next) = (owner[index], owner[index + 1]);
            if here == next {
                continue;
            }
            let t_here = edge.t0 + (edge.t1 - edge.t0) * index as f64 / COUNT as f64;
            let t_next = edge.t0 + (edge.t1 - edge.t0) * (index + 1) as f64 / COUNT as f64;
            let (mut low, mut high) = (t_here, t_next);
            for _ in 0..48 {
                let middle = 0.5 * (low + high);
                let on = read(&fars[here], [t_here, middle], 8).and_then(|read| read.last().map(|last| last.2));
                match on {
                    Some(true) => low = middle,
                    Some(false) => high = middle,
                    None => return decline(line!()),
                }
            }
            let cut = 0.5 * (low + high);
            let contact = read(&fars[here], [t_here, cut], 8).and_then(|read| read.last().map(|last| last.1));
            let Some(contact) = contact else { return decline(line!()) };
            pieces.push(Piece { lip: edge.id, t: [start, cut], pad: fars[here].pad.id });
            contacts.push((edge.id, cut, contact));
            start = cut;
        }
        pieces.push(Piece { lip: edge.id, t: [start, edge.t1], pad: fars[owner[COUNT]].pad.id });
        // The contacts at the lip edge's own ends.
        for (station, t) in [(0usize, edge.t0), (COUNT, edge.t1)] {
            let Some(read) = readings[owner[station]].as_ref() else { return decline(line!()) };
            contacts.push((edge.id, t, read[station].1));
        }
    }
    if debug {
        for piece in &pieces {
            eprintln!("consumed ring: lip {} [{:.9}, {:.9}] rides pad {}", piece.lip, piece.t[0], piece.t[1], piece.pad);
        }
    }

    // The pieces in the lip loop's order, and the pad runs in the far loop's
    // order turned to run the same way round.
    let mut ordered: Vec<Piece> = Vec::new();
    for lip in &lips {
        let mut own: Vec<Piece> = pieces.iter().copied().filter(|piece| piece.lip == lip.edge.id).collect();
        if !lip.forward {
            own.reverse();
        }
        ordered.extend(own);
    }
    let aligned: Vec<&Far> = fars.iter().rev().collect();
    // Rotate the pieces so a pad run starts the sequence.
    let n = ordered.len();
    let Some(first_run) = (0..n).find(|&index| ordered[index].pad != ordered[(index + n - 1) % n].pad) else {
        say("the whole ring rides one pad face");
        return decline(line!());
    };
    ordered.rotate_left(first_run);
    let mut runs: Vec<(u64, Vec<Piece>)> = Vec::new();
    for piece in ordered {
        match runs.last_mut() {
            Some((pad, run)) if *pad == piece.pad => run.push(piece),
            _ => runs.push((piece.pad, vec![piece])),
        }
    }
    if runs.len() != aligned.len() {
        say(&format!("{} pad runs along the lip against {} far edges", runs.len(), aligned.len()));
        return decline(line!());
    }
    let Some(offset) = (0..aligned.len()).find(|&offset| (0..runs.len()).all(|index| aligned[(index + offset) % aligned.len()].pad.id == runs[index].0)) else {
        say("the pad runs and the far edges do not pair in order");
        return decline(line!());
    };

    // The scratch body.
    let mut scratch = solid.clone();
    let mut take_id = super::edge::fresh_id_source(solid);
    // Lip vertices: each piece's start and end in LOOP order (the vertex the
    // loop reaches it from, and the one it leaves by).
    let mut lip_records: Vec<EdgeRecord> = Vec::new();
    let mut new_vertices: Vec<VertexRecord> = Vec::new();
    // Per lip edge, its pieces' new records in edge order.
    let mut by_lip: rustc_hash::FxHashMap<u64, Vec<EdgeRecord>> = Default::default();
    for lip in &lips {
        let edge = lip.edge;
        let own: Vec<Piece> = pieces.iter().copied().filter(|piece| piece.lip == edge.id).collect();
        let mut records = Vec::with_capacity(own.len());
        let mut previous = edge.start_vertex_id;
        for (index, piece) in own.iter().enumerate() {
            let end = if index + 1 == own.len() {
                edge.end_vertex_id
            } else {
                let id = take_id();
                let point = edge.curve.evaluate(piece.t[1]).or_refuse(KernelStage::Refine, "evaluate")?;
                new_vertices.push(VertexRecord { id, point });
                id
            };
            let id = if own.len() == 1 { edge.id } else { take_id() };
            records.push(EdgeRecord { id, t0: piece.t[0], t1: piece.t[1], start_vertex_id: previous, end_vertex_id: end, ..edge.clone() });
            previous = end;
        }
        lip_records.extend(records.iter().cloned());
        by_lip.insert(edge.id, records);
    }
    // The loop-order piece records with their pad, and the vertex each starts
    // from in loop order.
    let mut loop_pieces: Vec<(EdgeRecord, u64, u64, u64)> = Vec::new(); // record, pad, loop start, loop end
    for lip in &lips {
        let records = &by_lip[&lip.edge.id];
        let own: Vec<Piece> = pieces.iter().copied().filter(|piece| piece.lip == lip.edge.id).collect();
        let mut pairs: Vec<(EdgeRecord, u64)> = records.iter().cloned().zip(own.iter().map(|piece| piece.pad)).collect();
        if !lip.forward {
            pairs.reverse();
        }
        for (record, pad) in pairs {
            let (from, to) = if lip.forward { (record.start_vertex_id, record.end_vertex_id) } else { (record.end_vertex_id, record.start_vertex_id) };
            loop_pieces.push((record, pad, from, to));
        }
    }
    loop_pieces.rotate_left(first_run);

    // Far pieces: each far edge cut at the contacts of its run's inner lip
    // vertices. `identify` maps far vertices onto lip vertices.
    let mut identify: rustc_hash::FxHashMap<u64, u64> = Default::default();
    // Per far edge, its renamed pad coedges in the PAD loop's order.
    let mut pad_coedges: rustc_hash::FxHashMap<u64, Vec<CoedgeRecord>> = Default::default();
    let mut radii: rustc_hash::FxHashMap<(u64, u64, u64), (f64, f64)> = Default::default();
    let mut cursor = 0usize;
    for (run_index, (pad, run)) in runs.iter().enumerate() {
        let far = aligned[(run_index + offset) % aligned.len()];
        let run_pieces = &loop_pieces[cursor..cursor + run.len()];
        cursor += run.len();
        // The far edge traversed the lip's way round: against its strip coedge.
        let along_forward = !far.forward;
        let (far_from, far_to) = if along_forward { (far.edge.start_vertex_id, far.edge.end_vertex_id) } else { (far.edge.end_vertex_id, far.edge.start_vertex_id) };
        identify.insert(far_from, run_pieces[0].2);
        identify.insert(far_to, run_pieces[run_pieces.len() - 1].3);
        // Cut fractions along the far edge (edge order), at the inner lip
        // vertices' pad contacts.
        let mut fractions = vec![0.0];
        for piece in &run_pieces[..run_pieces.len() - 1] {
            let vertex = piece.3;
            let point = vertex_point(&scratch, &new_vertices, vertex).ok_or(KernelRefusal::internal(KernelStage::Classify, "ring_vertex", "blend: a lip vertex is missing"))?;
            let contact = contacts
                .iter()
                .filter(|(_, _, contact)| contact.sub(point).length() < 4.0 * radius)
                .min_by(|a, b| a.2.sub(point).length().total_cmp(&b.2.sub(point).length()))
                .map(|(_, _, contact)| *contact);
            let Some(contact) = contact else { return decline(line!()) };
            let projection = crate::project_point_to_curve(&far.edge.curve, contact).or_refuse(KernelStage::Classify, "project_point_to_curve")?;
            let span = far.edge.t1 - far.edge.t0;
            let fraction = (projection.u - far.edge.t0) / span;
            let fraction = if along_forward { fraction } else { 1.0 - fraction };
            fractions.push(fraction);
        }
        fractions.push(1.0);
        if fractions.windows(2).any(|pair| !(pair[1] > pair[0] + 1e-9)) {
            say(&format!("far edge {}: the cuts do not run in order ({fractions:?})", far.edge.id));
            return decline(line!());
        }
        // The pad coedge's pieces (in the lip's order round), renamed onto the
        // lip pieces. A pad coedge running the far edge's own way runs along
        // the lip's way when the far edge does (`along_forward`).
        let mut renamed = Vec::with_capacity(run_pieces.len());
        for (index, (record, piece_pad, from, _)) in run_pieces.iter().enumerate() {
            debug_assert_eq!(piece_pad, pad);
            let (a, b) = (fractions[index], fractions[index + 1]);
            // Edge-order fractions of this piece on the far edge.
            let (edge_a, edge_b) = if along_forward { (a, b) } else { (1.0 - b, 1.0 - a) };
            let Some(pcurve) = fraction_piece(far.pad_coedge, edge_a, edge_b) else { return decline(line!()) };
            // Which way the pad coedge runs relative to the lip's way round:
            // the pad's coedge opposes the strip's on the far edge.
            let pad_runs_along = far.pad_coedge.forward == along_forward;
            // The lip piece runs the lip's way round when it starts at `from`.
            let piece_along = record.start_vertex_id == *from;
            renamed.push(CoedgeRecord { id: take_id(), edge_id: record.id, forward: pad_runs_along == piece_along, pcurve });
            let wall = lips.iter().find(|lip| lip.edge.id == record.id || by_lip.get(&lip.edge.id).is_some_and(|records| records.iter().any(|r| r.id == record.id))).map(|lip| (lip.wall.id, lip.rho_wall));
            let (Some((wall_id, rho_wall)), Some(rho_pad)) = (wall, pad_rho(*pad)) else { return decline(line!()) };
            radii.insert((record.id, wall_id, *pad), (rho_wall, rho_pad));
            radii.insert((record.id, *pad, wall_id), (rho_pad, rho_wall));
        }
        // In the pad loop's order: the pad loop runs against the lip's way
        // when its coedge does.
        if far.pad_coedge.forward != along_forward {
            renamed.reverse();
        }
        pad_coedges.insert(far.edge.id, renamed);
    }

    // Rewrite the scratch.
    let far_ids: Vec<u64> = fars.iter().map(|far| far.edge.id).collect();
    let lip_ids: Vec<u64> = lips.iter().map(|lip| lip.edge.id).collect();
    scratch.edges.retain(|record| !far_ids.contains(&record.id) && !lip_ids.contains(&record.id));
    for record in &mut scratch.edges {
        if let Some(&to) = identify.get(&record.start_vertex_id) {
            record.start_vertex_id = to;
        }
        if let Some(&to) = identify.get(&record.end_vertex_id) {
            record.end_vertex_id = to;
        }
    }
    scratch.edges.extend(lip_records.iter().cloned());
    scratch.vertices.retain(|vertex| !identify.contains_key(&vertex.id));
    scratch.vertices.extend(new_vertices.iter().cloned());
    for shell in &mut scratch.shells {
        shell.faces.retain(|face| face.id != strip.id);
        for face in &mut shell.faces {
            for loop_record in &mut face.loops {
                let mut rewritten = Vec::with_capacity(loop_record.coedges.len());
                for coedge in &loop_record.coedges {
                    if let Some(renamed) = pad_coedges.get(&coedge.edge_id) {
                        rewritten.extend(renamed.iter().cloned());
                    } else if let Some(records) = by_lip.get(&coedge.edge_id).filter(|records| records.len() > 1) {
                        // A wall coedge on a cut lip edge: one coedge per piece.
                        let mut own = Vec::with_capacity(records.len());
                        let lip = lips.iter().find(|lip| lip.edge.id == coedge.edge_id);
                        let Some(lip) = lip else { return decline(line!()) };
                        for record in records {
                            let a = (record.t0 - lip.edge.t0) / (lip.edge.t1 - lip.edge.t0);
                            let b = (record.t1 - lip.edge.t0) / (lip.edge.t1 - lip.edge.t0);
                            let Some(pcurve) = fraction_piece(coedge, a, b) else { return decline(line!()) };
                            own.push(CoedgeRecord { id: take_id(), edge_id: record.id, forward: coedge.forward, pcurve });
                        }
                        if !coedge.forward {
                            own.reverse();
                        }
                        rewritten.extend(own);
                    } else {
                        rewritten.push(coedge.clone());
                    }
                }
                loop_record.coedges = rewritten;
            }
        }
    }
    // The selection on the scratch: every lip piece, named as its lip edge.
    let piece_ids: Vec<u64> = loop_pieces.iter().map(|(record, _, _, _)| record.id).collect();
    let piece_names: Vec<Option<String>> = loop_pieces
        .iter()
        .map(|(record, _, _, _)| {
            let parent = lips.iter().position(|lip| lip.edge.id == record.id || by_lip[&lip.edge.id].iter().any(|r| r.id == record.id));
            parent.and_then(|parent| edge_ids.iter().position(|id| *id == lips[parent].edge.id)).and_then(|index| names.get(index).cloned().flatten())
        })
        .collect();
    if debug {
        eprintln!("consumed ring: scratch with {} lip pieces, {} identified vertices", piece_ids.len(), identify.len());
    }
    crate::blend::record_count("count.network.consumed_ring.scratch", 1);
    let previous = SIGNED_RADII.with(|cell| cell.replace(Some(radii)));
    let _restore = Restore(previous);
    let built = super::blend_star_network_with_corner_policy(&scratch, &piece_ids, radius, false, &piece_names, corner_name, wrap_concave)?;
    let issues = built.validate();
    if !issues.is_empty() {
        say(&format!("the built body does not validate: {issues:?}"));
        return decline(line!());
    }
    crate::blend::record_count("count.network.consumed_ring", 1);
    Ok(Some(built))
}

fn vertex_point(scratch: &BrepSolid, extra: &[VertexRecord], id: u64) -> Option<Vec3> {
    scratch.vertices.iter().chain(extra).find(|vertex| vertex.id == id).map(|vertex| vertex.point)
}

/// The piece of `coedge`'s pcurve between the edge fractions `a < b`, read
/// as `edge_uv_on_face` reads it, so the piece reads by fraction over its own
/// sub-edge.
fn fraction_piece(coedge: &CoedgeRecord, a: f64, b: f64) -> Option<NurbsCurve> {
    let [p0, p1] = coedge.pcurve.domain().ok()?;
    let at = |fraction: f64| if coedge.forward { p0 + (p1 - p0) * fraction } else { p1 - (p1 - p0) * fraction };
    let (low, high) = {
        let (x, y) = (at(a), at(b));
        (x.min(y), x.max(y))
    };
    let tail = if low <= p0 + 1e-12 { coedge.pcurve.clone() } else { coedge.pcurve.split(low).ok()?.1 };
    if high >= p1 - 1e-12 {
        return Some(tail);
    }
    Some(tail.split(high).ok()?.0)
}

/// A degree-1 pcurve on `surface` through the projections of `edge`'s points
/// over `ends`, parametrised [0, 1]: a march seed for a candidate pad.
fn projected_pcurve(edge: &EdgeRecord, ends: [f64; 2], surface: &crate::NurbsSurface) -> Option<CoedgeRecord> {
    const SAMPLES: usize = 16;
    let mut points = Vec::with_capacity(SAMPLES + 1);
    for index in 0..=SAMPLES {
        let t = ends[0] + (ends[1] - ends[0]) * index as f64 / SAMPLES as f64;
        let point = edge.curve.evaluate(t).ok()?;
        let projection = crate::project_point_to_surface(surface, point).ok()?;
        points.push(Vec3::new(projection.u, projection.v, 0.0));
    }
    let pcurve = polyline(&points)?;
    Some(CoedgeRecord { id: 0, edge_id: edge.id, forward: true, pcurve })
}

/// A degree-1 NURBS through `points`, parametrised uniformly on [0, 1].
fn polyline(points: &[Vec3]) -> Option<NurbsCurve> {
    let n = points.len();
    if n < 2 {
        return None;
    }
    let mut knots = vec![0.0, 0.0];
    for index in 1..n - 1 {
        knots.push(index as f64 / (n - 1) as f64);
    }
    knots.extend([1.0, 1.0]);
    NurbsCurve::new(1, knots, points.iter().map(|point| crate::Vec4::from_point(*point, 1.0)).collect()).ok()
}