Surface trim: projected curves, several kept regions, mutual trim (#767) (#1466)

* kernel: trim keeps picked regions, mutual trim, curves swept along a direction (#767)

Trim moves to surface_trim.rs: TrimKeep::Side (the old behaviour) or
Regions (the connected pieces the points pick, parted where the tool runs
along an edge). mutual_trim cuts two one-face surfaces by each other's
surface, extending one that stops short when asked. SplitTool::Curves takes
a sweep direction; a closed curve's field is signed by inside/outside
instead of extending its end segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM

* kernel: classify display edges of a face with a closed-edge hole without a panic

A hole cut by a closed curve is a loop of one edge that starts and ends at
one vertex; mapping the face rebuilt that edge through a check that
panics on it (the guard caught it and dropped every smooth flag of the
body). Such faces are now left out of the ruled-surface test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM

* surface.trim: keep several regions, trim by projected sketch curves, mutual trim (#767)

keep takes a list of points (the regions they pick); curves: {sketch,
curves?, direction?} sweeps sketch curves onto the surface (along the
surface's normal: not supported yet); with + keep_with trims two
surfaces by each other, extend? meets a short one, stitch? sews the
kept pieces. Trimmed faces carry their lineage, so they are named
after the faces they are pieces of. New fields noted in a pending format file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM

* Trim dialog: sketch curves as the tool, several keep points, mutual trim (#767)

The tool input takes sketch curves too; keep points are places (several
on one face add up); another surface with its keep points makes a mutual
trim with Extend to meet and Stitch toggles. Edit Feature brings it all
back. Labels in every locale catalog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM

* ROADMAP: M8 trim by projected curves, several regions and mutual trim (#767)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGeCa5jWWdroMWvXxN3LLM

---------

Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
Irakli Kourtis
2026-10-19 16:04:02 -04:00
committed by GitHub
parent f1f5298bc5
commit 1cd9983c8f
32 changed files with 1246 additions and 87 deletions
+117 -12
View File
@@ -24,10 +24,11 @@ pub enum SplitTool<'a> {
Plane(Plane),
/// The surface of another body's face (`face` in that body's face order), extended.
Face { body: &'a Body, face: usize },
/// Sketch curves (chains of segments in `plane`) swept along the plane's normal; each curve
/// splits on its own, extended past its ends. A single line or arc splits exactly (a plane
/// or a cylinder); longer chains and splines follow the curve.
Curves { plane: Plane, curves: Vec<Vec<Seg2>> },
/// Sketch curves (chains of segments in `plane`) swept along `along` (none: the plane's
/// normal); each curve splits on its own, an open one extended past its ends. A single line
/// splits exactly (a plane), and so does a single arc swept along the normal (a cylinder);
/// longer chains, splines and arcs swept aslant follow the curve.
Curves { plane: Plane, curves: Vec<Vec<Seg2>>, along: Option<Vec3> },
}
/// Which side of the tool a point is on (zero on the tool).
@@ -45,9 +46,13 @@ enum Field {
r: f64,
out: f64,
},
/// A chain of points in `plane`, swept along `along` (the plane's normal when none). A
/// closed chain is positive inside it; an open one on its left, its end segments extended.
Curve {
plane: Plane,
pts: Vec<Vec2>,
closed: bool,
along: Option<Vec3>,
},
}
@@ -68,9 +73,28 @@ impl Field {
let radial = v - *axis * v.dot(*axis);
*out * (radial.len() - *r)
}
Field::Curve { plane, pts } => {
Field::Curve { plane, pts, closed, along } => {
// Where p's line along the sweep direction meets the plane.
let p = match along {
Some(d) => p - *d * ((p - plane.origin).dot(plane.normal()) / d.dot(plane.normal())),
None => p,
};
let q = plane.to_local(p);
let q = Vec2::new(q.x, q.y);
if *closed {
// Distance to the loop, positive inside it.
let d = (0..pts.len().saturating_sub(1))
.filter_map(|i| Some((*pts.get(i)?, *pts.get(i + 1)?)))
.map(|(a, b)| {
let d = b - a;
let l2 = d.dot(d);
let t = if l2 > 0.0 { ((q - a).dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 };
(q - (a + d * t)).len()
})
.fold(f64::INFINITY, f64::min);
let uv: Vec<(f64, f64)> = pts.iter().map(|p| (p.x, p.y)).collect();
return if inside(&uv, (q.x, q.y)) { d } else { -d };
}
// Signed distance to the polyline, its end segments extended as lines.
let n = pts.len();
let mut best = (f64::INFINITY, 0.0);
@@ -119,6 +143,11 @@ struct Chain {
/// Mesh tolerance for tracing a face.
fn trace_tol(face: &mt::Face, size: f64) -> f64 {
let _ = face;
trace_tol_of(size)
}
/// Mesh tolerance for tracing on a body of this size.
fn trace_tol_of(size: f64) -> f64 {
(size * 2e-3).max(1e-4)
}
@@ -989,18 +1018,36 @@ fn fields(tool: &SplitTool) -> Result<Vec<Field>> {
let f = other.solid.face_iter().nth(*face).ok_or_else(|| KernelError::Invalid(format!("the tool body has no face {face}")))?;
vec![surface_field(&f.oriented_surface())]
}
SplitTool::Curves { plane, curves } => {
SplitTool::Curves { plane, curves, along } => {
let n = plane.normal();
// The sweep direction, turned to the plane's side (a direction along the plane sweeps
// nothing).
let along = match along {
None => None,
Some(d) => {
let d = d
.normalized()
.filter(|d| d.is_finite())
.ok_or_else(|| KernelError::Invalid("the projection direction must be a nonzero vector".into()))?;
if d.dot(n).abs() < 1e-6 {
return Err(KernelError::Invalid("the projection direction runs along the sketch plane".into()));
}
let d = if d.dot(n) < 0.0 { -d } else { d };
(d.cross(n).len() > 1e-12).then_some(d)
}
};
let sweep = along.unwrap_or(n);
let mut out = Vec::new();
for c in curves {
out.push(match c.as_slice() {
[Seg2::Line { a, b }] => {
let (wa, wb) = (plane.to_world(*a), plane.to_world(*b));
let n = plane.normal().cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?;
let n = sweep.cross(wb - wa).normalized().ok_or_else(|| KernelError::Invalid("a zero-length split line".into()))?;
Field::Plane { o: wa, n }
}
[Seg2::Arc { center, radius, .. }] if radius.is_finite() && *radius > 0.0 => Field::Cylinder {
[Seg2::Arc { center, radius, .. }] if along.is_none() && radius.is_finite() && *radius > 0.0 => Field::Cylinder {
o: plane.to_world(*center),
axis: plane.normal().unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?,
axis: n.unit().ok_or_else(|| KernelError::Invalid("a sketch plane with no normal".into()))?,
r: *radius,
out: 1.0,
},
@@ -1016,7 +1063,9 @@ fn fields(tool: &SplitTool) -> Result<Vec<Field>> {
if pts.len() < 2 || pts.iter().any(|p| !(p.x.is_finite() && p.y.is_finite())) || pts.len() > 1_000_000 {
return Err(KernelError::Invalid("split curves need finite segments".into()));
}
Field::Curve { plane: *plane, pts }
let span = pts.iter().fold(0.0f64, |m, p| m.max(p.len()));
let closed = pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| (*a - *b).len() <= span * 1e-9 + 1e-9);
Field::Curve { plane: *plane, pts, closed, along }
}
});
}
@@ -1193,6 +1242,62 @@ fn chain_loops(edges: &[mt::Edge]) -> Result<Vec<Vec<mt::Edge>>> {
Ok(out)
}
/// The regions of a body cut by a tool: for each face (in face order), the region it lies in,
/// and how many there are. Faces are in one region when they meet at an edge the tool does not
/// run along; an edge along the tool (a split line) parts them.
pub(crate) fn regions(split: &Body, tool: &SplitTool) -> Result<(Vec<usize>, usize)> {
let fields = fields(tool)?;
let tol = trace_tol_of(split.size());
let faces: Vec<&mt::Face> = split.solid.face_iter().collect();
let mut along_tool: HashMap<mt::EdgeID, bool> = HashMap::new();
let mut by_edge: HashMap<mt::EdgeID, Vec<usize>> = HashMap::new();
for (i, f) in faces.iter().enumerate() {
for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
by_edge.entry(e.id()).or_default().push(i);
along_tool.entry(e.id()).or_insert_with(|| {
let c = e.curve();
let (t0, t1) = c.range_tuple();
let at: Vec<Vec3> = [0.25, 0.5, 0.75].iter().map(|s| from_p3(c.subs(t0 + (t1 - t0) * s))).collect();
fields.iter().any(|g| at.iter().all(|p| g.eval(*p).abs() <= tol))
});
}
}
let mut region = vec![usize::MAX; faces.len()];
let mut count = 0;
for s in 0..faces.len() {
if region.get(s) != Some(&usize::MAX) {
continue;
}
if let Some(r) = region.get_mut(s) {
*r = count;
}
let mut stack = vec![s];
while let Some(i) = stack.pop() {
let Some(f) = faces.get(i) else { continue };
for e in f.boundaries().iter().flat_map(|w| w.edge_iter()) {
if along_tool.get(&e.id()).copied().unwrap_or(false) {
continue;
}
for &j in by_edge.get(&e.id()).into_iter().flatten() {
if let Some(r) = region.get_mut(j)
&& *r == usize::MAX
{
*r = count;
stack.push(j);
}
}
}
}
count += 1;
}
Ok((region, count))
}
/// How many fields a tool is (a sketch tool: one per curve).
pub(crate) fn field_count(tool: &SplitTool) -> Result<usize> {
Ok(fields(tool)?.len())
}
/// Faces grouped by shared edges (in face order).
fn components(faces: Vec<mt::Face>) -> Vec<Vec<mt::Face>> {
let n = faces.len();
@@ -1484,7 +1589,7 @@ mod tests {
let side = c.faces(0.01).unwrap().iter().position(|f| f.plane_normal.is_none()).unwrap();
// A horizontal line seen from the front (XZ sketch) at z = 5, swept along y.
let xz = Plane { y: Vec3::Z, ..Plane::XZ };
let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]] };
let tool = SplitTool::Curves { plane: xz, curves: vec![vec![Seg2::Line { a: Vec2::new(-20.0, 5.0), b: Vec2::new(20.0, 5.0) }]], along: None };
let s = split_faces(&c, &[side], &tool).unwrap();
let m = measure(&s).unwrap();
// (Measured on meshes: curved faces agree to about 1e-4.)
@@ -1566,7 +1671,7 @@ mod tests {
let t = top(&b, 30.0);
let arc = Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 6.0, start: 0.0, sweep: std::f64::consts::FRAC_PI_2 };
let plane = Plane { origin: Vec3::new(0.0, 0.0, 30.0), ..Plane::XY };
let tool = SplitTool::Curves { plane, curves: vec![vec![arc]] };
let tool = SplitTool::Curves { plane, curves: vec![vec![arc]], along: None };
let (s, map) = split_faces_with_map(&b, &[t], &tool).unwrap();
assert_eq!(map.len(), s.face_count());
assert_eq!(map.iter().filter(|o| **o == t).count(), 2);