BREP_construction 0.35.0

Rust B-rep CAD kernel (next.BREP.io): solid construction: extrusions, revolutions, sweeps and lofts.
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Fold creases of a trimmed tube, unzipped.
//!
//! Where K's self-intersection curve ends at a fold's fixed point, the curve's
//! own side and its mate side lie in one patch and the trim leaves one face
//! whose loop runs the same edge out and back: the two runs are apart on the
//! (u, v) plane (they leave the fixed point in opposite directions) and are one
//! curve in space. That is a valid face, but a reader that places a loop on its
//! surface by inverting the edges' points cannot tell the two runs apart (both
//! are preimages of every point of the edge), walks the same run back, and
//! starts the next edge on the wrong one (brep-bench's measurer: "the integral
//! round a loop does not converge").
//!
//! Each such face is cut here along the parameter line through the fixed point
//! that crosses the curve there, into faces on the two parts of the surface
//! split at that line: the two runs then lie in different faces on different
//! surfaces, each surface holding one preimage only.

use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, VertexRecord};
use crate::{BrepSolid, Vec3};

/// A reading this near the line is on it (parameter units).
const ON_LINE: f64 = 1e-7;
/// A pcurve may stray this far over the line beside a vertex on it: a chart
/// run's pcurve wanders so at a fold's fixed point, along the direction the
/// surface's rates lose there, which costs nothing in space. It is left as it
/// is (the surface is read at its edge there): bringing its poles back to
/// their side moved the curve 6e-4 in space. Farther is a crossing
/// missed.
const STRAY: f64 = 1e-2;

/// A crease shorter than this (in space) whose runs meet before its tip is dropped.
const MICRO: f64 = 1e-3;
/// A crease shorter than this (in space) may have its two pcurves laid straight.
const SHORT: f64 = 2e-2;
/// Two runs of a crease this near each other on the (u, v) plane, at the same
/// point of the edge, are on one path.
const SPUR: f64 = 1e-4;

/// A cut's end may be this far (in space) from the vertex it ends at.
const OFF_VERTEX: f64 = 1e-5;

type Uv = (f64, f64);


fn at(coedge: &CoedgeRecord, fraction: f64) -> Result<Uv, String> {
    let [q0, q1] = coedge.pcurve.domain()?;
    let p = coedge.pcurve.evaluate(q0 + (q1 - q0) * fraction)?;
    Ok((p.x, p.y))
}

fn pick(p: Uv, axis: usize) -> f64 {
    if axis == 0 {
        p.0
    } else {
        p.1
    }
}

fn stations(coedge: &CoedgeRecord) -> usize {
    (8 * coedge.pcurve.control_points.len()).clamp(32, 2048)
}

fn next_id(solid: &BrepSolid) -> u64 {
    let mut top = solid.id;
    top = solid.vertices.iter().fold(top, |m, v| m.max(v.id));
    top = solid.edges.iter().fold(top, |m, e| m.max(e.id));
    for shell in &solid.shells {
        top = top.max(shell.id);
        for face in &shell.faces {
            top = top.max(face.id);
            for lp in &face.loops {
                top = lp.coedges.iter().fold(top.max(lp.id), |m, c| m.max(c.id));
            }
        }
    }
    top + 1
}

/// The first loop that runs one edge out and straight back: (shell, face, the
/// fixed point on the (u, v) plane, the curve's direction through it).
#[allow(clippy::type_complexity)]
fn crease(solid: &BrepSolid) -> Result<Option<(usize, usize, usize, usize, Uv, Uv)>, String> {
    for (si, shell) in solid.shells.iter().enumerate() {
        for (fi, face) in shell.faces.iter().enumerate() {
            for (li, lp) in face.loops.iter().enumerate() {
                let n = lp.coedges.len();
                for i in 0..n {
                    let j = (i + 1) % n;
                    if i != j && lp.coedges[i].edge_id == lp.coedges[j].edge_id {
                        let tip = at(&lp.coedges[i], 1.0)?;
                        let (a, b) = (at(&lp.coedges[i], 0.9)?, at(&lp.coedges[j], 0.1)?);
                        return Ok(Some((si, fi, li, i, tip, (b.0 - a.0, b.1 - a.1))));
                    }
                }
            }
        }
    }
    Ok(None)
}

