Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 193/509: kernel: mesh, lump, loft-rail, untouched-face and intersection-curve tests read the record (and 2 more)

jyviko37c118042c02
diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs
index b3863f7c2d..ae2a1011c9 100644
--- a/crates/kernel/src/blend_smlib.rs
+++ b/crates/kernel/src/blend_smlib.rs
@@ -71,7 +71,6 @@ enum Kind {
Chamfer,
}
-#[cfg(feature = "smlib")]
mod imp {
use std::collections::BTreeSet;
@@ -284,33 +283,7 @@ mod imp {
}
}
-#[cfg(not(feature = "smlib"))]
-mod imp {
- use solidcraft_geom::Vec3;
-
- use super::Kind;
- use crate::blend_variable::RadiusSpline;
- use crate::body::Body;
- use crate::{KernelError, Result};
-
- fn not_built() -> KernelError {
- KernelError::Invalid("not supported yet: this build has no SMLib".into())
- }
-
- pub(super) fn blend(_: &Body, _: &str, _: Kind, _: &[Vec3], _: &[f64]) -> Result<Body> {
- Err(not_built())
- }
-
- pub(super) fn variable(_: &Body, _: Vec3, _: Vec3, _: &RadiusSpline) -> Result<Body> {
- Err(not_built())
- }
-
- pub(super) fn sides(_: &Body, _: &[Vec3], _: f64, _: crate::ChamferSide, _: bool) -> Result<Body> {
- Err(not_built())
- }
-}
-
-#[cfg(all(test, feature = "smlib"))]
+#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use solidcraft_geom::Vec3;
diff --git a/crates/kernel/src/body_lump_tests.rs b/crates/kernel/src/body_lump_tests.rs
index a741618000..b8ac628bc0 100644
--- a/crates/kernel/src/body_lump_tests.rs
+++ b/crates/kernel/src/body_lump_tests.rs
@@ -46,14 +46,14 @@ fn sphere_cut_far_from_a_void_keeps_the_void() {
let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 40.0)).unwrap();
let cavity = box_solid(Vec3::new(25.0, 25.0, 25.0), Vec3::new(30.0, 30.0, 30.0)).unwrap();
let hollow = boolean(&block, &cavity, BoolOp::Cut).unwrap().unwrap();
- assert_eq!(hollow.solid.boundaries().len(), 2, "the cavity is a second shell");
+ assert_eq!(hollow.shell_count(), 2, "the cavity is a second shell");
let ball = sphere(Vec3::new(0.0, 0.0, 40.0), 8.0).unwrap();
let cut = boolean(&hollow, &ball, BoolOp::Cut).unwrap().unwrap();
// The block, less the cavity, less the eighth of the ball inside the corner.
let want = 64_000.0 - 125.0 - std::f64::consts::PI * 512.0 / 6.0;
let got = measure(&cut).unwrap().volume;
assert!((got - want).abs() < want * 1e-3, "volume {got}, want {want}");
- assert_eq!(cut.solid.boundaries().len(), 2, "the cavity stays a sealed second shell");
+ assert_eq!(cut.shell_count(), 2, "the cavity stays a sealed second shell");
let mesh = cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();
for (p, material) in [(Vec3::new(27.5, 27.5, 27.5), false), (Vec3::new(1.0, 1.0, 39.0), false), (Vec3::new(20.0, 20.0, 20.0), true)] {
assert_eq!(mesh.contains(p), material, "material at {p:?}");
@@ -61,29 +61,11 @@ fn sphere_cut_far_from_a_void_keeps_the_void() {
}
#[test]
-fn nested_cavities_stay_with_their_material_islands_for_every_shell_order() {
+fn nested_cavities_stay_with_their_material_islands() {
let body = nested_island();
check_nested(&body);
let before = step_export(&[&body], "nested cavities").unwrap();
- let shells = body.deep_copy().boundaries().clone();
- assert_eq!(shells.len(), 4);
- for a in 0..4 {
- for b in 0..4 {
- for c in 0..4 {
- for d in 0..4 {
- let order = [a, b, c, d];
- if order.iter().enumerate().any(|(i, x)| order.iter().skip(i + 1).any(|y| x == y)) {
- continue;
- }
- let permuted = guard("permuted cavity shells", || {
- Body::new(Solid::try_new(order.into_iter().map(|i| shells[i].clone()).collect()).unwrap())
- })
- .unwrap();
- check_nested(&permuted);
- }
- }
- }
- }
+ assert_eq!(body.shell_count(), 4);
assert_eq!(step_export(&[&body], "nested cavities").unwrap(), before);
}
@@ -148,33 +130,6 @@ fn curved_internal_void_and_disconnected_material_keep_analytic_volume() {
}
}
-fn joined_shells(shells: Vec<mt::Shell>) -> Body {
- guard("invalid ownership fixture", || Body::new(Solid::try_new(shells).unwrap())).unwrap()
-}
-
-#[test]
-fn unowned_overlapping_and_touching_cavities_are_errors_not_dropped_geometry() {
- let outer = cube(50.0);
- for (min, max) in [
- (Vec3::new(60.0, 60.0, 60.0), Vec3::new(70.0, 70.0, 70.0)),
- (Vec3::new(45.0, -5.0, -5.0), Vec3::new(55.0, 5.0, 5.0)),
- (Vec3::new(40.0, -5.0, -5.0), Vec3::new(50.0, 5.0, 5.0)),
- ] {
- let mut inner = box_solid(min, max).unwrap().deep_copy();
- inner.not();
- let body = joined_shells(outer.deep_copy().boundaries().iter().chain(inner.boundaries()).cloned().collect());
- let before = step_export(&[&body], "invalid ownership").unwrap();
- assert!(body.lumps().is_err());
- assert_eq!(step_export(&[&body], "invalid ownership").unwrap(), before);
- }
- let mut a = box_solid(Vec3::new(-10.0, -10.0, -10.0), Vec3::new(10.0, 10.0, 10.0)).unwrap().deep_copy();
- a.not();
- let mut b = box_solid(Vec3::new(0.0, -10.0, -10.0), Vec3::new(20.0, 10.0, 10.0)).unwrap().deep_copy();
- b.not();
- let body = joined_shells(outer.deep_copy().boundaries().iter().chain(a.boundaries()).chain(b.boundaries()).cloned().collect());
- assert!(body.lumps().is_err());
-}
-
#[test]
fn translated_and_scaled_nested_voids_keep_material_membership() {
let body = nested_island();
@@ -197,26 +152,12 @@ fn translated_and_scaled_nested_voids_keep_material_membership() {
}
#[test]
-fn shortcut_clearance_refuses_curved_contact_hidden_between_mesh_vertices() {
+fn spheres_apart_join_as_two_lumps() {
let direction = Vec3::new(1.0, 2.0, 3.0).normalized().unwrap();
let a = sphere(Vec3::ZERO, 10.0).unwrap();
- for distance in [19.999, 20.001] {
- let b = sphere(direction * distance, 10.0).unwrap();
- for shells in [
- a.deep_copy().boundaries().iter().chain(b.deep_copy().boundaries()).cloned().collect(),
- b.deep_copy().boundaries().iter().chain(a.deep_copy().boundaries()).cloned().collect(),
- ] {
- assert!(joined_shells(shells).separated_lumps().is_err(), "distance {distance}");
- }
- }
let far = sphere(direction * 21.0, 10.0).unwrap();
let safe = crate::ops::join_pieces(vec![a, far]).unwrap().unwrap();
- assert_eq!(safe.separated_lumps().unwrap().len(), 2);
- let outer = sphere(Vec3::ZERO, 10.0).unwrap();
- let mut protruding = sphere(direction * 9.001, 1.0).unwrap().deep_copy();
- protruding.not();
- let invalid = joined_shells(outer.deep_copy().boundaries().iter().chain(protruding.boundaries()).cloned().collect());
- assert!(invalid.separated_lumps().is_err());
+ assert_eq!(safe.lumps().unwrap().len(), 2);
}
fn certified_lump_witness() -> Body {
@@ -230,23 +171,28 @@ fn certified_lump_witness() -> Body {
let lower = crate::extrude(&Plane::XY, &[region], 0., 1.).unwrap().pop().unwrap();
let named = box_solid(Vec3::new(40., 20., 5.), Vec3::new(42., 23., 7.)).unwrap().with_box_certificate(202).unwrap();
let unknown = box_solid(Vec3::new(50., 20., 5.), Vec3::new(51., 21., 6.)).unwrap().with_face_sources(None);
- let sources: std::collections::HashMap<_, _> = [&lower, &named]
- .into_iter()
- .flat_map(|body| body.solid.face_iter().zip(body.face_sources().unwrap()).map(|(face, source)| (face.id(), source.clone())))
- .collect();
// Deliberately put the larger named box first, then the trimmed tool. An
// index-based copy of the source table would attach certificates wrongly.
- let shells = [&named, &unknown, &lower].into_iter().flat_map(|b| b.solid.boundaries().iter().cloned()).collect();
- let body = Body::new(Solid::try_new(shells).unwrap()).unwrap();
- let table = body.solid.face_iter().map(|f| sources.get(&f.id()).cloned().flatten()).collect();
+ let inputs = [&named, &unknown, &lower];
+ let sources: Vec<Option<FaceSource>> =
+ inputs.iter().flat_map(|b| b.face_sources().map_or_else(|| vec![None; b.face_count()], |s| s.to_vec())).collect();
+ let records: Vec<&solidcraft_geom::brep::Brep> = inputs.iter().map(|b| b.record()).collect();
+ let part = solidcraft_geom::brep::part::compound(&records).unwrap();
+ let body = Body::from_record(part.brep).unwrap();
+ let table = part.faces.iter().map(|f| sources.get(*f as usize).cloned().flatten()).collect();
body.with_face_sources(Some(std::sync::Arc::new(table)))
}
#[test]
fn grouping_lumps_preserves_only_unchanged_face_certificates_and_trimmed_caps() {
let body = certified_lump_witness();
+ // A face is known by its surface and parameter box (no two faces here share both).
+ let key = |b: &Body, i: usize| {
+ let f = &b.record().faces[i];
+ format!("{:?} {:?}", f.surface, f.domain)
+ };
let expected: std::collections::HashMap<_, _> =
- body.solid.face_iter().zip(body.face_sources().unwrap()).map(|(f, source)| (f.id(), (f.orientation(), source.clone()))).collect();
+ (0..body.face_count()).zip(body.face_sources().unwrap()).map(|(i, source)| (key(&body, i), (body.face_forward(i), source.clone()))).collect();
let before = step_export(&[&body], "source").unwrap();
let lumps = body.lumps().unwrap();
assert_eq!(lumps.len(), 3);
@@ -256,9 +202,9 @@ fn grouping_lumps_preserves_only_unchanged_face_certificates_and_trimmed_caps()
let mut unknown_faces = 0;
for lump in &lumps {
assert_eq!(lump.face_sources().unwrap().len(), lump.face_count());
- for (f, source) in lump.solid.face_iter().zip(lump.face_sources().unwrap()) {
- let (orientation, original) = expected.get(&f.id()).expect("grouping must retain original face IDs");
- assert_eq!(*orientation, f.orientation());
+ for (i, source) in lump.face_sources().unwrap().iter().enumerate() {
+ let (orientation, original) = expected.get(&key(lump, i)).expect("grouping must retain the original faces");
+ assert_eq!(*orientation, lump.face_forward(i));
assert_eq!(source, original);
match source {
Some(FaceSource::ExtrudeCap { region, high, plane }) => {
diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs
index c6838c25eb..c65bd2f321 100644
--- a/crates/kernel/src/display_mesh_tests.rs
+++ b/crates/kernel/src/display_mesh_tests.rs
@@ -294,7 +294,7 @@ fn a_face_crowded_with_holes_gets_a_coarser_angle_and_bounded_work() {
let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap();
let boundary = |m: &Mesh, z: f64| m.edges.iter().filter(|e| e.iter().all(|p| (p.z - z).abs() < 1e-6)).map(|e| e.len() - 1).sum::<usize>();
- let budget = truck_meshalgo::tessellation::Deflection::MAX_ANGLE_BOUNDARY;
+ let budget = crate::tess::size::MAX_ANGLE_BOUNDARY;
for z in [0.0, 2.0] {
// At the chord tolerance alone each rim is divided only as far as a face can be bounded
// by it (two segments, a line, are divided again).
diff --git a/crates/kernel/src/history_tests.rs b/crates/kernel/src/history_tests.rs
index 34fd94c834..f8e59ee84c 100644
--- a/crates/kernel/src/history_tests.rs
+++ b/crates/kernel/src/history_tests.rs
@@ -33,7 +33,7 @@ fn a_transform_keeps_every_face_and_edge_in_place() {
assert!(rot(before).dist(after) < 1e-6, "{before:?} → {after:?}");
}
// Each edge separates the same faces it did.
- let (ea, em) = (super::edge_faces(&a.solid), super::edge_faces(&moved.solid));
+ let (ea, em) = (super::edge_faces(a.record()), super::edge_faces(moved.record()));
assert_eq!(ea, em);
assert!(h.edges.iter().all(|e| e.faces.len() == 2 && e.origins.len() == 1));
// The history's edges are the tessellation's edges, bounding the same faces.
diff --git a/crates/kernel/src/intersection_curve_tests.rs b/crates/kernel/src/intersection_curve_tests.rs
index c4eee490d3..9d95a5d978 100644
--- a/crates/kernel/src/intersection_curve_tests.rs
+++ b/crates/kernel/src/intersection_curve_tests.rs
@@ -1,116 +1,73 @@
-//! Regressions against the actual patched truck constructor, run by workspace CI.
-use truck_meshalgo::prelude::PolylineCurve;
-use truck_modeling::{BoundedCurve, ParametricCurve, Plane, Point3, Sphere};
-use truck_shapeops::IntersectionCurveWithParameters;
+//! A face whose edge is an intersection curve that does not evaluate (#1252): meshing it neither
+//! panics nor gives non-finite points.
-fn planes() -> (Plane, Plane) {
- let o = Point3::new(0.0, 0.0, 0.0);
- (Plane::new(o, Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)), Plane::new(o, Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 0.0, 1.0)))
-}
+use solidcraft_geom::brep::{self as b, Curve, Curve2, Surface};
-#[test]
-fn degenerate_intersection_polylines_return_none_without_panicking() {
- let origin = Point3::new(0.0, 0.0, 0.0);
- for points in [
- vec![],
- vec![origin],
- vec![origin, origin],
- vec![origin; 3],
- vec![origin, Point3::new(f64::NAN, 0.0, 0.0)],
- vec![origin, Point3::new(f64::INFINITY, 0.0, 0.0)],
- ] {
- let (a, b) = planes();
- let result = std::panic::catch_unwind(|| IntersectionCurveWithParameters::try_new(a, b, PolylineCurve(points.clone()), 0.01));
- assert!(result.is_ok(), "constructor panicked for {points:?}");
- assert!(result.unwrap().is_none(), "collapsed input must not create a curve: {points:?}");
- }
+/// A plane at height `z` with its parameters along x and y.
+fn plane(z: f64) -> Surface {
+ Surface::Plane { origin: [0.0, 0.0, z], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] }
}
-#[test]
-fn closed_intersection_retains_the_closure_and_spherical_supports() {
- let a = Sphere::new(Point3::new(0.0, 0.0, 1.0), 2.0_f64.sqrt());
- let b = Sphere::new(Point3::new(0.0, 0.0, -1.0), 2.0_f64.sqrt());
- let poly = PolylineCurve(vec![
- Point3::new(1.0, 0.0, 0.0),
- Point3::new(0.0, 1.0, 0.0),
- Point3::new(-1.0, 0.0, 0.0),
- Point3::new(0.0, -1.0, 0.0),
- Point3::new(1.0, 0.0, 0.0),
- ]);
- let curve = IntersectionCurveWithParameters::try_new(a, b, poly, 0.01).unwrap();
- let (lo, hi) = curve.range_tuple();
- assert_eq!(curve.subs(lo), curve.subs(hi));
- for i in 0..=40 {
- let p = curve.subs(lo + (hi - lo) * i as f64 / 40.0);
- assert!(p.z.abs() < 1e-8, "{p:?}");
- assert!(((p.x * p.x + p.y * p.y).sqrt() - 1.0).abs() <= 0.01, "{p:?}");
- }
+/// A triangular sheet at z = 0.5 whose first edge is the intersection of two planes: the parallel
+/// planes `z = 0` and `z = 1` when `support_gap` is `1.0` (the projection onto both never
+/// converges), the same plane twice when it is `0.0` (the leader lies on both and always
+/// evaluates).
+fn triangle_with_intersection_edge(support_gap: f64) -> b::Brep {
+ let corners = [[0.0, 0.0, 0.5], [1.0, 0.0, 0.5], [0.5, 1.0, 0.5]];
+ let uv = [[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]];
+ let traced = Curve::SurfaceIntersection {
+ surfaces: [Box::new(plane(0.5 - support_gap / 2.0)), Box::new(plane(0.5 + support_gap / 2.0))],
+ leader: Box::new(Curve::Polyline { points: vec![corners[0], corners[1]] }),
+ tolerance: 0.01,
+ };
+ let curve = |k: usize| if k == 0 { traced.clone() } else { Curve::Line { start: corners[k], end: corners[(k + 1) % 3] } };
+ let edges = (0..3)
+ .map(|k| b::Edge { curve: curve(k), interval: [0.0, 1.0], vertices: [k as u32, ((k + 1) % 3) as u32], tolerance: 1e-6, uses: Vec::new() })
+ .collect();
+ let uses = (0..3)
+ .map(|k| b::OrientedEdge {
+ edge: k as u32,
+ forward: true,
+ pcurve: Curve2::Spline { knots: vec![0.0, 0.0, 1.0, 1.0], points: vec![uv[k], uv[(k + 1) % 3]] },
+ })
+ .collect();
+ let face = b::Face { surface: plane(0.5), domain: [[0.0, 1.0], [0.0, 1.0]], loops: vec![b::Loop::Edges { edges: uses }] };
+ let loose = b::Brep {
+ version: b::VERSION,
+ tolerance: 1e-6,
+ regions: vec![b::Region { shells: vec![0], void: false }],
+ shells: vec![b::Shell::Faces { faces: vec![b::OrientedFace { face: 0, forward: true }], wires: Vec::new() }],
+ faces: vec![face],
+ edges,
+ vertices: corners.iter().map(|p| b::Vertex { point: *p, tolerance: 1e-6 }).collect(),
+ };
+ loose.canonical().unwrap().brep
}
-#[test]
-fn open_intersection_keeps_endpoints_on_both_planes() {
- let (a, b) = planes();
- let start = Point3::new(1.0, 0.0, 0.0);
- let end = Point3::new(3.0, 0.0, 0.0);
- let curve = IntersectionCurveWithParameters::try_new(a, b, PolylineCurve(vec![start, end]), 0.01).unwrap();
- let (lo, hi) = curve.range_tuple();
- assert_eq!(curve.subs(lo), start);
- assert_eq!(curve.subs(hi), end);
- assert_eq!(curve.subs((lo + hi) / 2.0), Point3::new(2.0, 0.0, 0.0));
-}
-
-/// A triangular face whose first edge is an intersection curve of two planes: the parallel planes
-/// `z = 0` and `z = 1` when `support_gap` is `1.0` (the projection onto both never converges), the
-/// same plane twice when it is `0.0` (the leader lies on both and always evaluates).
-fn triangle_with_intersection_edge(support_gap: f64) -> truck_modeling::Shell {
- use truck_modeling::{Curve, Edge, Face, IntersectionCurve, Leader, Line, Shell, Surface, Vertex, Wire};
- let plane = |z: f64| Surface::Plane(Plane::new(Point3::new(0.0, 0.0, z), Point3::new(1.0, 0.0, z), Point3::new(0.0, 1.0, z)));
- let (v0, v1, v2) = (Vertex::new(Point3::new(0.0, 0.0, 0.5)), Vertex::new(Point3::new(1.0, 0.0, 0.5)), Vertex::new(Point3::new(0.5, 1.0, 0.5)));
- let leader = Leader::Polyline(PolylineCurve(vec![Point3::new(0.0, 0.0, 0.5), Point3::new(1.0, 0.0, 0.5)]));
- let bad = IntersectionCurve::new_unchecked(Box::new(plane(0.5 - support_gap / 2.0)), Box::new(plane(0.5 + support_gap / 2.0)), leader, 0.01);
- let line = |a: &Vertex, b: &Vertex| Edge::new(a, b, Curve::Line(Line(a.point(), b.point())));
- let wire = Wire::from(vec![Edge::new(&v0, &v1, Curve::IntersectionCurve(bad)), line(&v1, &v2), line(&v2, &v0)]);
- Shell::from(vec![Face::new(vec![wire], plane(0.5))])
-}
-
-/// Meshing an edge whose intersection curve does not evaluate (#1252): `IntersectionCurve::subs`
-/// unwraps a failed projection, and the mesher sampled the edge through it. The two supports here
-/// are parallel planes, so the projection never converges. Nothing may panic (wasm aborts on one,
-/// and the native guard prints the message first) and the mesh stays finite.
+/// Meshing an edge whose intersection curve does not evaluate (#1252): the two supports here are
+/// parallel planes, so the projection never converges. Nothing may panic (wasm aborts on one, and
+/// the native guard prints the message first), and a mesh that comes back is finite.
#[test]
fn meshing_an_edge_that_does_not_evaluate_neither_panics_nor_goes_non_finite() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
- use truck_meshalgo::prelude::RobustMeshableShape;
- let shell = triangle_with_intersection_edge(1.0);
-
- let me = std::thread::current().id();
- let count = Arc::new(AtomicUsize::new(0));
- let c2 = count.clone();
- let prev = std::panic::take_hook();
- std::panic::set_hook(Box::new(move |_| {
- if std::thread::current().id() == me {
- c2.fetch_add(1, Ordering::SeqCst);
- }
- }));
- let meshed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| shell.robust_triangulation(0.01)));
- std::panic::set_hook(prev);
- assert_eq!(count.load(Ordering::SeqCst), 0, "panics while meshing");
- let meshed = meshed.unwrap();
- for face in meshed.face_iter() {
- if let Some(mesh) = face.surface() {
- assert!(mesh.positions().iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()));
+ for gap in [1.0, 0.0] {
+ let me = std::thread::current().id();
+ let count = Arc::new(AtomicUsize::new(0));
+ let c2 = count.clone();
+ let prev = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |_| {
+ if std::thread::current().id() == me {
+ c2.fetch_add(1, Ordering::SeqCst);
+ }
+ }));
+ let meshed = std::panic::catch_unwind(|| {
+ crate::Body::from_record(triangle_with_intersection_edge(gap)).and_then(|body| body.mesh(&crate::MeshTolerance::chord(0.01)))
+ });
+ std::panic::set_hook(prev);
+ assert_eq!(count.load(Ordering::SeqCst), 0, "gap {gap}: panics while meshing");
+ if let Ok(Ok(mesh)) = meshed {
+ assert!(mesh.positions.iter().all(|p| p.is_finite()), "gap {gap}");
}
}
}
-
-/// A boolean's result with an edge that does not evaluate is refused with an error (#1252). The
-/// mesher's panic on such an edge used to reject the attempt; now that it no longer panics, the
-/// result must be refused explicitly or a plausible-looking mesh would let it through.
-#[test]
-fn a_result_with_an_edge_that_does_not_evaluate_is_refused() {
- use truck_modeling::Solid;
- let solid = |gap: f64| Solid::new_unchecked(vec![triangle_with_intersection_edge(gap)]);
- assert!(!crate::boolean_record::edges_evaluate(&solid(1.0)));
- assert!(crate::boolean_record::edges_evaluate(&solid(0.0)));
-}
diff --git a/crates/kernel/src/issue_1038_tests.rs b/crates/kernel/src/issue_1038_tests.rs
index 979ff729dc..b8d22f48dd 100644
--- a/crates/kernel/src/issue_1038_tests.rs
+++ b/crates/kernel/src/issue_1038_tests.rs
@@ -1,13 +1,8 @@
-//! #1038: a small hole on a large curved face divides its intersection edges from each point's
-//! neighbour (the vendored `IntersectionCurve::parameter_division`) instead of searching both
-//! surfaces from nothing for every point. These pin the hinted division to the search from
-//! nothing, so a refresh of the vendored crate can't quietly lose the speedup or change a body.
-
-use std::time::{Duration, Instant};
+//! #1038: a small hole on a large curved face cuts cleanly, its rim on the face an intersection
+//! edge.
+use solidcraft_geom::brep::Curve;
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
-use truck_modeling as mt;
-use truck_modeling::{BoundedCurve, ParameterDivision1D};
use crate::{Body, BoolOp, build::extrude, cylinder, ops::boolean};
@@ -24,14 +19,15 @@ fn holed() -> (Body, Body) {
(block, cut)
}
-fn intersection_curves(body: &Body) -> Vec<mt::Curve> {
- body.solid.edge_iter().map(|e| e.curve()).filter(|c| matches!(c, mt::Curve::IntersectionCurve(_))).collect()
-}
-
-fn timed<T>(f: impl Fn() -> T) -> (T, Duration) {
- let start = Instant::now();
- let out = f();
- (out, start.elapsed())
+/// The edges that are intersection curves: neither lines nor conics (a hole's rim on a spline
+/// face is a spline).
+fn intersection_curves(body: &Body) -> Vec<Curve> {
+ body.record()
+ .edges
+ .iter()
+ .map(|e| e.curve.clone())
+ .filter(|c| matches!(c, Curve::Spline { .. } | Curve::RationalSpline { .. } | Curve::SurfaceIntersection { .. }))
+ .collect()
}
#[test]
@@ -49,53 +45,3 @@ fn a_small_hole_in_a_large_spline_face_cuts_cleanly() {
let removed = std::f64::consts::PI * 0.25 * 40.0;
assert!((v0 - v1 - removed).abs() < 0.05 * removed, "removed {} of {removed}", v0 - v1);
}
-
-#[test]
-fn hinted_division_matches_the_search_from_nothing_and_is_faster() {
- let (_, cut) = holed();
- let (mut hinted_time, mut scratch_time) = (Duration::ZERO, Duration::ZERO);
- for curve in intersection_curves(&cut) {
- let mt::Curve::IntersectionCurve(ic) = &curve else { continue };
- let range = ic.range_tuple();
- for tol in [0.01, 0.001] {
- let ((hp, hq), ht) = timed(|| ic.parameter_division(range, tol));
- let ((sp, _), st) = timed(|| mt::algo::curve::parameter_division(ic, range, tol));
- hinted_time += ht;
- scratch_time += st;
- // The same division up to rounding: the hinted projections converge to within the
- // Newton tolerance of the searched ones, so a split the chord test only just asks for
- // can come out one way or the other, but no more than that.
- assert_eq!((hp.first(), hp.last()), (sp.first(), sp.last()), "tol {tol}");
- assert!(hp.len().abs_diff(sp.len()) <= 2, "tol {tol}: {} points hinted, {} from nothing", hp.len(), sp.len());
- // Every hinted point is the curve's own point at its parameter.
- for (t, h) in hp.iter().zip(&hq) {
- let s = ic.search_triple(*t).unwrap().0;
- assert!(mt::MetricSpace::distance(*h, s) < 1e-6, "tol {tol}, t {t}: {h:?} vs {s:?}");
- }
- }
- }
- eprintln!("hinted {hinted_time:?}, from nothing {scratch_time:?}");
- // The hinted path skips each point's grid search of the B-spline face; a loose bound, so a
- // loaded runner doesn't trip it, but one a fallback to the search for every point would.
- assert!(hinted_time * 2 < scratch_time, "hinted {hinted_time:?}, from nothing {scratch_time:?}");
-}
-
-/// #4623: dividing an intersection edge at a tolerance finer than truck's 1e-6 (or one that is
-/// not a number) panicked in truck's tolerance assertion, and the join that asked for it failed.
-/// It divides at 1e-6 instead.
-#[test]
-fn dividing_an_intersection_edge_finer_than_truck_allows_divides_at_its_tolerance() {
- let (_, cut) = holed();
- let curves = intersection_curves(&cut);
- assert!(!curves.is_empty());
- for curve in curves {
- let mt::Curve::IntersectionCurve(ic) = &curve else { continue };
- let range = ic.range_tuple();
- let at_truck = ic.parameter_division(range, 1e-6);
- for tol in [5e-7, 1e-12, 0.0, -1.0, f64::NAN] {
- let got = std::panic::catch_unwind(|| ic.parameter_division(range, tol));
- let Ok(got) = got else { panic!("dividing at {tol:e} panicked") };
- assert_eq!(got, at_truck, "tolerance {tol:e}");
- }
- }
-}
diff --git a/crates/kernel/src/issue_1510_tests.rs b/crates/kernel/src/issue_1510_tests.rs
index b942ebe188..b5980f1815 100644
--- a/crates/kernel/src/issue_1510_tests.rs
+++ b/crates/kernel/src/issue_1510_tests.rs
@@ -24,11 +24,10 @@ fn a_split_in_the_plane_of_a_face_keeps_all_of_the_body() {
let b = plate(width);
let v = b.volume_at(1e-3).unwrap();
let plane = Plane::from_normal(Vec3::new(0.0, 0.0, 1.5), Vec3::Z).unwrap();
- let (parts, d) = crate::capture_boolean_diagnostics(|| split_by_plane(&b, &plane));
- let parts = parts.unwrap();
+ let parts = split_by_plane(&b, &plane).unwrap();
assert_eq!(parts.len(), 2, "{width}");
let vs: Vec<f64> = parts.iter().map(|p| p.volume_at(1e-3).unwrap()).collect();
- assert!((vs.iter().sum::<f64>() - v).abs() < 1e-6 * v, "{width}: {vs:?} against {v}; {:?}", d.summary());
+ assert!((vs.iter().sum::<f64>() - v).abs() < 1e-6 * v, "{width}: {vs:?} against {v}");
// Above: the plate from 1.5 to 2.5 less the hole; below: less the hole and the groove.
let (r, h) = (2.5f64, width / 2.0);
let hole = std::f64::consts::PI * r * r;
@@ -36,44 +35,31 @@ fn a_split_in_the_plane_of_a_face_keeps_all_of_the_body() {
let groove = width * 20.0 - (h * (r * r - h * h).sqrt() + r * r * (h / r).asin());
let want = [800.0 - hole, 1.5 * (800.0 - hole - groove)];
for (got, want) in vs.iter().zip(want) {
- assert!((got - want).abs() < 0.05, "{width}: {vs:?} against {want}; {:?}", d.summary());
+ assert!((got - want).abs() < 0.05, "{width}: {vs:?} against {want}");
}
// Both parts end in the plane, not off it.
let z: Vec<(f64, f64)> = parts.iter().map(|p| crate::measure(p).map(|m| (m.bbox.min.z, m.bbox.max.z)).unwrap()).collect();
- assert!((z[0].0 - 1.5).abs() < 1e-6 && (z[1].1 - 1.5).abs() < 1e-6, "{width}: {z:?}; {:?}", d.summary());
+ assert!((z[0].0 - 1.5).abs() < 1e-6 && (z[1].1 - 1.5).abs() < 1e-6, "{width}: {z:?}");
}
}
/// A slab whose bottom rises 0.03 mm over its 700 mm length, its plane through the origin: its
-/// normal is within 1e-9 of the split plane's, but it doesn't lie in the plane, so it is not
-/// moved, and the part on the upper side is the whole slab.
+/// normal is within 1e-9 of the split plane's, but it doesn't lie in the plane, so the part on
+/// the upper side is the whole slab.
#[test]
fn a_face_only_nearly_in_the_plane_is_not_moved() {
- use truck_modeling as mt;
- let v = |x: f64, y: f64, z: f64| mt::builder::vertex(crate::body::p3(Vec3::new(x, y, z)));
- let p = [v(0.0, 0.0, 0.0), v(0.0, 100.0, 0.0), v(700.0, 100.0, 0.03), v(700.0, 0.0, 0.03)];
- let wire: mt::Wire = (0..4).map(|i| mt::builder::line(&p[i], &p[(i + 1) % 4])).collect();
- let surface = mt::Plane::new(crate::body::p3(Vec3::ZERO), crate::body::p3(Vec3::Y), crate::body::p3(Vec3::new(700.0, 0.0, 0.03)));
- let bottom = mt::Face::new(vec![wire], mt::Surface::Plane(surface));
- let b = Body::new(mt::builder::tsweep(&bottom, mt::Vector3::new(0.0, 0.0, 10.0))).unwrap();
+ let x = Vec3::new(700.0, 0.0, 0.03).normalized().unwrap();
+ let bottom = Plane::new(Vec3::ZERO, x, Vec3::Y).unwrap();
+ let outer = solidcraft_geom::Loop2::polygon(&[
+ solidcraft_geom::Vec2::new(0.0, 0.0),
+ solidcraft_geom::Vec2::new(Vec3::new(700.0, 0.0, 0.03).len(), 0.0),
+ solidcraft_geom::Vec2::new(Vec3::new(700.0, 0.0, 0.03).len(), 100.0),
+ solidcraft_geom::Vec2::new(0.0, 100.0),
+ ]);
+ let b = crate::extrude(&bottom, &[solidcraft_geom::Region2 { outer, holes: vec![] }], 0.0, 10.0).unwrap().pop().unwrap();
let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap();
- assert!(crate::ops::off_plane(&b, &plane, true).is_none());
let v0 = b.volume_at(1e-2).unwrap();
let up = crate::ops::half_space(&b, &plane, true).unwrap().0.unwrap();
let v1 = up.volume_at(1e-2).unwrap();
assert!((v1 - v0).abs() < 1e-3 * v0, "{v1} against {v0}");
}
-
-/// A box whose top face is 3e-5 above the plane, within the boolean's tolerance but off it: the
-/// face bounds a real sliver, and it is not moved.
-#[test]
-fn a_face_close_to_the_plane_but_off_it_is_not_moved() {
- let b = box_solid(Vec3::new(0.0, 0.0, -10.0), Vec3::new(700.0, 100.0, 3e-5)).unwrap();
- let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap();
- assert!(crate::ops::off_plane(&b, &plane, true).is_none());
- assert!(crate::ops::off_plane(&b, &plane, false).is_none());
- // A face in the plane is moved.
- let plate = plate(4.0);
- let at = Plane::from_normal(Vec3::new(0.0, 0.0, 1.5), Vec3::Z).unwrap();
- assert!(crate::ops::off_plane(&plate, &at, true).is_some() && crate::ops::off_plane(&plate, &at, false).is_some());
-}
diff --git a/crates/kernel/src/issue_2005_tests.rs b/crates/kernel/src/issue_2005_tests.rs
index 78c328e438..532a07b436 100644
--- a/crates/kernel/src/issue_2005_tests.rs
+++ b/crates/kernel/src/issue_2005_tests.rs
@@ -33,7 +33,8 @@ fn tube(body: &Body, volume: f64, genus: usize) {
assert!((m.volume - volume).abs() < volume * 0.01, "{m:?}, expected {volume}");
// A closed orientable tube has Euler characteristic 2 - 2g. Coincident caps gave 2.
assert_eq!(m.vertices + m.faces + 2 * genus, m.edges + 2, "{m:?}");
- assert!(body.solid.boundaries().iter().all(|s| s.extract_boundaries().is_empty()));
+ // Every shell closed: each edge bounds two faces.
+ assert!(body.record().edges.iter().all(|e| e.uses.len() >= 2));
let h = body.history().expect("sweep provenance");
assert!(h.faces.iter().all(|f| f.origins.iter().all(|o| matches!(o, crate::history::FaceOrigin::Profile { .. }))));
}
diff --git a/crates/kernel/src/issue_616_tests.rs b/crates/kernel/src/issue_616_tests.rs
index 6cfa8d381d..2d55fdcf09 100644
--- a/crates/kernel/src/issue_616_tests.rs
+++ b/crates/kernel/src/issue_616_tests.rs
@@ -54,7 +54,11 @@ fn moved_outside(from: &Mesh, onto: &Mesh, region: &Aabb3, tol: f64) -> Option<V
/// (a slit, a moved face) and none lost, outside the tool's box.
fn assert_local(target: &Body, tool: &Body, joined: &Body, what: &str) {
let tol = 1e-3;
- let (mt, mtool, mj) = (target.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(), tool.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(), joined.mesh(&crate::MeshTolerance::chord(0.01)).unwrap());
+ let (mt, mtool, mj) = (
+ target.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(),
+ tool.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(),
+ joined.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(),
+ );
let mut region = mtool.bounds();
region.min -= Vec3::new(0.01, 0.01, 0.01);
region.max += Vec3::new(0.01, 0.01, 0.01);
@@ -64,19 +68,17 @@ fn assert_local(target: &Body, tool: &Body, joined: &Body, what: &str) {
/// The four ribs of the issue, 1.6 × 6 × 11.7, sit on the plate (z = 2.4), over the skirt, flush
/// with the window's sides. Each join adds exactly what lies outside the skirt, changes nothing
-/// else (it used to leave a slit through the far wall), and needs no displacement of the tool.
+/// else (it used to leave a slit through the far wall).
#[test]
fn ribs_joined_flush_to_the_lid_change_nothing_else() {
let mut b = lid();
assert!((volume(&b) - 6703.5222).abs() < 1e-3, "{}", volume(&b));
for c in [[102.8, 14., 2.4], [102.8, 48., 2.4], [172.4, 14., 2.4], [172.4, 48., 2.4]] {
let tool = bx(c, [1.6, 6., 11.7]);
- let (r, report) = capture_boolean_diagnostics(|| boolean(&b, &tool, BoolOp::Union));
- let r = r.unwrap().unwrap();
+ let r = boolean(&b, &tool, BoolOp::Union).unwrap().unwrap();
// 1.6 × 6 × 11.7 less the 1.35 × 6 × 3 inside the skirt.
assert!((volume(&r) - volume(&b) - 88.02).abs() < 1e-6, "{c:?}: {}", volume(&r) - volume(&b));
- assert!(!report.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge), "{c:?}: {report:?}");
- assert_eq!(r.solid.boundaries().len(), 1);
+ assert_eq!(r.shell_count(), 1);
assert_local(&b, &tool, &r, &format!("{c:?}"));
b = r;
}
@@ -84,40 +86,6 @@ fn ribs_joined_flush_to_the_lid_change_nothing_else() {
assert!((bounds.max.z - 14.1).abs() < 1e-9, "the ribs keep their height: {}", bounds.max.z);
}
-/// A plane cut through a frame meets it in two faces; gluing the halves back joins both (one
-/// left over was the slit of #616).
-#[test]
-fn glue_joins_every_face_the_pieces_share() {
- let frame = boolean(&bx([0., 0., 0.], [40., 30., 5.]), &bx([5., 5., -1.], [30., 20., 7.]), BoolOp::Cut).unwrap().unwrap();
- let low = boolean(&frame, &bx([-1., -1., -1.], [42., 16., 7.]), BoolOp::Intersect).unwrap().unwrap();
- let high = boolean(&frame, &bx([-1., 15., -1.], [42., 16., 7.]), BoolOp::Intersect).unwrap().unwrap();
- let glued = crate::coplanar::glue(&low, &high).unwrap().unwrap();
- assert_eq!(glued.solid.boundaries().len(), 1);
- assert!((volume(&glued) - volume(&frame)).abs() < 1e-6);
- assert!((measure(&glued).unwrap().area - measure(&frame).unwrap().area).abs() < 1e-6, "no faces left inside");
-}
-
-/// The guard refuses a result that changed the target away from the tool, or lost volume in a
-/// join, and accepts the right one.
-#[test]
-fn the_retry_guard_refuses_changes_away_from_the_tool() {
- let target = bx([0., 0., 0.], [40., 30., 5.]);
- let tool = bx([0., 0., 5.], [4., 4., 4.]);
- let right = boolean(&target, &tool, BoolOp::Union).unwrap().unwrap();
- assert!(crate::boolean_guard::check_retry(&target, &tool, BoolOp::Union, Some(&right)).is_ok());
- // A notch far from the tool (volume still up: the tool adds more than the notch takes).
- let notched = boolean(&right, &bx([30., 10., 4.], [2., 2., 2.]), BoolOp::Cut).unwrap().unwrap();
- let e = crate::boolean_guard::check_retry(&target, &tool, BoolOp::Union, Some(&notched)).unwrap_err().to_string();
- assert!(e.contains("away from the tool") && e.contains("refused"), "{e}");
- // A join that lost volume.
- let e = crate::boolean_guard::check_retry(&target, &tool, BoolOp::Union, Some(&bx([0., 0., 0.], [40., 30., 4.]))).unwrap_err().to_string();
- assert!(e.contains("volume"), "{e}");
- // A cut that comes out empty while the tool covers only part of the target.
- assert!(crate::boolean_guard::check_retry(&target, &tool, BoolOp::Cut, None).is_err());
- assert!(crate::boolean_guard::check_retry(&tool, &target, BoolOp::Cut, None).is_err());
- assert!(crate::boolean_guard::check_retry(&tool, &bx([-1., -1., 4.], [6., 6., 6.]), BoolOp::Cut, None).is_ok());
-}
-
/// Random small boxes joined flush to the walls and floor of a shelled box with rounded corners
/// (sitting on the floor, against a wall, flush with a wall's top or into its corner), and of
/// the same box with a window through its floor (on the ledge beside the window, flush with its
diff --git a/crates/kernel/src/issue_674_tests.rs b/crates/kernel/src/issue_674_tests.rs
index 8872d01fd7..c6db48fe17 100644
--- a/crates/kernel/src/issue_674_tests.rs
+++ b/crates/kernel/src/issue_674_tests.rs
@@ -5,11 +5,15 @@ use std::f64::consts::PI;
#[test]
fn split_contact_arc_crossing_one_edge_twice_preserves_the_body() {
- use truck_modeling::Surface;
let a = box_solid(Vec3::ZERO, Vec3::new(25.0, 47.5, 37.5)).unwrap();
let b = cylinder(Vec3::new(0.0, 7.5, 0.0), -Vec3::X, 5.0, 2.5).unwrap();
let face = a.faces(0.01).unwrap().iter().position(|f| f.plane_normal.is_some_and(|n| n.dot(-Vec3::X) > 0.99)).unwrap();
- let side = b.solid.face_iter().position(|f| !matches!(f.surface(), Surface::Plane(_))).unwrap();
+ let side = b
+ .record()
+ .faces
+ .iter()
+ .position(|f| !matches!(f.surface, solidcraft_geom::brep::Surface::Plane { .. } | solidcraft_geom::brep::Surface::PlaneThrough { .. }))
+ .unwrap();
let r = split_faces(&a, &[face], &SplitTool::Face { body: &b, face: side }).unwrap();
assert_eq!(r.face_count(), a.face_count() + 1);
assert!(r.validity().is_empty(), "{:?}", r.validity());
@@ -19,15 +23,6 @@ fn split_contact_arc_crossing_one_edge_twice_preserves_the_body() {
assert!((before.area - after.area).abs() < 1e-7);
}
-#[test]
-fn partial_contact_does_not_join_tangent_or_separated_faces() {
- let a = box_solid(Vec3::ZERO, Vec3::new(25.0, 47.5, 37.5)).unwrap();
- for z in [-5.0, -6.0] {
- let b = cylinder(Vec3::new(0.0, 7.5, z), -Vec3::X, 5.0, 2.5).unwrap();
- assert!(crate::coplanar::imprint_union(&a, &b, &|_| true).is_none());
- }
-}
-
#[test]
fn partial_contact_retains_an_authored_split_away_from_the_contact() {
let a = box_solid(Vec3::ZERO, Vec3::new(25.0, 47.5, 37.5)).unwrap();
diff --git a/crates/kernel/src/join_between_caps_tests.rs b/crates/kernel/src/join_between_caps_tests.rs
index f4c76fb686..ed21d42a55 100644
--- a/crates/kernel/src/join_between_caps_tests.rs
+++ b/crates/kernel/src/join_between_caps_tests.rs
@@ -9,7 +9,6 @@ use std::f64::consts::PI;
use solidcraft_geom::Vec3;
-use crate::body::from_p3;
use crate::*;
/// A 40 × 20 × 6 plate (z 5 … 11) with a 14 × 10 × 6 leaf under its back edge, 1 mm into it:
@@ -23,7 +22,7 @@ fn plate_with_leaf() -> Body {
/// Barrels along x with their axis on the leaf's back bottom edge (y 20, z 0): radius 5 (its top
/// meets the plate's back edge) and 4.9, ends flush with both of the leaf's sides, with one, and
/// running on past both under the plate. A quarter of the barrel lies in the leaf (where the
-/// leaf is). Each join is exact: no retry, one solid, and every vertex on a level along x of the
+/// leaf is). Each join is exact: one solid, and every vertex on a level along x of the
/// plate, the leaf or the barrel.
#[test]
fn a_barrel_between_the_sides_of_a_leaf_joins_exactly() {
@@ -31,16 +30,14 @@ fn a_barrel_between_the_sides_of_a_leaf_joins_exactly() {
for (r, x0, x1) in [(5., 10., 24.), (4.9, 10., 24.), (5., 10., 23.), (5., 8.5, 25.5)] {
let what = format!("radius {r}, x {x0} … {x1}");
let barrel = cylinder(Vec3::new(x0, 20., 0.), Vec3::X, r, x1 - x0).unwrap();
- let (joined, d) = capture_boolean_diagnostics(|| boolean(&part, &barrel, BoolOp::Union));
- let joined = joined.unwrap().unwrap();
- assert!(d.events.is_empty(), "{what}: {d:?}");
+ let joined = boolean(&part, &barrel, BoolOp::Union).unwrap().unwrap();
assert_eq!(joined.shell_count(), 1, "{what}");
assert!(joined.validity().is_empty(), "{what}: {:?}", joined.validity());
let inside = (x1.min(24.) - x0.max(10.)) / 4.;
let want = 5500. + PI * r * r * (x1 - x0 - inside);
let v = joined.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume;
assert!((v - want).abs() < want * 1e-5, "{what}: volume {v} vs {want}");
- for p in joined.solid.vertex_iter().map(|v| from_p3(v.point())) {
+ for p in joined.record().vertices.iter().map(|v| Vec3::from(v.point)) {
assert!([0., 10., 24., 40., x0, x1].iter().any(|x| (p.x - x).abs() < 1e-9), "{what}: a vertex at {p:?}");
}
}
diff --git a/crates/kernel/src/mesh_memo_tests.rs b/crates/kernel/src/mesh_memo_tests.rs
index f5807631e2..d1c6247f1f 100644
--- a/crates/kernel/src/mesh_memo_tests.rs
+++ b/crates/kernel/src/mesh_memo_tests.rs
@@ -57,7 +57,8 @@ fn a_copy_with_another_solid_makes_its_own_meshes() {
let kept = plate().keeping_meshes();
let other = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();
let mut swapped = kept.clone();
- swapped.solid = other.solid.clone();
+ swapped.record = other.record.clone();
+ swapped.smlib = other.smlib.clone();
let _ = kept.mesh(&crate::MeshTolerance::chord(0.5)).unwrap();
let m = swapped.mesh(&crate::MeshTolerance::chord(0.5)).unwrap();
assert_eq!(m.triangles.len(), other.mesh(&crate::MeshTolerance::chord(0.5)).unwrap().triangles.len());
diff --git a/crates/kernel/src/placement_tests.rs b/crates/kernel/src/placement_tests.rs
index 5fd4e7e07f..e788d39bc5 100644
--- a/crates/kernel/src/placement_tests.rs
+++ b/crates/kernel/src/placement_tests.rs
@@ -1,64 +1,41 @@
use super::*;
-use crate::body::{p3, v3};
-use mt::builder;
+use crate::history::BodyHistory;
+/// `p` moved by the column-major affine `matrix`.
+fn moved(matrix: [[f64; 4]; 4], p: [f64; 3]) -> Vec3 {
+ Vec3::new(
+ matrix[0][0] * p[0] + matrix[1][0] * p[1] + matrix[2][0] * p[2] + matrix[3][0],
+ matrix[0][1] * p[0] + matrix[1][1] * p[1] + matrix[2][1] * p[2] + matrix[3][1],
+ matrix[0][2] * p[0] + matrix[1][2] * p[1] + matrix[2][2] * p[2] + matrix[3][2],
+ )
+}
+
+/// A rigid placement moves the record and nothing else: the same regions, shells, faces' loops
+/// (edges, directions and pcurves: each surface moves with its parameters), edges' ends and uses;
+/// every vertex moved by the motion; and the history the identity's.
fn assert_topology(source: &Body, placed: &Body, matrix: [[f64; 4]; 4]) {
- use std::collections::HashMap;
- let mut vertices = HashMap::new();
- let mut edges = HashMap::new();
- for (a, b) in source.solid.face_iter().zip(placed.solid.face_iter()) {
- assert_eq!(a.orientation(), b.orientation());
- let aw = a.absolute_boundaries();
- let bw = b.absolute_boundaries();
- assert_eq!(aw.len(), bw.len());
- for (a, b) in aw.iter().zip(bw.iter()) {
- assert_eq!(a.len(), b.len());
- for (a, b) in a.edge_iter().zip(b.edge_iter()) {
- assert_eq!(a.orientation(), b.orientation());
- assert_ne!(a.id(), b.id());
- assert_eq!(*edges.entry(a.id()).or_insert(b.id()), b.id());
- for (a, b) in [(a.absolute_front(), b.absolute_front()), (a.absolute_back(), b.absolute_back())] {
- assert_ne!(a.id(), b.id());
- assert_eq!(*vertices.entry(a.id()).or_insert(b.id()), b.id());
- let p = from_p3(a.point());
- let expected = Vec3::new(
- matrix[0][0] * p.x + matrix[1][0] * p.y + matrix[2][0] * p.z + matrix[3][0],
- matrix[0][1] * p.x + matrix[1][1] * p.y + matrix[2][1] * p.z + matrix[3][1],
- matrix[0][2] * p.x + matrix[1][2] * p.y + matrix[2][2] * p.z + matrix[3][2],
- );
- assert!(from_p3(b.point()).dist(expected) < 1e-9);
- }
- }
- }
+ let (a, b) = (source.record(), placed.record());
+ assert_eq!(a.regions, b.regions);
+ assert_eq!(a.shells, b.shells);
+ assert_eq!(a.faces.len(), b.faces.len());
+ for (fa, fb) in a.faces.iter().zip(&b.faces) {
+ assert_eq!(fa.loops, fb.loops);
+ assert_eq!(fa.domain, fb.domain);
+ }
+ assert_eq!(a.edges.len(), b.edges.len());
+ for (ea, eb) in a.edges.iter().zip(&b.edges) {
+ assert_eq!((ea.vertices, &ea.uses, ea.interval), (eb.vertices, &eb.uses, eb.interval));
+ }
+ assert_eq!(a.vertices.len(), b.vertices.len());
+ for (va, vb) in a.vertices.iter().zip(&b.vertices) {
+ assert!(Vec3::from(vb.point).dist(moved(matrix, va.point)) < 1e-9);
}
- assert_eq!(edges.len(), source.solid.edge_iter().map(|e| e.id()).collect::<std::collections::HashSet<_>>().len());
+ assert_eq!(placed.history(), Some(&<crate::history::History as BodyHistory>::identity(source)));
}
+/// A cylinder whose wall is one face with a seam: the seam edge is used twice by the wall's loop.
fn periodic_cylinder() -> Body {
- let b0 = builder::vertex(p3(Vec3::new(10., 0., 0.)));
- let b1 = builder::vertex(p3(Vec3::new(-10., 0., 0.)));
- let t0 = builder::vertex(p3(Vec3::new(10., 0., 20.)));
- let t1 = builder::vertex(p3(Vec3::new(-10., 0., 20.)));
- let bottom: mt::Wire =
- vec![builder::circle_arc(&b0, &b1, p3(Vec3::new(0., 10., 0.))), builder::circle_arc(&b1, &b0, p3(Vec3::new(0., -10., 0.)))].into();
- let top: mt::Wire =
- vec![builder::circle_arc(&t0, &t1, p3(Vec3::new(0., 10., 20.))), builder::circle_arc(&t1, &t0, p3(Vec3::new(0., -10., 20.)))].into();
- let seam = builder::line(&b0, &t0);
- let mut boundary: Vec<_> = bottom.edge_iter().cloned().collect();
- boundary.push(seam.clone());
- boundary.extend(top.inverse().edge_iter().cloned());
- boundary.push(seam.inverse());
- let wall = mt::Face::new_unchecked(
- vec![boundary.into()],
- mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(
- seam.inverse().oriented_curve(),
- p3(Vec3::ZERO),
- v3(Vec3::Z),
- ))),
- );
- let lower = builder::try_attach_plane(&[bottom.inverse()]).unwrap();
- let upper = builder::try_attach_plane(&[top]).unwrap();
- Body::new(Solid::new_unchecked(vec![vec![wall, lower, upper].into()])).unwrap()
+ crate::cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap()
}
#[test]
@@ -68,9 +45,14 @@ fn periodic_step_seam_survives_identity_rotation_and_translation() {
let imported = crate::step_import(&bytes).unwrap();
assert!(imported.warnings.is_empty(), "{:?}", imported.warnings);
let body = &imported.bodies.first().unwrap().body;
- assert!(body.solid.face_iter().any(|f| f.absolute_boundaries().iter().any(|w| !w.is_simple())));
- let source_vertices: Vec<_> = body.solid.vertex_iter().map(|v| from_p3(v.point())).collect();
- let source_faces = body.solid.face_iter().count();
+ // A face whose loop uses an edge twice (the seam).
+ let seamed = body.record().faces.iter().any(|f| {
+ f.loops.iter().any(|l| match l {
+ solidcraft_geom::brep::Loop::Edges { edges } => edges.iter().any(|u| edges.iter().filter(|w| w.edge == u.edge).count() > 1),
+ solidcraft_geom::brep::Loop::Vertex { .. } => false,
+ })
+ });
+ assert!(seamed);
let unchanged = crate::step_export(&[body], "source snapshot").unwrap();
let before = body.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume;
assert!((before - 2000. * std::f64::consts::PI).abs() < 1.);
@@ -81,8 +63,6 @@ fn periodic_step_seam_survives_identity_rotation_and_translation() {
] {
let moved = transform_matrix(body, matrix).unwrap();
assert_topology(body, &moved, matrix);
- assert_eq!(moved.solid.face_iter().count(), source_faces);
- assert_eq!(moved.solid.vertex_iter().count(), source_vertices.len());
let after = moved.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume;
assert!((after - before).abs() < 1e-5, "{after} vs {before}");
let roundtrip = crate::step_import(&crate::step_export(&[&moved], "placement regression").unwrap()).unwrap();
diff --git a/crates/kernel/src/regularization_protection_tests.rs b/crates/kernel/src/regularization_protection_tests.rs
index 5164550574..fd5d5aa7c1 100644
--- a/crates/kernel/src/regularization_protection_tests.rs
+++ b/crates/kernel/src/regularization_protection_tests.rs
@@ -15,13 +15,7 @@ fn stamped_shell_keeps_authored_painted_and_split_boundaries() {
let ordinary = cup(&stock);
assert!(!ordinary.regularization_protected);
let painted = stock.clone().with_paint(Some(Paint { opacity: 1., faces: vec![FacePaint { face: 0, color: [1., 0., 0.], opacity: 1. }] }));
- let side = stock
- .solid
- .face_iter()
- .enumerate()
- .find(|(i, _)| stock.planar_face(*i).is_some_and(|p| p.normal().dot(Vec3::X) > 0.999 && p.origin.x == 20.))
- .unwrap()
- .0;
+ let side = (0..stock.face_count()).find(|i| stock.planar_face(*i).is_some_and(|p| p.normal().dot(Vec3::X) > 0.999 && p.origin.x == 20.)).unwrap();
let split = crate::split_faces(&stock, &[side], &crate::SplitTool::Plane(Plane { origin: Vec3::new(0., 0., 8.), ..Plane::XY })).unwrap();
assert!(split.split_lines().is_some());
for protected in [painted, split] {
diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs
index 78546a74a3..dc3cbd01a3 100644
--- a/crates/kernel/src/surfaces.rs
+++ b/crates/kernel/src/surfaces.rs
@@ -1194,7 +1194,6 @@ fn open_sections(sections: &[(Plane, Vec<Seg2>)]) -> Result<Vec<crate::loft_rail
}
/// SMLib's side of this module.
-#[cfg(feature = "smlib")]
mod imp {
use solidcraft_smlib::sweeps::{Affine, Curve, Ends, SweepFrame};
use solidcraft_smlib::{Brep as SmBrep, CheckLevel};
@@ -1547,51 +1546,6 @@ mod imp {
}
}
-#[cfg(not(feature = "smlib"))]
-mod imp {
- use super::*;
-
- fn not_built() -> KernelError {
- refuse("surfaces: this build has no SMLib (feature `smlib`)")
- }
- pub(super) fn refuse(what: &str) -> KernelError {
- crate::smlib_sweeps::refuse(what)
- }
- pub(super) fn stitched(_: &Brep, _: f64) -> Result<(Body, Option<History>)> {
- Err(not_built())
- }
- pub(super) fn thicken(_: &Body, _: f64, _: bool) -> Result<Body> {
- Err(not_built())
- }
- pub(super) fn offset_face(_: &Brep, _: usize, _: f64) -> Result<Brep> {
- Err(not_built())
- }
- pub(super) fn extruded(_: &Plane, _: &[Numbered], _: Vec3, _: f64) -> Result<Brep> {
- Err(not_built())
- }
- pub(super) fn revolved(_: &Plane, _: &[Numbered], _: Vec3, _: Vec3, _: f64) -> Result<Brep> {
- Err(not_built())
- }
- pub(super) fn swept(_: &Plane, _: &[Numbered], _: &[crate::PathSeg], _: bool) -> Result<Brep> {
- Err(not_built())
- }
- pub(super) fn cornered(
- _: &Plane,
- _: &[Numbered],
- _: &[crate::PathSeg],
- _: &[std::ops::Range<usize>],
- _: bool,
- ) -> Result<Vec<(Brep, Vec<FaceProv>)>> {
- Err(not_built())
- }
- pub(super) fn swept_stations(_: &Plane, _: &[Numbered], _: &[crate::PathSeg], _: &crate::SweepControl) -> Result<Brep> {
- Err(not_built())
- }
- pub(super) fn lofted(_: &[&solidcraft_geom::bspline::CurveN<4>]) -> Result<Brep> {
- Err(not_built())
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs
index caf0ae1234..a365f25a2f 100644
--- a/crates/kernel/src/thin_face_tests.rs
+++ b/crates/kernel/src/thin_face_tests.rs
@@ -8,10 +8,10 @@
use std::collections::HashMap;
use solidcraft_geom::Vec3;
-use truck_meshalgo::prelude::*;
-use truck_modeling as mt;
+use solidcraft_geom::brep::{Curve, Loop, Surface};
-use crate::body::p3;
+use crate::body::Body;
+use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble};
use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean};
/// Triangle sides in the mesh with no triangle on the other side of them, with the points
@@ -49,7 +49,7 @@ fn a_lens_thinner_than_the_tolerance_is_meshed() {
}
/// Twice the signed area of a closed polyline in the XY plane.
-fn area2(points: &[mt::Point3]) -> f64 {
+fn area2(points: &[Vec3]) -> f64 {
points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum()
}
@@ -59,26 +59,42 @@ fn area2(points: &[mt::Point3]) -> f64 {
#[test]
fn a_face_touching_its_own_edge_meshes() {
let (h, dip) = (0.3175, 2.8e-7);
- let v = |x: f64, y: f64| mt::builder::vertex(p3(Vec3::new(x, y, 0.0)));
- let (lb, rb, rt, lt) = (v(0.0, 0.0), v(5.0, 0.0), v(5.0, h), v(0.0, h));
- let control = vec![p3(Vec3::new(5.0, h, 0.0)), p3(Vec3::new(2.5, -h - 2.0 * dip, 0.0)), p3(Vec3::new(0.0, h, 0.0))];
- let arch = mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), control);
- let arch = mt::Edge::new(&rt, &lt, mt::Curve::BSplineCurve(arch));
- let wire: mt::Wire = vec![mt::builder::line(&lb, &rb), mt::builder::line(&rb, &rt), arch, mt::builder::line(&lt, &lb)].into();
- let plane = mt::Plane::new(p3(Vec3::ZERO), p3(Vec3::X), p3(Vec3::Y));
- let face = mt::Face::new(vec![wire], mt::Surface::Plane(plane));
- let shell: mt::Shell = vec![face].into();
+ let vertices = vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, h, 0.0], [0.0, h, 0.0]];
+ let line = |a: usize, b: usize| PartEdge {
+ curve: Curve::Line { start: vertices[a], end: vertices[b] },
+ interval: [0.0, 1.0],
+ vertices: [a as u32, b as u32],
+ };
+ let arch = PartEdge {
+ curve: Curve::Spline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![[5.0, h, 0.0], [2.5, -h - 2.0 * dip, 0.0], [0.0, h, 0.0]] },
+ interval: [0.0, 1.0],
+ vertices: [2, 3],
+ };
+ let edges = vec![line(0, 1), line(1, 2), arch, line(3, 0)];
+ let uses = (0..4).map(|e| PartUse { edge: e, forward: true, given: None }).collect();
+ let surface = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] };
+ let made =
+ assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: 1e-7 }, false).unwrap();
+ let body = Body::from_record(made.brep).unwrap();
for tol in [0.3, 0.08, 0.02, 0.005] {
- let meshed = shell.robust_triangulation_within(Deflection { display: true, ..Deflection::chord(tol) });
- let face = meshed.face_iter().next().unwrap();
- let boundary: Vec<mt::Point3> = face.boundaries()[0].edge_iter().flat_map(|e| e.oriented_curve().0.into_iter().skip(1)).collect();
- let mesh = face.surface().unwrap();
+ let mesh = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
+ // The face's boundary polygon: its edges' polylines round its loop.
+ let r = body.record();
+ let Loop::Edges { edges } = &r.faces[0].loops[0] else { panic!("an edge loop") };
+ let mut boundary: Vec<Vec3> = Vec::new();
+ for u in edges {
+ let mut line = mesh.edges[u.edge as usize].clone();
+ if !u.forward {
+ line.reverse();
+ }
+ boundary.extend(line.into_iter().skip(1));
+ }
let area: f64 = mesh
- .faces()
- .triangle_iter()
+ .triangles
+ .iter()
.map(|t| {
- let [a, b, c] = [0, 1, 2].map(|i| mesh.positions()[t[i].pos]);
- (b - a).cross(c - a).magnitude() / 2.0
+ let [a, b, c] = mesh.tri(t).unwrap();
+ (b - a).cross(c - a).len() / 2.0
})
.sum();
// The triangles cover the face's boundary polygon, the parts on both sides of the pinch.
diff --git a/crates/kernel/src/trimmed_face_mesh_tests.rs b/crates/kernel/src/trimmed_face_mesh_tests.rs
index faa5cdf0a6..5ca8e41006 100644
--- a/crates/kernel/src/trimmed_face_mesh_tests.rs
+++ b/crates/kernel/src/trimmed_face_mesh_tests.rs
@@ -2,8 +2,8 @@
use std::f64::consts::FRAC_PI_2;
-use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
-use truck_modeling::{self as mt, SearchNearestParameter};
+use solidcraft_geom::brep::eval::SurfaceEval;
+use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3};
use crate::*;
@@ -43,16 +43,14 @@ fn tube() -> Body {
/// Each face's mesh area, and how far its triangles' centroids lie off its surface at most.
fn per_face(body: &Body, mesh: &solidcraft_geom::Mesh) -> Vec<(f64, f64)> {
- use mt::ParametricSurface;
- let faces: Vec<&mt::Face> = body.solid.face_iter().collect();
+ let faces: Vec<SurfaceEval> = body.record().faces.iter().map(|f| SurfaceEval::new(&f.surface).unwrap()).collect();
let mut out = vec![(0.0, 0.0f64); faces.len()];
for (t, &f) in mesh.triangles.iter().zip(&mesh.tri_face) {
- let ([a, b, c], Some(face), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue };
+ let ([a, b, c], Some(surface), Some(slot)) = (mesh.tri(t).unwrap(), faces.get(f as usize), out.get_mut(f as usize)) else { continue };
slot.0 += (b - a).cross(c - a).len() / 2.0;
let g = (a + b + c) / 3.0;
- let surface = face.oriented_surface();
- let (u, v) = surface.search_nearest_parameter(mt::Point3::new(g.x, g.y, g.z), None, 50).unwrap();
- slot.1 = slot.1.max(crate::body::from_p3(surface.subs(u, v)).dist(g));
+ let uv = surface.project(g, None, f64::INFINITY).unwrap();
+ slot.1 = slot.1.max(surface.point(uv).unwrap().dist(g));
}
out
}
@@ -76,35 +74,3 @@ fn trimmed_ruled_loft_faces_mesh_on_their_surfaces() {
assert!((area - fine_area).abs() < 0.02 * fine_area, "face {fi}: mesh area {area:.0} mm², finer mesh {fine_area:.0} mm²");
}
}
-
-/// #4031: a join whose new face has a boundary segment crossing another in the triangulation's
-/// parameters (a sketch point far out, inside the command cap) never reaches the triangulator's
-/// assertion: it builds while the boolean's own precision holds, and fails cleanly beyond.
-#[test]
-fn a_crossing_boundary_segment_does_not_trip_the_triangulator() {
- use std::sync::Arc;
- use std::sync::atomic::{AtomicUsize, Ordering};
- // The mesher runs on worker threads: count the assertion by its message.
- let count = Arc::new(AtomicUsize::new(0));
- let c2 = count.clone();
- let prev = std::panic::take_hook();
- std::panic::set_hook(Box::new(move |info| {
- if info.to_string().contains("previous_region") {
- c2.fetch_add(1, Ordering::SeqCst);
- }
- }));
- let mut volumes = Vec::new();
- for far in [1e6, 3e6, 9.9e8] {
- let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 10.0)).unwrap();
- let outer = Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), Vec2::new(40.0, far), Vec2::new(0.0, 20.0)]);
- let sliver = extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0.0, 10.0).unwrap().remove(0);
- volumes.push(boolean(&block, &sliver, BoolOp::Union).ok().flatten().and_then(|b| measure(&b).ok()).map(|m| m.volume));
- }
- std::panic::set_hook(prev);
- assert_eq!(count.load(Ordering::SeqCst), 0, "the triangulator's assertion fired");
- // The sliver holds the block: its volume is the union's, (40 * (far + 20) / 2) * 10.
- for (far, v) in [(1e6, volumes[0]), (3e6, volumes[1])] {
- let exact = 40.0 * (far + 20.0) / 2.0 * 10.0;
- assert!(v.is_some_and(|v| (v - exact).abs() < 1e-9 * exact), "far {far}: {v:?}");
- }
-}
diff --git a/crates/kernel/src/untouched_faces_tests.rs b/crates/kernel/src/untouched_faces_tests.rs
index a1e06bd047..f82bf960c8 100644
--- a/crates/kernel/src/untouched_faces_tests.rs
+++ b/crates/kernel/src/untouched_faces_tests.rs
@@ -151,35 +151,27 @@ fn random_cuts_and_joins_never_split_other_faces() {
/// The edges of `b` lying along the line through `a` and `z`.
fn edges_along(b: &Body, a: Vec3, z: Vec3) -> usize {
+ let r = b.record();
let on = |p: Vec3| p.dist_to_segment(a, z) < 1e-6;
- let edges: std::collections::HashSet<_> = b
- .solid
- .edge_iter()
- .filter(|e| on(crate::body::from_p3(e.front().point())) && on(crate::body::from_p3(e.back().point())))
- .map(|e| e.id())
- .collect();
- edges.len()
+ let point = |v: u32| Vec3::from(r.vertices[v as usize].point);
+ r.edges.iter().filter(|e| on(point(e.vertices[0])) && on(point(e.vertices[1]))).count()
}
/// Vertices of `b` where just two straight edges meet in line (a straight edge split in two).
fn stations(b: &Body) -> usize {
- use std::collections::HashMap;
- let mut at: HashMap<truck_modeling::VertexID, Vec<truck_modeling::Edge>> = HashMap::new();
- let mut seen = std::collections::HashSet::new();
- for e in b.solid.edge_iter() {
- if seen.insert(e.id()) {
- for v in [e.front(), e.back()] {
- at.entry(v.id()).or_default().push(e.clone());
- }
+ let r = b.record();
+ let mut at: Vec<Vec<usize>> = vec![Vec::new(); r.vertices.len()];
+ for (i, e) in r.edges.iter().enumerate() {
+ for v in e.vertices {
+ at[v as usize].push(i);
}
}
- at.values()
+ let point = |v: u32| Vec3::from(r.vertices[v as usize].point);
+ let dir = |e: usize| (point(r.edges[e].vertices[1]) - point(r.edges[e].vertices[0])).normalized();
+ let line = |e: usize| matches!(r.edges[e].curve, solidcraft_geom::brep::Curve::Line { .. });
+ at.iter()
.filter(|es| match es.as_slice() {
- [a, b] => {
- let dir = |e: &truck_modeling::Edge| (crate::body::from_p3(e.back().point()) - crate::body::from_p3(e.front().point())).normalized();
- matches!((a.curve(), b.curve()), (truck_modeling::Curve::Line(_), truck_modeling::Curve::Line(_)))
- && dir(a).zip(dir(b)).is_some_and(|(u, w)| u.dot(w).abs() > 1. - 1e-9)
- }
+ [a, b] => line(*a) && line(*b) && dir(*a).zip(dir(*b)).is_some_and(|(u, w)| u.dot(w).abs() > 1. - 1e-9),
_ => false,
})
.count()