brepkit-wasm 3.2.16

WebAssembly bindings for brepkit — browser-native B-Rep solid modeling
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Shared free functions and constants used across WASM binding modules.

#![allow(
    clippy::missing_errors_doc,
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss
)]

use brepkit_math::mat::Mat4;
use brepkit_math::vec::{Point2, Point3, Vec3};
use brepkit_operations::boolean::BooleanOp;
use brepkit_operations::tessellate;
use brepkit_topology::Topology;
use wasm_bindgen::prelude::*;

use crate::error::WasmError;
use crate::handles::face_id_to_u32;
use crate::shapes::JsMesh;

/// Default tolerance for vertices created by the kernel.
pub const TOL: f64 = 1e-7;

// ── Parsing helpers ───────────────────────────────────────────────

/// Parse flat `[x,y,z, ...]` coordinates into `Vec<Point3>`.
pub fn parse_points(coords: &[f64]) -> Result<Vec<Point3>, JsError> {
    if !coords.len().is_multiple_of(3) {
        return Err(WasmError::InvalidInput {
            reason: format!(
                "coordinate array length must be a multiple of 3, got {}",
                coords.len()
            ),
        }
        .into());
    }
    Ok(coords
        .chunks_exact(3)
        .map(|c| Point3::new(c[0], c[1], c[2]))
        .collect())
}

/// Parse flat coordinates into a 2D grid of points.
pub fn parse_point_grid(
    coords: &[f64],
    rows: usize,
    cols: usize,
) -> Result<Vec<Vec<Point3>>, JsError> {
    if rows == 0 || cols == 0 {
        return Err(WasmError::InvalidInput {
            reason: format!("rows and cols must be > 0, got {rows}x{cols}"),
        }
        .into());
    }
    let total = rows
        .checked_mul(cols)
        .ok_or_else(|| WasmError::InvalidInput {
            reason: format!("rows*cols overflow: {rows}*{cols}"),
        })?;
    let points = parse_points(coords)?;
    if points.len() != total {
        return Err(WasmError::InvalidInput {
            reason: format!(
                "expected {total} points ({rows}x{cols}), got {}",
                points.len()
            ),
        }
        .into());
    }
    Ok(points.chunks(cols).map(<[Point3]>::to_vec).collect())
}

/// Parse a flat 16-element array into a `Mat4` (row-major).
pub fn parse_mat4(elems: &[f64]) -> Result<Mat4, JsError> {
    if elems.len() != 16 {
        return Err(WasmError::InvalidInput {
            reason: format!("matrix requires 16 elements, got {}", elems.len()),
        }
        .into());
    }
    let rows = std::array::from_fn(|i| std::array::from_fn(|j| elems[i * 4 + j]));
    Ok(Mat4(rows))
}

/// Convert a `Mat4` to a flat 16-element f64 array for JSON (row-major).
pub fn mat4_to_array(mat: &Mat4) -> Vec<f64> {
    let mut out = Vec::with_capacity(16);
    for row in &mat.0 {
        for &v in row {
            out.push(v);
        }
    }
    out
}

/// Parse a boolean operation string to the enum.
pub fn parse_boolean_op(op: &str) -> Result<BooleanOp, JsError> {
    match op {
        "fuse" | "union" => Ok(BooleanOp::Fuse),
        "cut" | "difference" => Ok(BooleanOp::Cut),
        "intersect" | "intersection" => Ok(BooleanOp::Intersect),
        _ => Err(WasmError::InvalidInput {
            reason: format!("unknown boolean op: {op}"),
        }
        .into()),
    }
}

/// Extract a required `f64` value from a JSON object.
pub fn get_f64(args: &serde_json::Value, key: &str) -> Result<f64, String> {
    args[key]
        .as_f64()
        .ok_or_else(|| format!("missing or invalid '{key}'"))
}

/// Extract a required `u32` value from a JSON object.
pub fn get_u32(args: &serde_json::Value, key: &str) -> Result<u32, String> {
    args[key]
        .as_u64()
        .map(|v| v as u32)
        .ok_or_else(|| format!("missing or invalid '{key}'"))
}

/// Extract a `usize` from a JSON value.
pub fn json_usize(val: &serde_json::Value, key: &str) -> Result<usize, JsError> {
    val[key].as_u64().map(|v| v as usize).ok_or_else(|| {
        WasmError::InvalidInput {
            reason: format!("missing or invalid '{key}'"),
        }
        .into()
    })
}