/// Whether any face uses an edge twice.
fn twice(solid: &BrepSolid) -> Option<(u64, u64)> {
    for shell in &solid.shells {
        for face in &shell.faces {
            let mut seen = std::collections::HashSet::new();
            for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
                if !seen.insert(coedge.edge_id) {
                    return Some((face.id, coedge.edge_id));
                }
            }
        }
    }
    None
}

/// Every face whose loop runs an edge out and back, cut at the fold's fixed
/// point; the number of cuts. Refuses where a face cannot be cut so, or where
/// a face still uses an edge twice afterwards.
pub(crate) fn unzip_creases(solid: &mut BrepSolid) -> Result<usize, String> {
    let (mut cuts, mut dropped) = (0, 0);
    let mut tips: Vec<u64> = Vec::new();
    while let Some((si, fi, li, at_coedge, tip, along)) = crease(solid)? {
        cuts += 1;
        if cuts > 64 {
            return Err("a fold crease does not come apart (over 64 cuts)".into());
        }
        let lp = &solid.shells[si].faces[fi].loops[li];
        let (own, mate) = (at_coedge, (at_coedge + 1) % lp.coedges.len());
        let edge_id = lp.coedges[own].edge_id;
        let edge = solid.edges.iter().find(|e| e.id == edge_id).ok_or("a coedge's edge is missing")?;
        let mut length = 0.0;
        let mut last = edge.curve.evaluate(edge.t0)?;
        for k in 1..=16 {
            let here = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * k as f64 / 16.0)?;
            length += here.sub(last).length();
            last = here;
        }
        // A short crease whose two runs come together before its tip: the
        // trim's fixed point, read where a mate falls onto the point itself,
        // is set beyond where the runs meet, and from there on they waver
        // within that reading, so the crease has no tip to cut at. It is
        // dropped whole (its two coedges, the edge, the tip): the loop passes
        // its foot once, with a step on the (u, v) plane from the own run's
        // foot to the mate run's, both the one point in space.
        let apart = |f: f64| -> Result<f64, String> {
            let (a, b) = (at(&lp.coedges[own], f)?, at(&lp.coedges[mate], 1.0 - f)?);
            Ok((a.0 - b.0).hypot(a.1 - b.1))
        };
        let mut meet = 1.0;
        for k in 1..256 {
            let f = k as f64 / 256.0;
            if apart(f)? <= SPUR {
                meet = f;
                break;
            }
        }
        if std::env::var("BREP_TUBE_TRACE_UNZIP").is_ok() {
            let mut line = format!("unzip crease: face {} edge {edge_id} length {length:.3e} meet {meet:.4} apart", solid.shells[si].faces[fi].id);
            for k in 0..=16 {
                line += &format!(" {:.2e}", apart(k as f64 / 16.0)?);
            }
            eprintln!("{line}");
        }
        if meet < 0.98 && length < MICRO && lp.coedges.len() >= 4 {
            let forward = lp.coedges[own].forward;
            let (lp_own, lp_mate) = (lp.coedges[own].clone(), lp.coedges[mate].clone());
            let tip_vertex = if forward { edge.end_vertex_id } else { edge.start_vertex_id };
            solid.shells[si].faces[fi].loops[li].coedges.retain(|c| c.edge_id != edge_id);
            solid.edges.retain(|e| e.id != edge_id);
            if !solid.edges.iter().any(|e| e.start_vertex_id == tip_vertex || e.end_vertex_id == tip_vertex) {
                solid.vertices.retain(|v| v.id != tip_vertex);
            }
            cuts -= 1;
            dropped += 1;
            // The face is then cut through the mate run's foot, across the
            // step, so the edge that leaves that foot is on a part of the
            // surface the own run's foot is not on (where it can be: the cut
            // may not run along an edge of the face).
            let (foot, far) = (at(&lp_own, 0.0)?, at(&lp_mate, 1.0)?);
            let step = (far.0 - foot.0, far.1 - foot.1);
            for axis in if step.0.abs() >= step.1.abs() { [0, 1] } else { [1, 0] } {
                let mut trial = solid.clone();
                if cut_face(&mut trial, si, fi, axis, pick(far, axis), Some(pick(far, 1 - axis)), true).is_ok() {
                    *solid = trial;
                    break;
                }
            }
            continue;
        }
        // The cut, along the line that crosses the curve at the fixed point
        // (of constant u where the curve runs mostly along u). Where neither
        // line cuts the face, a short crease's two pcurves are laid straight,
        // foot to tip to foot, and the cut tried again: read on few stations
        // beside the fixed point they waver across each other and across the
        // line, and a straight run is within the crease's length of the edge.
        tips.push(if lp.coedges[own].forward { edge.end_vertex_id } else { edge.start_vertex_id });
        let (foot, far) = (at(&lp.coedges[own], 0.0)?, at(&lp.coedges[mate], 1.0)?);
        // Of the two lines through the fixed point, the one that leaves it
        // faster in space first: the surface's two rates run together there
        // (the curve's own direction is the one they lose), and a cut that
        // creeps away beside the fold's curve is no better told from it than
        // the curve's other run was (a reader that walks out of the tip along
        // the curve kept to a cut line 3e-6 from it).
        let fastest = {
            let surface = &solid.shells[si].faces[fi].surface;
            let here = surface.evaluate_extended(tip.0, tip.1)?;
            let h = 1e-5;
            let rate = |du: f64, dv: f64| -> Result<f64, String> {
                let (a, b) = (surface.evaluate_extended(tip.0 + du, tip.1 + dv)?, surface.evaluate_extended(tip.0 - du, tip.1 - dv)?);
                Ok(a.sub(here).length().max(b.sub(here).length()))
            };
            // the line of constant u runs along v, and the other way about
            let (along_v, along_u) = (rate(0.0, h)?, rate(h, 0.0)?);
            if std::env::var("BREP_TUBE_TRACE_UNZIP").is_ok() {
                eprintln!("unzip rates: face {} edge {edge_id} tip ({:.6}, {:.6}) along v {along_v:.3e} along u {along_u:.3e} curve ({:.3e}, {:.3e})", solid.shells[si].faces[fi].id, tip.0, tip.1, along.0, along.1);
            }
            if along_v >= along_u { [0, 1] } else { [1, 0] }
        };
        let mut why = String::new();
        let mut done = false;
        'tries: for straight in [false, true] {
            if straight && !(length < SHORT) {
                break;
            }
            let mut base = solid.clone();
            let mut along = along;
            if straight {
                let line = |a: Uv, b: Uv| crate::make_line(Vec3::new(a.0, a.1, 0.0), Vec3::new(b.0, b.1, 0.0));
                let lp = &mut base.shells[si].faces[fi].loops[li];
                lp.coedges[own].pcurve = line(foot, tip)?;
                lp.coedges[mate].pcurve = line(tip, far)?;
                along = (far.0 - foot.0, far.1 - foot.1);
            }
            for axis in if straight { if along.0.abs() >= along.1.abs() { [0, 1] } else { [1, 0] } } else { fastest } {
                let mut trial = base.clone();
                match cut_face(&mut trial, si, fi, axis, pick(tip, axis), Some(pick(tip, 1 - axis)), false) {
                    Ok(()) => {
                        *solid = trial;
                        done = true;
                        break 'tries;
                    }
                    Err(e) => why = format!("{why}{}{}{} = {}: {e}", if why.is_empty() { "" } else { "; " }, if straight { "straight, " } else { "" }, if axis == 0 { "u" } else { "v" }, pick(tip, axis)),
                }
            }
        }
        if !done {
            return Err(format!("a fold crease's face cannot be cut at its fixed point (face {}, edge {edge_id}, length {length:.3e}): {why}", solid.shells[si].faces[fi].id));
        }
    }
    // No loop passes two folds' tips: it can start at one only, and at the
    // other a reader arrives along the cut and sets out along the fold's edge
    // (or the other way about, walked the other way round). A face whose loop
    // would is cut once more, along a line between the two.
    let mut parted = 0;
    let mut left: Vec<u64> = Vec::new();
    loop {
        let mut found = None;
        'faces: for (si, shell) in solid.shells.iter().enumerate() {
            for (fi, face) in shell.faces.iter().enumerate() {
                if left.contains(&face.id) {
                    continue;
                }
                for lp in &face.loops {
                    let mut here: Vec<(u64, Uv)> = Vec::new();
                    for c in &lp.coedges {
                        let Some(edge) = solid.edges.iter().find(|e| e.id == c.edge_id) else { continue };
                        let end = if c.forward { edge.end_vertex_id } else { edge.start_vertex_id };
                        if tips.contains(&end) && !here.iter().any(|(v, _)| *v == end) {
                            here.push((end, at(c, 1.0)?));
                        }
                    }
                    if here.len() >= 2 {
                        found = Some((si, fi, face.id, here[0].1, here[1].1));
                        break 'faces;
                    }
                }
            }
        }
        let Some((si, fi, face_id, a, b)) = found else { break };
        parted += 1;
        if parted > 32 {
            return Err("two fold tips on one loop do not come apart (over 32 cuts)".into());
        }
        let mut done = false;
        for axis in if (a.0 - b.0).abs() >= (a.1 - b.1).abs() { [0, 1] } else { [1, 0] } {
            let mut trial = solid.clone();
            let cut = cut_face(&mut trial, si, fi, axis, 0.5 * (pick(a, axis) + pick(b, axis)), None, false);
            if std::env::var("BREP_TUBE_TRACE_UNZIP").is_ok() {
                eprintln!("unzip apart: face {face_id} tips ({:.6}, {:.6}) ({:.6}, {:.6}) axis {axis}: {cut:?}", a.0, a.1, b.0, b.1);
            }
            if cut.is_ok() {
                *solid = trial;
                done = true;
                break;
            }
        }
        if !done {
            left.push(face_id);
        }
    }
    // Each loop through a fold's tip starts there. The surface's two rates
    // run together at the tip and its sheets lie within a hair of the fold's
    // curve beside it, so a reader that follows a loop on the surface from
    // edge to edge loses the fold's edge when it sets out along it from the
    // tip; a loop's first edge it reads from the middle outwards, and its last
    // it reads into the tip. Either way round the loop is walked, then, the
    // fold's edge is first or last.
    let ends: std::collections::HashMap<u64, (u64, u64)> = solid.edges.iter().map(|e| (e.id, (e.start_vertex_id, e.end_vertex_id))).collect();
    for lp in solid.shells.iter_mut().flat_map(|s| &mut s.faces).flat_map(|f| &mut f.loops) {
        let found = lp.coedges.iter().position(|c| ends.get(&c.edge_id).is_some_and(|(start, end)| tips.contains(if c.forward { end } else { start })));
        if let Some(k) = found {
            let n = lp.coedges.len();
            lp.coedges.rotate_left((k + 1) % n);
        }
    }
    if let Some((face, edge)) = twice(solid) {
        return Err(format!("face {face} uses edge {edge} twice"));
    }
    if cuts + dropped + parted > 0 {
        solid.mass_properties_cache = Default::default();
    }
    Ok(cuts)
}

