BREP_kernel 0.2.0

A boundary representation (BREP) geometry kernel for building CAD applications.
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Cut / split a body by a plane (Golovanov §6.4).
//!
//! The split reuses the ROBUST boolean rather than a bespoke classifier: the
//! plane is realised as two very large half-space TOOL boxes (one covering each
//! side of the plane), and each output piece is `Intersect(solid, tool)`. The
//! boolean machinery imprints the cut plane onto the solid and re-closes the
//! shell, so both pieces inherit the kernel's validated, watertight topology.

use crate::boolean::{boolean_operation, BooleanOperation, BooleanOptions};
use crate::spatial::Aabb;
use crate::topology::{make_box_brep, make_cylinder_brep, BrepSolid};
use crate::transform_topology::{transform_brep, AffineTransform};
use crate::{
    make_cone_brep, make_sphere_brep, make_torus_brep, AnalyticSurface, NurbsSurface, Vec3,
};
use serde::Deserialize;

/// Axis-aligned bounding box of a solid's vertices.
fn solid_aabb(solid: &BrepSolid) -> Aabb {
    let mut bounds = Aabb::empty();
    for vertex in &solid.vertices {
        bounds.include_point(vertex.point);
    }
    bounds
}

/// A boolean result counts as an empty piece when it carries no face geometry —
/// i.e. the half-space tool did not overlap the solid on that side.
fn is_empty_piece(solid: &BrepSolid) -> bool {
    solid.shells.is_empty() || solid.shells.iter().all(|shell| shell.faces.is_empty())
}

/// Build the affine placing a local, origin-centred cube so its local +Z axis
/// maps to `n`, +X to `u`, +Y to `v`, and its centre lands at `center`. The
/// columns of the rotation are `[u v n]` (a right-handed, det = +1 frame), so
/// the map is a proper rigid motion (no orientation reversal needed).
fn frame_transform(u: Vec3, v: Vec3, n: Vec3, center: Vec3) -> Result<AffineTransform, String> {
    AffineTransform::new([
        u.x, v.x, n.x, center.x, //
        u.y, v.y, n.y, center.y, //
        u.z, v.z, n.z, center.z, //
        0.0, 0.0, 0.0, 1.0,
    ])
}

/// Split `solid` into two pieces by the plane through `plane_point` with normal
/// `plane_normal`. Returns `(below, above)` where `below` is the piece on the
/// −n side of the plane and `above` the piece on the +n side.
///
/// Contract: when the plane does not actually divide the solid into two
/// non-degenerate pieces (it misses the body, or is tangent so one side is
/// empty), this returns `Err("split_solid_by_plane: plane does not intersect
/// the solid")` rather than a degenerate/empty piece.
pub fn split_solid_by_plane(
    solid: &BrepSolid,
    plane_point: Vec3,
    plane_normal: Vec3,
) -> Result<(BrepSolid, BrepSolid), String> {
    let n = plane_normal.normalized()?;
    // Orthonormal frame (n, u, v): u ⟂ n (unit), v = n × u (unit); [u v n] is
    // right-handed so the tool placement is a proper rotation.
    let u = n.perpendicular()?;
    let v = n.cross(u);

    let bounds = solid_aabb(solid);
    if !bounds.minimum.x.is_finite() {
        return Err("split_solid_by_plane: solid has no geometry".into());
    }
    let diagonal = bounds.diagonal();
    if diagonal <= 0.0 {
        return Err("split_solid_by_plane: solid is degenerate".into());
    }
    // A tool box 3× the solid diagonal on every side easily covers the body in
    // the plane's tangent directions.
    let length = 3.0 * diagonal;
    let half = 0.5 * length;

    // Centre the tool in the tangent (u, v) plane on the projection of the AABB
    // centre onto the cut plane, so the box brackets the whole solid regardless
    // of where `plane_point` sits within it. Along n it is offset by ±half so
    // the tool's cut face lands exactly on the plane.
    let center = bounds.minimum.add(bounds.maximum).scale(0.5);
    let center_on_plane = center.sub(n.scale(center.sub(plane_point).dot(n)));

    // Local cube centred at the local origin, spanning [-half, half]³.
    let cube = make_box_brep(Vec3::new(-half, -half, -half), length, length, length)?;

    // BELOW: tool centred at plane − n·half, so its +n face lies on the plane
    // and it extends distance `length` along −n, covering the −n side.
    let below_center = center_on_plane.sub(n.scale(half));
    let tool_below = transform_brep(&cube, frame_transform(u, v, n, below_center)?, false)?;

    // ABOVE: mirror to the +n side (centre at plane + n·half).
    let above_center = center_on_plane.add(n.scale(half));
    let tool_above = transform_brep(&cube, frame_transform(u, v, n, above_center)?, false)?;

    let options = BooleanOptions::default();
    let below = boolean_operation(solid, &tool_below, BooleanOperation::Intersect, &options);
    let above = boolean_operation(solid, &tool_above, BooleanOperation::Intersect, &options);

    match (below, above) {
        (Ok(below), Ok(above)) if !is_empty_piece(&below) && !is_empty_piece(&above) => {
            Ok((below, above))
        }
        _ => Err("split_solid_by_plane: plane does not intersect the solid".into()),
    }
}