/// Extract an `f64` from a JSON value.
pub fn json_f64(val: &serde_json::Value, key: &str) -> Result<f64, JsError> {
    val[key].as_f64().ok_or_else(|| {
        WasmError::InvalidInput {
            reason: format!("missing or invalid '{key}'"),
        }
        .into()
    })
}

// ── Edge/face helpers ─────────────────────────────────────────────

/// Attempt a fillet, preferring the rolling-ball engine and validating output.
///
/// The rolling-ball engine produces watertight single-edge fillets, does the
/// per-corner setback trimming + spherical patches multi-edge inputs need
/// (the walking `FilletBuilder` over-removes corner material — all 12 box edges
/// drop to ~470 instead of ~975), and now solves true contacts against curved
/// neighbours, so a fillet whose neighbour is a prior fillet's NURBS blend face
/// is watertight too (#834). It runs first; the `FilletBuilder` and a flat
/// bevel are fallbacks.
///
/// Every candidate is validated as a closed (watertight) solid before being
/// accepted, so a malformed result is rejected in favour of the next engine
/// and, if none qualifies, the solid is returned unchanged. This guard lets
/// `filter_filletable_edges` be permissive about curved neighbours without ever
/// returning a degenerate solid.
#[allow(deprecated)]
pub fn try_fillet(
    topo: &mut brepkit_topology::Topology,
    solid_id: brepkit_topology::solid::SolidId,
    edge_ids: &[brepkit_topology::edge::EdgeId],
    radius: f64,
) -> Result<brepkit_topology::solid::SolidId, brepkit_operations::OperationsError> {
    // Drop tangent / degenerate edges (e.g. a fillet face's G1 contact line with
    // its planar neighbour). If none qualify, the solid is returned unchanged.
    let edges = brepkit_operations::query::filter_filletable_edges(topo, solid_id, edge_ids)?;
    if edges.is_empty() {
        return Ok(solid_id);
    }
    let edges = edges.as_slice();

    // A candidate is acceptable only if its outer shell is a CLOSED 2-manifold
    // (every edge used by exactly two faces — no free/boundary edges). The
    // weaker manifold-only check silently accepted open shells (e.g. a fillet
    // that leaves a cap untrimmed at a contact circle), which tessellate to a
    // plausible-but-wrong volume; reject them so the next engine or the
    // unchanged input is used.
    let is_valid =
        |topo: &brepkit_topology::Topology, s: brepkit_topology::solid::SolidId| -> bool {
            topo.solid(s)
                .and_then(|sd| topo.shell(sd.outer_shell()))
                .map(|sh| brepkit_topology::validation::validate_shell_closed(sh, topo).is_ok())
                .unwrap_or(false)
        };

    // Try engines in preference order; accept the first valid result.
    if let Ok(s) = brepkit_operations::fillet::fillet_rolling_ball(topo, solid_id, edges, radius)
        && is_valid(topo, s)
    {
        return Ok(s);
    }
    if let Ok(r) = brepkit_operations::blend_ops::fillet_v2(topo, solid_id, edges, radius)
        && is_valid(topo, r.solid)
    {
        return Ok(r.solid);
    }
    if let Ok(s) = brepkit_operations::fillet::fillet(topo, solid_id, edges, radius)
        && is_valid(topo, s)
    {
        return Ok(s);
    }

    // No engine produced a valid solid — leave the input unchanged.
    Ok(solid_id)
}

/// Extract a human-readable message from a `catch_unwind` panic payload.
pub fn panic_message(payload: &Box<dyn std::any::Any + Send>, operation: &str) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        format!("{operation} operation panicked: {s}")
    } else if let Some(s) = payload.downcast_ref::<String>() {
        format!("{operation} operation panicked: {s}")
    } else {
        format!("{operation} operation panicked (unknown cause)")
    }
}

/// Sample a closed periodic curve (period = TAU) into a flat `[x, y, z, ...]` buffer.
///
/// Produces `n` evenly-spaced points in `[0, TAU)` — the endpoint at `TAU` is
/// excluded because it duplicates `t = 0` on periodic curves. Callers that need
/// a closed polyline should append the first point or close the loop in JS.
///
/// Returns an empty buffer if `n == 0`.
pub fn sample_full_period_curve(n: usize, evaluate: impl Fn(f64) -> Point3) -> Vec<f64> {
    if n <= 1 {
        if n == 1 {
            let p = evaluate(0.0);
            return vec![p.x(), p.y(), p.z()];
        }
        return Vec::new();
    }
    let mut result = Vec::with_capacity(n * 3);
    for i in 0..n {
        let t = std::f64::consts::TAU * (i as f64) / (n as f64);
        let p = evaluate(t);
        result.push(p.x());
        result.push(p.y());
        result.push(p.z());
    }
    result
}