/// Edge `edge_id` cut at `fraction` of its range, and every coedge on it with
/// it (a coedge's pcurve at the same fraction, from its own start).
fn split_edge(solid: &mut BrepSolid, edge_id: u64, fraction: f64) -> Result<(), String> {
    let mut id = next_id(solid);
    let mut fresh = || {
        id += 1;
        id - 1
    };
    let index = solid.edges.iter().position(|e| e.id == edge_id).ok_or("a coedge's edge is missing")?;
    let edge = solid.edges[index].clone();
    let s = edge.t0 + (edge.t1 - edge.t0) * fraction;
    let vertex = fresh();
    solid.vertices.push(VertexRecord { id: vertex, point: edge.curve.evaluate(s)? });
    let second = fresh();
    solid.edges[index].t1 = s;
    solid.edges[index].end_vertex_id = vertex;
    solid.edges.push(EdgeRecord { id: second, curve: edge.curve.clone(), t0: s, t1: edge.t1, start_vertex_id: vertex, end_vertex_id: edge.end_vertex_id, degenerate: false, name: edge.name.clone() });
    for shell in &mut solid.shells {
        for face in &mut shell.faces {
            for lp in &mut face.loops {
                let mut out = Vec::with_capacity(lp.coedges.len() + 1);
                for coedge in lp.coedges.drain(..) {
                    if coedge.edge_id != edge_id {
                        out.push(coedge);
                        continue;
                    }
                    let [q0, q1] = coedge.pcurve.domain()?;
                    let f = if coedge.forward { fraction } else { 1.0 - fraction };
                    let (head, tail) = coedge.pcurve.split(q0 + (q1 - q0) * f)?;
                    let (first, last) = if coedge.forward { (edge_id, second) } else { (second, edge_id) };
                    out.push(CoedgeRecord { id: coedge.id, edge_id: first, forward: coedge.forward, pcurve: head });
                    out.push(CoedgeRecord { id: fresh(), edge_id: last, forward: coedge.forward, pcurve: tail });
                }
                lp.coedges = out;
            }
        }
    }
    Ok(())
}