// ---------------------------------------------------------------------------
// Generalized split by an analytic surface (Golovanov §6.4).
//
// The plane case above splits a body against two large half-space TOOL boxes.
// The analytic cases generalize that idea: an unbounded/bounded analytic
// surface (cylinder, cone, sphere, torus) is realised as ONE CLOSED SOLID
// region big enough to span the body wherever it matters, and the two output
// pieces are the boolean `Intersect` (inside the tool region) and `Subtract`
// (outside it) of the body against that region.  Because every cut runs
// through the validated boolean machinery, each piece inherits watertight
// topology, the cut surface is imprinted onto the body, and the two volumes
// sum to the original.
// ---------------------------------------------------------------------------

/// A closed analytic tool region used to cut a body.  Each variant is realised
/// as a closed solid (unbounded carriers are capped well beyond the body) whose
/// interior is one side of the analytic surface.
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum SplitSurface {
    /// Infinite plane through `point` with `normal`; delegates to the plane path.
    Plane { point: Vec3, normal: Vec3 },
    /// Infinite cylinder about the axis line through `axis_point` along
    /// `axis_dir`, of the given `radius`.  Interior = inside the cylinder.
    Cylinder {
        axis_point: Vec3,
        axis_dir: Vec3,
        radius: f64,
    },
    /// Sphere centred at `center`.  Interior = inside the ball.
    Sphere { center: Vec3, radius: f64 },
    /// Single-nappe cone with its apex at `apex`, opening along `+axis_dir`,
    /// with the given `half_angle` (radians, apex half-angle).  Interior =
    /// inside the cone.
    Cone {
        apex: Vec3,
        axis_dir: Vec3,
        half_angle: f64,
    },
    /// Torus centred at `center` about `axis_dir`.  Interior = inside the tube.
    Torus {
        center: Vec3,
        axis_dir: Vec3,
        major_radius: f64,
        minor_radius: f64,
    },
}

/// Bounds + a sane margin/diagonal for a body, erroring on empty/degenerate
/// geometry the same way the plane path does.
fn solid_extent(solid: &BrepSolid) -> Result<(Aabb, f64), String> {
    let bounds = solid_aabb(solid);
    if !bounds.minimum.x.is_finite() {
        return Err("split_solid_by_surface: solid has no geometry".into());
    }
    let diagonal = bounds.diagonal();
    if diagonal <= 0.0 {
        return Err("split_solid_by_surface: solid is degenerate".into());
    }
    Ok((bounds, diagonal))
}