/// Create a tiny degenerate polygon face at a point, matching the vertex
/// count of the first existing profile. Used for loft start/end points.
pub fn create_apex_face(
    topo: &mut Topology,
    point: Point3,
    existing_profiles: &[brepkit_topology::face::FaceId],
) -> Result<brepkit_topology::face::FaceId, JsError> {
    // Determine target vertex count from the first profile.
    let n = if let Some(&fid) = existing_profiles.first() {
        let verts = brepkit_operations::boolean::face_polygon(topo, fid)
            .map_err(|e: brepkit_operations::OperationsError| JsError::new(&e.to_string()))?;
        verts.len().max(3)
    } else {
        3
    };

    // Create a tiny polygon at the apex point.
    let epsilon = 1e-6;
    let mut pts = Vec::with_capacity(n);
    for i in 0..n {
        let angle = 2.0 * std::f64::consts::PI * (i as f64) / (n as f64);
        pts.push(Point3::new(
            point.x() + epsilon * angle.cos(),
            point.y() + epsilon * angle.sin(),
            point.z(),
        ));
    }

    let wire_id = brepkit_topology::builder::make_polygon_wire(topo, &pts, TOL)
        .map_err(|e| JsError::new(&e.to_string()))?;
    let face_id = brepkit_topology::builder::make_face_from_wire(topo, wire_id)
        .map_err(|e| JsError::new(&e.to_string()))?;
    Ok(face_id)
}

// ── Mesh / tessellation helpers ───────────────────────────────────

/// Build a `TriangleMesh` from flat position/index arrays.
pub fn build_triangle_mesh(
    positions: &[f64],
    indices: &[u32],
) -> Result<tessellate::TriangleMesh, JsError> {
    if !positions.len().is_multiple_of(3) {
        return Err(WasmError::InvalidInput {
            reason: format!(
                "positions length must be a multiple of 3, got {}",
                positions.len()
            ),
        }
        .into());
    }
    let pts: Vec<Point3> = positions
        .chunks_exact(3)
        .map(|c| Point3::new(c[0], c[1], c[2]))
        .collect();
    // Compute normals as zero vectors (mesh_boolean recomputes them)
    let normals = vec![Vec3::new(0.0, 0.0, 0.0); pts.len()];
    Ok(tessellate::TriangleMesh {
        positions: pts,
        normals,
        indices: indices.to_vec(),
    })
}

/// Convert a `TriangleMesh` to `JsMesh`.
pub fn triangle_mesh_to_js(mesh: &tessellate::TriangleMesh) -> JsMesh {
    JsMesh::from(mesh.clone())
}

// ── Classification / serialization ────────────────────────────────

/// Convert a `PointClassification` to a string.
pub fn classify_to_string(c: brepkit_operations::classify::PointClassification) -> String {
    match c {
        brepkit_operations::classify::PointClassification::Inside => "inside".into(),
        brepkit_operations::classify::PointClassification::Outside => "outside".into(),
        brepkit_operations::classify::PointClassification::OnBoundary => "boundary".into(),
    }
}

/// Serialize a `Feature` enum to JSON.
pub fn serialize_feature(
    f: &brepkit_operations::feature_recognition::Feature,
) -> serde_json::Value {
    use brepkit_operations::feature_recognition::Feature;
    match f {
        Feature::Hole { faces, diameter } => serde_json::json!({
            "type": "hole",
            "faces": faces.iter().map(|f| face_id_to_u32(*f)).collect::<Vec<_>>(),
            "diameter": diameter,
        }),
        Feature::Chamfer {
            face,
            adjacent,
            angle,
        } => serde_json::json!({
            "type": "chamfer",
            "face": face_id_to_u32(*face),
            "adjacent": [face_id_to_u32(adjacent.0), face_id_to_u32(adjacent.1)],
            "angle": angle,
        }),
        Feature::FilletLike { face, area } => serde_json::json!({
            "type": "filletLike",
            "face": face_id_to_u32(*face),
            "area": area,
        }),
        Feature::Pocket { floor, walls } => serde_json::json!({
            "type": "pocket",
            "floor": face_id_to_u32(*floor),
            "walls": walls.iter().map(|f| face_id_to_u32(*f)).collect::<Vec<_>>(),
        }),
        Feature::Pattern {
            feature_indices,
            pattern_type,
            count,
            spacing,
        } => serde_json::json!({
            "type": "pattern",
            "featureIndices": feature_indices,
            "patternType": format!("{pattern_type:?}").to_lowercase(),
            "count": count,
            "spacing": spacing,
        }),
    }
}