/// Where a coedge's pcurve crosses `axis = value` strictly inside it (not
/// within ON_LINE of either end): the fraction along it.
fn crossing(coedge: &CoedgeRecord, axis: usize, value: f64) -> Result<Option<f64>, String> {
    let n = stations(coedge);
    let g = |f: f64| -> Result<f64, String> { Ok(pick(at(coedge, f)?, axis) - value) };
    let (start, end) = (at(coedge, 0.0)?, at(coedge, 1.0)?);
    let mut last: Option<(f64, f64)> = None;
    for k in 0..=n {
        let f = k as f64 / n as f64;
        let here = g(f)?;
        if here.abs() <= ON_LINE {
            continue;
        }
        if let Some((mut fa, ga)) = last {
            if ga * here < 0.0 {
                let mut fb = f;
                for _ in 0..80 {
                    let fm = 0.5 * (fa + fb);
                    if g(fm)? * ga > 0.0 {
                        fa = fm;
                    } else {
                        fb = fm;
                    }
                }
                let root = 0.5 * (fa + fb);
                let p = at(coedge, root)?;
                let far = |q: Uv| (p.0 - q.0).hypot(p.1 - q.1) > 10.0 * ON_LINE;
                if far(start) && far(end) {
                    return Ok(Some(root));
                }
            }
        }
        last = Some((f, here));
    }
    Ok(None)
}