/// Build the closed tool solid for an analytic tool, sized to fully span the
/// body wherever the analytic surface passes through it.
fn build_tool_solid(solid: &BrepSolid, tool: &SplitSurface) -> Result<BrepSolid, String> {
    let (_, diagonal) = solid_extent(solid)?;
    let margin = diagonal.max(1.0);
    match *tool {
        SplitSurface::Plane { .. } => {
            Err("build_tool_solid: plane is handled by the plane path".into())
        }
        SplitSurface::Cylinder {
            axis_point,
            axis_dir,
            radius,
        } => {
            if radius <= 0.0 {
                return Err("split_solid_by_surface: cylinder radius must be positive".into());
            }
            let axis = axis_dir.normalized()?;
            // Extend the capped cylinder a full margin beyond the body's span
            // along the axis so its caps never cut the body.
            let (t_min, t_max) = axis_span(solid, axis_point, axis);
            let base = axis_point.add(axis.scale(t_min - margin));
            let height = (t_max - t_min) + 2.0 * margin;
            make_cylinder_brep(base, axis, radius, height)
        }
        SplitSurface::Sphere { center, radius } => {
            if radius <= 0.0 {
                return Err("split_solid_by_surface: sphere radius must be positive".into());
            }
            // A sphere is already a closed, bounded region.
            make_sphere_brep(center, radius, Vec3::new(0.0, 0.0, 1.0))
        }
        SplitSurface::Cone {
            apex,
            axis_dir,
            half_angle,
        } => {
            if !(half_angle > 0.0 && half_angle < std::f64::consts::FRAC_PI_2) {
                return Err("split_solid_by_surface: cone half-angle must be in (0, pi/2)".into());
            }
            let axis = axis_dir.normalized()?;
            // Distance of the farthest body point along +axis from the apex.
            let (_, d_max) = axis_span(solid, apex, axis);
            if d_max <= 0.0 {
                return Err(
                    "split_solid_by_surface: cone does not reach the solid (body is behind the apex)"
                        .into(),
                );
            }
            let big_h = d_max + margin;
            // Realise the nappe as a cone whose apex sits at `apex` and whose
            // base cap lands `big_h` past it along +axis: base at apex+axis·H,
            // built with axis pointing back to the apex so top(0-radius)=apex.
            let base = apex.add(axis.scale(big_h));
            let base_radius = big_h * half_angle.tan();
            make_cone_brep(base, axis.scale(-1.0), base_radius, 0.0, big_h)
        }
        SplitSurface::Torus {
            center,
            axis_dir,
            major_radius,
            minor_radius,
        } => {
            if minor_radius <= 0.0 || major_radius <= 0.0 {
                return Err("split_solid_by_surface: torus radii must be positive".into());
            }
            // A torus is already a closed, bounded region.
            make_torus_brep(center, axis_dir, major_radius, minor_radius)
        }
    }
}

/// Signed span `[min, max]` of the body's vertices projected onto the axis line
/// through `origin` along the unit direction `axis`.
fn axis_span(solid: &BrepSolid, origin: Vec3, axis: Vec3) -> (f64, f64) {
    let mut t_min = f64::INFINITY;
    let mut t_max = f64::NEG_INFINITY;
    for vertex in &solid.vertices {
        let t = vertex.point.sub(origin).dot(axis);
        t_min = t_min.min(t);
        t_max = t_max.max(t);
    }
    (t_min, t_max)
}

/// Split `solid` into pieces by an analytic tool surface (Golovanov §6.4).
///
/// For the `Plane` tool this is exactly `split_solid_by_plane`, returned as
/// `[below, above]`.  For a closed analytic tool region (cylinder / sphere /
/// cone / torus) the two pieces are `[inside, outside]` where `inside =
/// solid ∩ tool` and `outside = solid − tool`.  Both pieces are guaranteed
/// non-empty and valid; their volumes sum to the original.
///
/// Contract: when the tool does not actually divide the body into two
/// non-degenerate pieces (it misses the body, or wholly contains / is wholly
/// contained so one side is empty), this returns a clear `Err` rather than a
/// degenerate/empty piece.
pub fn split_solid_by_surface(
    solid: &BrepSolid,
    tool: &SplitSurface,
) -> Result<Vec<BrepSolid>, String> {
    if let SplitSurface::Plane { point, normal } = *tool {
        let (below, above) = split_solid_by_plane(solid, point, normal)?;
        return Ok(vec![below, above]);
    }

    let tool_solid = build_tool_solid(solid, tool)?;
    let options = BooleanOptions::default();
    let inside = boolean_operation(solid, &tool_solid, BooleanOperation::Intersect, &options);
    let outside = boolean_operation(solid, &tool_solid, BooleanOperation::Subtract, &options);

    match (inside, outside) {
        (Ok(inside), Ok(outside))
            if !is_empty_piece(&inside)
                && !is_empty_piece(&outside)
                && inside.validate().is_empty()
                && outside.validate().is_empty() =>
        {
            Ok(vec![inside, outside])
        }
        _ => Err("split_solid_by_surface: tool surface does not divide the solid".into()),
    }
}