// ── Sketch constraint parsing ─────────────────────────────────────

/// Parse a sketch constraint from a JSON value.
pub fn parse_sketch_constraint(
    val: &serde_json::Value,
) -> Result<brepkit_operations::sketch::Constraint, JsError> {
    use brepkit_operations::sketch::Constraint;
    let ty = val["type"].as_str().unwrap_or("");
    match ty {
        "coincident" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            Ok(Constraint::Coincident(p1, p2))
        }
        "distance" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            let v = json_f64(val, "value")?;
            Ok(Constraint::Distance(p1, p2, v))
        }
        "fixX" => {
            let p = json_usize(val, "point")?;
            let v = json_f64(val, "value")?;
            Ok(Constraint::FixX(p, v))
        }
        "fixY" => {
            let p = json_usize(val, "point")?;
            let v = json_f64(val, "value")?;
            Ok(Constraint::FixY(p, v))
        }
        "vertical" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            Ok(Constraint::Vertical(p1, p2))
        }
        "horizontal" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            Ok(Constraint::Horizontal(p1, p2))
        }
        "angle" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            // Backward compat: old API was (p1, p2, value) for single-line angle.
            // New API is (p1, p2, p3, p4, value) for angle between two lines.
            // When p3/p4 are absent, default to p1/p2 (zero angle between same line).
            let p3 = val
                .get("p3")
                .and_then(serde_json::Value::as_u64)
                .map_or(p1, |v| v as usize);
            let p4 = val
                .get("p4")
                .and_then(serde_json::Value::as_u64)
                .map_or(p2, |v| v as usize);
            let v = json_f64(val, "value")?;
            Ok(Constraint::Angle(p1, p2, p3, p4, v))
        }
        "perpendicular" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            let p3 = json_usize(val, "p3")?;
            let p4 = json_usize(val, "p4")?;
            Ok(Constraint::Perpendicular(p1, p2, p3, p4))
        }
        "parallel" => {
            let p1 = json_usize(val, "p1")?;
            let p2 = json_usize(val, "p2")?;
            let p3 = json_usize(val, "p3")?;
            let p4 = json_usize(val, "p4")?;
            Ok(Constraint::Parallel(p1, p2, p3, p4))
        }
        _ => Err(WasmError::InvalidInput {
            reason: format!("unknown constraint type: {ty}"),
        }
        .into()),
    }
}

// ── 2D polygon helpers ────────────────────────────────────────────

/// Parse flat `[x,y, ...]` coordinates into `Vec<Point2>`.
pub fn parse_polygon_2d(coords: &[f64]) -> Result<Vec<Point2>, JsError> {
    if !coords.len().is_multiple_of(2) || coords.len() < 6 {
        return Err(WasmError::InvalidInput {
            reason: "polygon needs at least 3 points (6 coordinates)".into(),
        }
        .into());
    }
    Ok(coords
        .chunks_exact(2)
        .map(|c| Point2::new(c[0], c[1]))
        .collect())
}

/// Check if two 2D polygons overlap using vertex containment + edge crossing.
pub fn polygons_overlap_2d(a: &[Point2], b: &[Point2]) -> bool {
    use brepkit_math::predicates::point_in_polygon;

    // Check if any vertex of A is inside B or vice versa.
    for p in a {
        if point_in_polygon(*p, b) {
            return true;
        }
    }
    for p in b {
        if point_in_polygon(*p, a) {
            return true;
        }
    }

    // Check edge crossings.
    for i in 0..a.len() {
        let a1 = a[i];
        let a2 = a[(i + 1) % a.len()];
        for j in 0..b.len() {
            let b1 = b[j];
            let b2 = b[(j + 1) % b.len()];
            if segments_intersect_2d(a1, a2, b1, b2) {
                return true;
            }
        }
    }
    false
}

/// Test if two 2D line segments intersect (proper crossing).
pub fn segments_intersect_2d(a1: Point2, a2: Point2, b1: Point2, b2: Point2) -> bool {
    use brepkit_math::polygon2d::cross_2d;
    let d1 = cross_2d(b1, b2, a1);
    let d2 = cross_2d(b1, b2, a2);
    let d3 = cross_2d(a1, a2, b1);
    let d4 = cross_2d(a1, a2, b2);

    ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0))
        && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
}