/// Which side of `axis = value` a coedge lies on (+1 or -1).
fn side(coedge: &CoedgeRecord, axis: usize, value: f64) -> Result<f64, String> {
    let n = stations(coedge);
    let (mut least, mut most) = (0.0f64, 0.0f64);
    for k in 0..=n {
        let here = pick(at(coedge, k as f64 / n as f64)?, axis) - value;
        least = least.min(here);
        most = most.max(here);
    }
    if most.max(-least) <= ON_LINE {
        return Err("an edge of the face runs along the cut".into());
    }
    if most > -least {
        if least < -STRAY {
            return Err(format!("edge {} crosses the cut unseen ({least:.3e} to {most:.3e}, from ({:.6}, {:.6}) to ({:.6}, {:.6}))", coedge.edge_id, at(coedge, 0.0)?.0, at(coedge, 0.0)?.1, at(coedge, 1.0)?.0, at(coedge, 1.0)?.1));
        }
        Ok(1.0)
    } else {
        if most > STRAY {
            return Err(format!("edge {} crosses the cut unseen ({least:.3e} to {most:.3e}, from ({:.6}, {:.6}) to ({:.6}, {:.6}))", coedge.edge_id, at(coedge, 0.0)?.0, at(coedge, 0.0)?.1, at(coedge, 1.0)?.0, at(coedge, 1.0)?.1));
        }
        Ok(-1.0)
    }
}

fn outline(lp: &[CoedgeRecord]) -> Result<Vec<Uv>, String> {
    let mut points = Vec::with_capacity(lp.len() * 16);
    for coedge in lp {
        for k in 0..16 {
            points.push(at(coedge, k as f64 / 16.0)?);
        }
    }
    Ok(points)
}

fn area(points: &[Uv]) -> f64 {
    let n = points.len();
    0.5 * (0..n).map(|i| points[i].0 * points[(i + 1) % n].1 - points[(i + 1) % n].0 * points[i].1).sum::<f64>()
}

fn inside(points: &[Uv], p: Uv) -> bool {
    let n = points.len();
    let mut odd = false;
    for i in 0..n {
        let (a, b) = (points[i], points[(i + 1) % n]);
        if (a.1 > p.1) != (b.1 > p.1) && p.0 < a.0 + (p.1 - a.1) / (b.1 - a.1) * (b.0 - a.0) {
            odd = !odd;
        }
    }
    odd
}