/// Map a face's exact analytic carrier to the closed tool region that splits a
/// body by that surface.  Reuses the kernel's own analytic recognition so the
/// caller only has to hand over the selected face's surface (no host-side
/// geometry extraction).  Unrecognized / general-revolution carriers are
/// reported as unsupported (deferred), never approximated.
fn recognized_split_surface(surface: &NurbsSurface) -> Result<SplitSurface, String> {
    let analytic = surface
        .analytic()
        .ok_or("split_solid_by_face_surface: selected face is not an analytic surface")?;
    match analytic {
        AnalyticSurface::Plane {
            origin,
            u_dir,
            v_dir,
            ..
        } => {
            let normal = u_dir.cross(*v_dir).normalized()?;
            Ok(SplitSurface::Plane {
                point: *origin,
                normal,
            })
        }
        AnalyticSurface::RuledRevolution {
            frame,
            rho0,
            rho1,
            height,
        } => {
            // Cylinder when the two radii coincide, otherwise a cone/frustum.
            let scale = rho0.abs().max(rho1.abs()).max(1.0);
            if (rho0 - rho1).abs() <= 1e-9 * scale {
                Ok(SplitSurface::Cylinder {
                    axis_point: frame.origin,
                    axis_dir: frame.axis,
                    radius: 0.5 * (rho0 + rho1),
                })
            } else {
                // radius(axial) = rho0 + slope·axial, apex where radius = 0.
                let slope = (rho1 - rho0) / height;
                let axial_apex = -rho0 / slope;
                let apex = frame.origin.add(frame.axis.scale(axial_apex));
                // The nappe opens in the direction of increasing radius.
                let axis_dir = if slope >= 0.0 {
                    frame.axis
                } else {
                    frame.axis.scale(-1.0)
                };
                Ok(SplitSurface::Cone {
                    apex,
                    axis_dir,
                    half_angle: slope.abs().atan(),
                })
            }
        }
        AnalyticSurface::Sphere { frame, radius } => Ok(SplitSurface::Sphere {
            center: frame.origin,
            radius: *radius,
        }),
        AnalyticSurface::Torus {
            frame,
            major_radius,
            minor_radius,
        } => Ok(SplitSurface::Torus {
            center: frame.origin,
            axis_dir: frame.axis,
            major_radius: *major_radius,
            minor_radius: *minor_radius,
        }),
        AnalyticSurface::Revolution { .. } => Err(
            "split_solid_by_face_surface: general revolved surfaces are not supported as a cut tool"
                .into(),
        ),
    }
}