#[cfg(test)]
mod fillet_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use std::collections::HashSet;

    use brepkit_topology::Topology;
    use brepkit_topology::edge::EdgeId;
    use brepkit_topology::solid::SolidId;

    use super::try_fillet;

    fn solid_edge_ids(topo: &Topology, solid_id: SolidId) -> Vec<EdgeId> {
        let solid = topo.solid(solid_id).expect("solid");
        let shell = topo.shell(solid.outer_shell()).expect("shell");
        let mut seen = HashSet::new();
        let mut edges = Vec::new();
        for &fid in shell.faces() {
            let face = topo.face(fid).expect("face");
            let wire = topo.wire(face.outer_wire()).expect("wire");
            for oe in wire.edges() {
                if seen.insert(oe.edge().index()) {
                    edges.push(oe.edge());
                }
            }
        }
        edges
    }

    // The wasm `fillet` binding (and its batch sibling) route through
    // `try_fillet`. Filleting all 12 box edges must remove only the rounded
    // slivers (volume ≈ 975.6 for a 10³ box at r=1), not excise whole corner
    // octants. This guards the consumer path against regressing to the
    // over-removing walking engine.
    #[test]
    fn try_fillet_all_box_edges_no_corner_over_removal() {
        let mut topo = Topology::new();
        let cube = brepkit_operations::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
        let edges = solid_edge_ids(&topo, cube);
        assert_eq!(edges.len(), 12, "box should have 12 edges");

        let result = try_fillet(&mut topo, cube, &edges, 1.0).expect("all-edges fillet");
        let vol = brepkit_operations::measure::solid_volume(&topo, result, 0.01).unwrap();
        assert!(
            vol > 970.0 && vol < 1000.0,
            "filleted box volume should be ≈975.6, got {vol}"
        );
    }

    // gh #967: filleting a plain cylinder's circular rim used to remove ~37% of
    // the volume (the rolling-ball engine collapses closed circular edges). The
    // rim now rounds into an exact quarter-torus: the rolling-ball degenerate
    // result is rejected, `try_fillet` falls through to the walking engine, and
    // the watertight rounded solid (≈6275.7, a ~0.12% rim round) is accepted —
    // never the corrupt ~3978.
    #[test]
    fn try_fillet_cylinder_rim_rounds_not_corrupts() {
        use brepkit_topology::face::FaceSurface;

        let mut topo = Topology::new();
        let cyl = brepkit_operations::primitives::make_cylinder(&mut topo, 10.0, 20.0).unwrap();
        let raw = brepkit_operations::measure::solid_volume(&topo, cyl, 0.01).unwrap();
        let edges = solid_edge_ids(&topo, cyl);

        let result = try_fillet(&mut topo, cyl, &edges, 0.5).expect("rim fillet");
        let vol = brepkit_operations::measure::solid_volume(&topo, result, 0.01).unwrap();

        // A tiny rim round — well under 1% removed, never the −37% corruption.
        assert!(
            vol < raw && vol > raw * 0.99,
            "cylinder rim fillet should round (~{:.0}), got {vol} vs raw {raw}",
            raw * 0.999
        );
        let sh = topo
            .shell(topo.solid(result).unwrap().outer_shell())
            .unwrap();
        let torus_count = sh
            .faces()
            .iter()
            .filter(|&&fid| matches!(topo.face(fid).unwrap().surface(), FaceSurface::Torus(_)))
            .count();
        assert_eq!(torus_count, 2, "both rims round into toroidal bands");
        assert!(
            brepkit_operations::validate::validate_solid(&topo, result)
                .unwrap()
                .is_valid(),
            "rounded rim solid must be watertight"
        );
    }

    #[test]
    fn try_fillet_second_pass_does_not_break_solid() {
        use brepkit_topology::face::FaceSurface;

        // #813: a second fillet whose target edge borders the first fillet's
        // NURBS blend face must not produce a self-intersecting solid — the
        // volume grew past the base to 1000.30 before the fix; such edges are
        // now skipped. Checked over *every* result edge so the guard doesn't
        // rely on a particular edge ordering.
        let mut topo = Topology::new();
        let cube = brepkit_operations::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
        let edges = solid_edge_ids(&topo, cube);
        let first = try_fillet(&mut topo, cube, &[edges[0], edges[1]], 1.0).expect("first fillet");
        let v1 = brepkit_operations::measure::solid_volume(&topo, first, 0.05).unwrap();

        // The scenario under test only exists if the first fillet produced NURBS
        // blend faces for the later edges to border.
        let sd = topo.solid(first).expect("solid");
        let sh = topo.shell(sd.outer_shell()).expect("shell");
        let has_blend = sh.faces().iter().any(|&fid| {
            topo.face(fid)
                .is_ok_and(|f| matches!(f.surface(), FaceSurface::Nurbs(_)))
        });
        assert!(has_blend, "first fillet should create NURBS blend faces");

        // Filleting any single result edge must stay a manifold solid and must
        // not self-intersect/inflate past the original box volume (the #813 bug
        // grew it to 1000.30). A blend-adjacent *concave* end-cap edge validly
        // *fills* (volume rises toward — but never beyond — the box), so the
        // guard is the box volume, not the pre-fillet volume.
        let _ = v1;
        let r_edges = solid_edge_ids(&topo, first);
        for &e in &r_edges {
            let mut t = topo.clone();
            let s = try_fillet(&mut t, first, &[e], 0.5).expect("second fillet");
            let v2 = brepkit_operations::measure::solid_volume(&t, s, 0.05).unwrap();
            assert!(
                v2 <= 1000.0 + 0.1,
                "second fillet on edge {} inflated past the box: second={v2:.2}",
                e.index()
            );
            let ssd = t.solid(s).expect("result solid");
            let ssh = t.shell(ssd.outer_shell()).expect("shell");
            brepkit_topology::validation::validate_shell_manifold(ssh, &t)
                .expect("second fillet result must remain a manifold solid");
        }
    }

    #[test]
    fn try_fillet_nurbs_blend_neighbor_is_watertight() {
        use std::collections::HashMap;

        use brepkit_topology::validation::{validate_shell_closed, validate_shell_manifold};

        // #834 via the consumer path: a single fillet creates a NURBS blend
        // face; `try_fillet` on a non-tangent edge bordering it must round it
        // into a valid watertight manifold (rather than skip it as before).
        let mut topo = Topology::new();
        let cube = brepkit_operations::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
        let edges = solid_edge_ids(&topo, cube);
        let first = try_fillet(&mut topo, cube, &[edges[0]], 1.0).expect("first fillet");
        {
            let sh = topo
                .shell(topo.solid(first).unwrap().outer_shell())
                .unwrap();
            validate_shell_closed(sh, &topo).expect("first fillet should be watertight");
        }

        let blend_faces: HashSet<usize> = {
            let sh = topo
                .shell(topo.solid(first).unwrap().outer_shell())
                .unwrap();
            sh.faces()
                .iter()
                .filter(|&&f| !topo.face(f).unwrap().surface().is_planar())
                .map(|f| f.index())
                .collect()
        };
        assert!(
            !blend_faces.is_empty(),
            "first fillet must create a blend face"
        );

        let mut ef: HashMap<usize, HashSet<usize>> = HashMap::new();
        {
            let sh = topo
                .shell(topo.solid(first).unwrap().outer_shell())
                .unwrap();
            for &fid in sh.faces() {
                for oe in topo
                    .wire(topo.face(fid).unwrap().outer_wire())
                    .unwrap()
                    .edges()
                {
                    ef.entry(oe.edge().index()).or_default().insert(fid.index());
                }
            }
        }

        let r_edges = solid_edge_ids(&topo, first);
        let filletable: HashSet<usize> =
            brepkit_operations::query::filter_filletable_edges(&topo, first, &r_edges)
                .unwrap()
                .iter()
                .map(|e| e.index())
                .collect();
        let target = r_edges
            .iter()
            .copied()
            .find(|e| {
                filletable.contains(&e.index())
                    && ef
                        .get(&e.index())
                        .is_some_and(|fs| fs.iter().any(|f| blend_faces.contains(f)))
            })
            .expect("a filletable edge bordering the NURBS blend face");

        let result = try_fillet(&mut topo, first, &[target], 0.5).expect("second fillet");
        assert_ne!(
            result, first,
            "the NURBS-blend-adjacent edge should be filleted, not skipped"
        );
        let sh = topo
            .shell(topo.solid(result).unwrap().outer_shell())
            .unwrap();
        validate_shell_manifold(sh, &topo).expect("second fillet must be manifold");
        validate_shell_closed(sh, &topo)
            .expect("second fillet on a NURBS-blend-adjacent edge must be watertight");
    }
}