struct Crossing {
    lp: usize,
    /// The coedge that ends at it.
    coedge: usize,
    /// Where on the line.
    w: f64,
    /// Whether the boundary leaves the + side there.
    leaves_plus: bool,
    vertex: u64,
}

/// Face `fi` of shell `si` cut along the whole line `axis = value` (axis 0: a
/// line of constant u) into faces on the surface's two parts; the line must
/// cross the face's boundary at `tip` (its other coordinate).
fn cut_face(solid: &mut BrepSolid, si: usize, fi: usize, axis: usize, value: f64, tip: Option<f64>, step: bool) -> Result<(), String> {
    // 1. Every edge the line crosses inside is cut there, on every face.
    for round in 0.. {
        if round > 256 {
            return Err("the cut crosses the face's boundary too often".into());
        }
        let mut found = None;
        'search: for lp in &solid.shells[si].faces[fi].loops {
            for coedge in &lp.coedges {
                if let Some(f) = crossing(coedge, axis, value)? {
                    found = Some((coedge.edge_id, if coedge.forward { f } else { 1.0 - f }));
                    break 'search;
                }
            }
        }
        let Some((edge_id, fraction)) = found else { break };
        split_edge(solid, edge_id, fraction)?;
    }
    let face = solid.shells[si].faces[fi].clone();
    // 2. Each coedge's side, and the vertices where the boundary changes side.
    let mut sides: Vec<Vec<f64>> = Vec::new();
    for lp in &face.loops {
        sides.push(lp.coedges.iter().map(|c| side(c, axis, value)).collect::<Result<_, _>>()?);
    }
    let mut crossings: Vec<Crossing> = Vec::new();
    for (l, lp) in face.loops.iter().enumerate() {
        let n = lp.coedges.len();
        for i in 0..n {
            let j = (i + 1) % n;
            if sides[l][i] == sides[l][j] {
                continue;
            }
            // (where a dropped crease left a step there, the end that is on the line)
            let mut p = at(&lp.coedges[i], 1.0)?;
            if step && (pick(p, axis) - value).abs() > 10.0 * ON_LINE {
                p = at(&lp.coedges[j], 0.0)?;
            }
            if (pick(p, axis) - value).abs() > 10.0 * ON_LINE {
                return Err("the boundary changes side off the cut".into());
            }
            let coedge = &lp.coedges[i];
            let edge = solid.edges.iter().find(|e| e.id == coedge.edge_id).ok_or("a coedge's edge is missing")?;
            let vertex = if coedge.forward { edge.end_vertex_id } else { edge.start_vertex_id };
            crossings.push(Crossing { lp: l, coedge: i, w: pick(p, 1 - axis), leaves_plus: sides[l][i] > 0.0, vertex });
        }
    }
    if crossings.len() < 2 || crossings.len() % 2 != 0 {
        return Err(format!("the cut meets the boundary {} times", crossings.len()));
    }
    if tip.is_some_and(|tip| !crossings.iter().any(|x| (x.w - tip).abs() <= 10.0 * ON_LINE)) {
        return Err("the cut does not cross the boundary at the fixed point".into());
    }
    crossings.sort_by(|a, b| a.w.total_cmp(&b.w));
    // 3. The cut's edges: between the crossings by twos along the line.
    let (before, after) = crate::split_surface(&face.surface, axis == 1, value)?;
    let iso = if axis == 0 { face.surface.iso_curve_u(value)? } else { face.surface.iso_curve_v(value)? };
    let mut id = next_id(solid);
    let mut fresh = || {
        id += 1;
        id - 1
    };
    let mut partner = vec![0usize; crossings.len()];
    let mut cut_edge = vec![0u64; crossings.len()];
    for k in (0..crossings.len()).step_by(2) {
        let (a, b) = (&crossings[k], &crossings[k + 1]);
        if a.leaves_plus == b.leaves_plus {
            return Err("the cut's crossings do not alternate".into());
        }
        if !(b.w - a.w > 10.0 * ON_LINE) {
            return Err("the cut has no length between two crossings".into());
        }
        for x in [a, b] {
            let vertex = solid.vertices.iter().find(|v| v.id == x.vertex).ok_or("a crossing's vertex is missing")?.point;
            let gap = iso.evaluate(x.w)?.sub(vertex).length();
            if gap > OFF_VERTEX {
                return Err(format!("the cut's end is {gap:.3e} off its vertex {} (loop {} coedge {} at {:.6})", x.vertex, x.lp, x.coedge, x.w));
            }
        }
        let edge = fresh();
        solid.edges.push(EdgeRecord { id: edge, curve: iso.clone(), t0: a.w, t1: b.w, start_vertex_id: a.vertex, end_vertex_id: b.vertex, degenerate: false, name: None });
        (partner[k], partner[k + 1]) = (k + 1, k);
        (cut_edge[k], cut_edge[k + 1]) = (edge, edge);
    }
    let on_line = |w: f64| if axis == 0 { Vec3::new(value, w, 0.0) } else { Vec3::new(w, value, 0.0) };
    // 4. The loops of each side: a run of the boundary on that side, the cut
    // to the crossing it is paired with, the run that starts there, and so on.
    let mut made: [Vec<Vec<CoedgeRecord>>; 2] = [Vec::new(), Vec::new()];
    for (l, lp) in face.loops.iter().enumerate() {
        if !crossings.iter().any(|x| x.lp == l) {
            made[usize::from(sides[l][0] > 0.0)].push(lp.coedges.clone());
        }
    }
    let mut used = vec![false; crossings.len()];
    for first in 0..crossings.len() {
        if used[first] {
            continue;
        }
        // The run that starts at crossing `first`.
        let plus = !crossings[first].leaves_plus;
        let mut coedges = Vec::new();
        let mut k = first;
        loop {
            if used[k] {
                return Err("the cut's loops do not close".into());
            }
            used[k] = true;
            let lp = &face.loops[crossings[k].lp].coedges;
            let n = lp.len();
            let mut i = (crossings[k].coedge + 1) % n;
            // to the crossing that ends this run
            let out = loop {
                coedges.push(lp[i].clone());
                if let Some(out) = crossings.iter().position(|x| x.lp == crossings[k].lp && x.coedge == i) {
                    break out;
                }
                i = (i + 1) % n;
                if coedges.len() > 100_000 {
                    return Err("the cut's loops do not close".into());
                }
            };
            let to = partner[out];
            let pcurve = crate::make_line(on_line(crossings[out].w), on_line(crossings[to].w))?;
            coedges.push(CoedgeRecord { id: fresh(), edge_id: cut_edge[out], forward: crossings[out].w < crossings[to].w, pcurve });
            k = to;
            if k == first {
                break;
            }
        }
        made[usize::from(plus)].push(coedges);
    }
    // 5. Faces: each outer loop with the holes inside it, on its side's part
    // of the surface.
    let mut whole = 0.0f64;
    for lp in &face.loops {
        let a = area(&outline(&lp.coedges)?);
        if a.abs() > whole.abs() {
            whole = a;
        }
    }
    let mut faces: Vec<FaceRecord> = Vec::new();
    for (s, loops) in made.into_iter().enumerate() {
        let surface = if s == 1 { &after } else { &before };
        let outlines = loops.iter().map(|lp| outline(lp)).collect::<Result<Vec<_>, _>>()?;
        let outer: Vec<usize> = (0..loops.len()).filter(|&k| area(&outlines[k]) * whole > 0.0).collect();
        let mut groups: Vec<Vec<usize>> = outer.iter().map(|&k| vec![k]).collect();
        for k in 0..loops.len() {
            if outer.contains(&k) {
                continue;
            }
            let home = outer.iter().position(|&o| inside(&outlines[o], outlines[k][0])).ok_or("a hole of the cut face lies in none of its parts")?;
            groups[home].push(k);
        }
        for group in groups {
            let loops = group.into_iter().map(|k| LoopRecord { id: fresh(), coedges: loops[k].clone() }).collect();
            faces.push(FaceRecord { id: fresh(), surface: surface.clone(), same_sense: face.same_sense, loops, name: face.name.clone() });
        }
    }
    if faces.len() < 2 {
        return Err("the cut leaves the face whole".into());
    }
    faces[0].id = face.id;
    let rest = faces.split_off(1);
    solid.shells[si].faces[fi] = faces.pop().ok_or("the cut leaves no face")?;
    solid.shells[si].faces.extend(rest);
    Ok(())
}