/// Split `solid` by the analytic carrier of a selected face `surface`
/// (Golovanov §6.4).  The face may be a plane, cylinder, cone, or sphere; the
/// carrier is extended to fully span the body.  Returns the two pieces
/// (`[below, above]` for a plane, `[inside, outside]` otherwise).  Errors on
/// non-analytic / general-revolution faces, or when the carrier does not
/// cleanly divide the body.
pub fn split_solid_by_face_surface(
    solid: &BrepSolid,
    surface: &NurbsSurface,
) -> Result<Vec<BrepSolid>, String> {
    let tool = recognized_split_surface(surface)?;
    split_solid_by_surface(solid, &tool)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        boolean_semantic_disagreement, make_box_brep, solid_mass_properties, BooleanOperation,
    };

    fn aabb(solid: &BrepSolid) -> (Vec3, Vec3) {
        let bounds = solid_aabb(solid);
        (bounds.minimum, bounds.maximum)
    }

    fn face_count(solid: &BrepSolid) -> usize {
        solid.shells.iter().map(|shell| shell.faces.len()).sum()
    }

    fn volume(solid: &BrepSolid) -> f64 {
        solid_mass_properties(solid).unwrap().volume
    }

    /// The `inside` piece must agree with `solid ∩ tool` and the `outside` piece
    /// with `solid − tool` at essentially every decidable sample point.
    fn assert_oracle_clean(
        solid: &BrepSolid,
        tool_solid: &BrepSolid,
        inside: &BrepSolid,
        outside: &BrepSolid,
    ) {
        let in_report = boolean_semantic_disagreement(
            solid,
            tool_solid,
            BooleanOperation::Intersect,
            inside,
            4000,
        )
        .unwrap();
        eprintln!(
            "  inside oracle: considered={} disagreements={} rate={:.6}",
            in_report.considered,
            in_report.disagreements.len(),
            in_report.disagreement_rate
        );
        // The kernel's own boolean correctness gate is `!is_flagged()`
        // (disagreement_rate <= DISAGREEMENT_THRESHOLD = 0.03).  The rare
        // residual disagreements here are grazing/near-boundary ray-cast noise,
        // not wrong topology; hold the pieces to well under 1% (~0).
        assert!(
            !in_report.is_flagged() && in_report.disagreement_rate < 0.01,
            "inside piece disagrees with solid∩tool (rate {}): {:?}",
            in_report.disagreement_rate,
            in_report.sample_disagreement()
        );
        let out_report = boolean_semantic_disagreement(
            solid,
            tool_solid,
            BooleanOperation::Subtract,
            outside,
            4000,
        )
        .unwrap();
        eprintln!(
            "  outside oracle: considered={} disagreements={} rate={:.6}",
            out_report.considered,
            out_report.disagreements.len(),
            out_report.disagreement_rate
        );
        assert!(
            !out_report.is_flagged() && out_report.disagreement_rate < 0.01,
            "outside piece disagrees with solid−tool (rate {}): {:?}",
            out_report.disagreement_rate,
            out_report.sample_disagreement()
        );
    }

    #[test]
    fn split_box_by_midplane_halves_it() {
        // Box(10³) centred at the origin.
        let box_solid = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();

        let (below, above) =
            split_solid_by_plane(&box_solid, Vec3::default(), Vec3::new(1.0, 0.0, 0.0)).unwrap();

        // (1) Both pieces are valid, watertight solids.
        assert!(
            below.validate().is_empty(),
            "below invalid: {:?}",
            below.validate()
        );
        assert!(
            above.validate().is_empty(),
            "above invalid: {:?}",
            above.validate()
        );

        // (2) Each half is still a six-faced box (5 trimmed originals + 1 cut).
        assert_eq!(face_count(&below), 6);
        assert_eq!(face_count(&above), 6);

        // (3) Volumes: each ≈ 500, summing to ≈ 1000 (allow small boolean noise).
        let vol_below = solid_mass_properties(&below).unwrap().volume;
        let vol_above = solid_mass_properties(&above).unwrap().volume;
        assert!((vol_below - 500.0).abs() < 1e-3, "below volume {vol_below}");
        assert!((vol_above - 500.0).abs() < 1e-3, "above volume {vol_above}");
        assert!((vol_below + vol_above - 1000.0).abs() < 1e-3);

        // (4) The cut is flat on x = 0: the below piece fills x ∈ [-5, 0] and the
        //     above piece x ∈ [0, 5], so each gains a planar cut face on x = 0.
        let (below_min, below_max) = aabb(&below);
        assert!(
            (below_min.x - (-5.0)).abs() < 1e-6,
            "below min.x {}",
            below_min.x
        );
        assert!(below_max.x.abs() < 1e-6, "below max.x {}", below_max.x);
        let (above_min, above_max) = aabb(&above);
        assert!(above_min.x.abs() < 1e-6, "above min.x {}", above_min.x);
        assert!(
            (above_max.x - 5.0).abs() < 1e-6,
            "above max.x {}",
            above_max.x
        );

        // Explicit cut-face check: each piece has a face all of whose vertices lie
        // on x = 0. Coedges reference edges by id; each edge names its endpoints.
        let has_cut_face = |solid: &BrepSolid| -> bool {
            solid
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .any(|face| {
                    let mut points: Vec<Vec3> = Vec::new();
                    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
                        let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else {
                            return false;
                        };
                        for vid in [edge.start_vertex_id, edge.end_vertex_id] {
                            if let Some(vx) = solid.vertices.iter().find(|vx| vx.id == vid) {
                                points.push(vx.point);
                            }
                        }
                    }
                    !points.is_empty() && points.iter().all(|p| p.x.abs() < 1e-6)
                })
        };
        assert!(has_cut_face(&below), "below missing cut face on x=0");
        assert!(has_cut_face(&above), "above missing cut face on x=0");
    }

    /// The generalized entry with a Plane tool must reproduce the plane path
    /// exactly (a new plane case still splits).
    #[test]
    fn generalized_plane_tool_still_splits() {
        let box_solid = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        // Cut on y = 2 with a +y normal.
        let pieces = split_solid_by_surface(
            &box_solid,
            &SplitSurface::Plane {
                point: Vec3::new(0.0, 2.0, 0.0),
                normal: Vec3::new(0.0, 1.0, 0.0),
            },
        )
        .unwrap();
        assert_eq!(pieces.len(), 2);
        for piece in &pieces {
            assert!(piece.validate().is_empty(), "plane piece invalid");
        }
        let (below, above) = (&pieces[0], &pieces[1]);
        // below = y ∈ [-5, 2] (vol 700), above = y ∈ [2, 5] (vol 300).
        assert!(
            (volume(below) - 700.0).abs() < 1e-3,
            "below {}",
            volume(below)
        );
        assert!(
            (volume(above) - 300.0).abs() < 1e-3,
            "above {}",
            volume(above)
        );
        assert!((volume(below) + volume(above) - 1000.0).abs() < 1e-3);
    }

    #[test]
    fn split_cube_by_cylinder_two_valid_solids() {
        // Cube [-5,5]³, volume 1000.  A cylinder of radius 3 about the Z axis
        // passes fully through it (through the interior, capped beyond the box).
        let cube = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        let tool = SplitSurface::Cylinder {
            axis_point: Vec3::default(),
            axis_dir: Vec3::new(0.0, 0.0, 1.0),
            radius: 3.0,
        };
        let pieces = split_solid_by_surface(&cube, &tool).unwrap();
        assert_eq!(pieces.len(), 2, "cylinder split should yield 2 pieces");
        let (inside, outside) = (&pieces[0], &pieces[1]);

        // (1) Both pieces valid, watertight.
        assert!(
            inside.validate().is_empty(),
            "inside invalid: {:?}",
            inside.validate()
        );
        assert!(
            outside.validate().is_empty(),
            "outside invalid: {:?}",
            outside.validate()
        );

        // (2) Volumes sum to the cube.  inside = the r=3 cylinder core of
        //     height 10 = π·9·10 ≈ 282.743; outside = the rest.
        let vol_in = volume(inside);
        let vol_out = volume(outside);
        let expected_core = std::f64::consts::PI * 9.0 * 10.0;
        assert!(
            (vol_in - expected_core).abs() < 1e-3,
            "core volume {vol_in}"
        );
        assert!(
            (vol_in + vol_out - 1000.0).abs() < 1e-6,
            "sum {}",
            vol_in + vol_out
        );

        // (3) Semantic oracle: inside == cube∩cyl, outside == cube−cyl.
        let tool_solid = build_tool_solid(&cube, &tool).unwrap();
        assert_oracle_clean(&cube, &tool_solid, inside, outside);
    }

    #[test]
    fn split_box_by_sphere_two_valid_solids() {
        // Box [-5,5]³, volume 1000.  A sphere of radius 4 centred at the origin
        // lies entirely inside → inside = the ball, outside = box with cavity.
        let box_solid = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        let tool = SplitSurface::Sphere {
            center: Vec3::default(),
            radius: 4.0,
        };
        let pieces = split_solid_by_surface(&box_solid, &tool).unwrap();
        assert_eq!(pieces.len(), 2, "sphere split should yield 2 pieces");
        let (inside, outside) = (&pieces[0], &pieces[1]);

        assert!(
            inside.validate().is_empty(),
            "inside invalid: {:?}",
            inside.validate()
        );
        assert!(
            outside.validate().is_empty(),
            "outside invalid: {:?}",
            outside.validate()
        );

        let vol_in = volume(inside);
        let vol_out = volume(outside);
        let expected_ball = 4.0 / 3.0 * std::f64::consts::PI * 4.0_f64.powi(3);
        assert!(
            (vol_in - expected_ball).abs() < 1e-2,
            "ball volume {vol_in}"
        );
        assert!(
            (vol_in + vol_out - 1000.0).abs() < 1e-6,
            "sum {}",
            vol_in + vol_out
        );

        let tool_solid = build_tool_solid(&box_solid, &tool).unwrap();
        assert_oracle_clean(&box_solid, &tool_solid, inside, outside);
    }

    #[test]
    fn split_box_by_cone_two_valid_solids() {
        // Box [-5,5]³.  A cone apexed at (0,0,-6), opening +Z at 20°, cuts the
        // box interior: it enters through the bottom face as a tiny circle and
        // exits through the top face as an r≈4 circle, both within the box
        // cross-section — so it cleanly divides the body (like the cylinder).
        let box_solid = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        let tool = SplitSurface::Cone {
            apex: Vec3::new(0.0, 0.0, -6.0),
            axis_dir: Vec3::new(0.0, 0.0, 1.0),
            half_angle: std::f64::consts::PI / 9.0, // 20°
        };
        let pieces = split_solid_by_surface(&box_solid, &tool).unwrap();
        assert_eq!(pieces.len(), 2, "cone split should yield 2 pieces");
        let (inside, outside) = (&pieces[0], &pieces[1]);

        assert!(
            inside.validate().is_empty(),
            "inside invalid: {:?}",
            inside.validate()
        );
        assert!(
            outside.validate().is_empty(),
            "outside invalid: {:?}",
            outside.validate()
        );

        let vol_in = volume(inside);
        let vol_out = volume(outside);
        assert!(vol_in > 0.0 && vol_out > 0.0, "both pieces non-empty");
        assert!(
            (vol_in + vol_out - 1000.0).abs() < 1e-6,
            "sum {}",
            vol_in + vol_out
        );

        let tool_solid = build_tool_solid(&box_solid, &tool).unwrap();
        assert_oracle_clean(&box_solid, &tool_solid, inside, outside);
    }

    #[test]
    fn split_by_selected_cylinder_face_recognizes_and_cuts() {
        // Take the side face of a real cylinder solid and use ITS surface as
        // the cut tool for a cube — exercises the analytic-recognition entry
        // the app uses when the user selects a cylindrical face.
        let cube = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        let cyl = make_cylinder_brep(
            Vec3::new(0.0, 0.0, -8.0),
            Vec3::new(0.0, 0.0, 1.0),
            3.0,
            16.0,
        )
        .unwrap();
        // Face id 105 is the cylindrical side (see make_cylinder_brep).
        let side = cyl
            .shells
            .iter()
            .flat_map(|s| &s.faces)
            .find(|f| f.id == 105)
            .expect("cylinder side face");
        assert!(
            matches!(
                recognized_split_surface(&side.surface).unwrap(),
                SplitSurface::Cylinder { radius, .. } if (radius - 3.0).abs() < 1e-9
            ),
            "side face should recognize as an r=3 cylinder"
        );
        let pieces = split_solid_by_face_surface(&cube, &side.surface).unwrap();
        assert_eq!(pieces.len(), 2);
        for piece in &pieces {
            assert!(piece.validate().is_empty(), "face-split piece invalid");
        }
        let sum = volume(&pieces[0]) + volume(&pieces[1]);
        assert!((sum - 1000.0).abs() < 1e-6, "volumes sum {sum}");
        assert!(
            (volume(&pieces[0]) - std::f64::consts::PI * 9.0 * 10.0).abs() < 1e-3,
            "core volume {}",
            volume(&pieces[0])
        );
    }

    #[test]
    fn split_misses_body_errs() {
        // A cylinder whose axis and radius keep it clear of the cube entirely →
        // no split, clean Err (not a bad/empty solid).
        let cube = make_box_brep(Vec3::new(-5.0, -5.0, -5.0), 10.0, 10.0, 10.0).unwrap();
        let tool = SplitSurface::Cylinder {
            axis_point: Vec3::new(100.0, 0.0, 0.0),
            axis_dir: Vec3::new(0.0, 0.0, 1.0),
            radius: 1.0,
        };
        assert!(split_solid_by_surface(&cube, &tool).is_err());
    }
}