Wave 463/509: kernel: Extend grows a surface of several faces face by face (and 3 more)
4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. -dd8867414jyviko: kernel: Extend grows a surface of several faces face by face -48a757827jyviko: kernel: Split Body by a face of a smooth sheet cuts with the whole sheet -3421a8ef0jyviko: Tests: a cylinder strip's run-offs are 100 pi + 100 to 1e-6, SMLib's exact area -20d5d8b13jyviko: kernel: an extension SMLib cannot make exact says so, naming the length asked Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
1 parent
cfd04c33fe
commit
24134d2ed0
8 files changed
+431
-55
No files matched your search
@@ -1296,8 +1296,8 @@ mod tests {
|
||||
/// along a straight edge, 20 long: each SMLib's G1 or G2 extension of the surface, so the
|
||||
/// strip stays one face. The distance is measured across the surface (the run-off's section
|
||||
/// is 5 long, whatever its curvature) and the strip is its section swept 20 along z, so each
|
||||
/// run-off adds 5 × 20: 10 · π/2 · 20 + 100.
|
||||
/// Undo, redo and reopening; the default saves nothing new.
|
||||
/// run-off adds 5 × 20: 10 · π/2 · 20 + 100 = 414.159265, exact to 1e-6. Areas are SMLib's,
|
||||
/// integrated on the exact surfaces. Undo, redo and reopening; the default saves nothing new.
|
||||
#[test]
|
||||
fn extend_a_cylinder_strip_every_way() {
|
||||
let pi = std::f64::consts::PI;
|
||||
@@ -1306,7 +1306,7 @@ mod tests {
|
||||
let top = [10.0 * (pi / 4.0).cos(), 10.0 * (pi / 4.0).sin(), 20.0];
|
||||
run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [top], "distance": "5 mm", "name": "Up"}));
|
||||
let want = 10.0 * pi / 2.0 * 25.0;
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); // (measured on meshes)
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip"));
|
||||
assert_eq!(s.world_state().unwrap().body("Strip").unwrap().body.face_count(), 1);
|
||||
let saved = s.doc.to_json();
|
||||
assert!(!saved.contains("\"mode\"") && !saved.contains("\"up_to\"") && !saved.contains("\"neighbours\""), "the default saves as before");
|
||||
@@ -1319,14 +1319,15 @@ mod tests {
|
||||
|
||||
run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [top], "up_to": {"origin": [0, 0, 30], "normal": [0, 0, 1]}}));
|
||||
let want = 10.0 * pi / 2.0 * 30.0;
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); // (measured on meshes)
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip"));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
let side = [0.0, 10.0, 10.0];
|
||||
for mode in ["tangent", "curvature"] {
|
||||
run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [side], "distance": 5, "mode": mode}));
|
||||
let want = 10.0 * pi / 2.0 * 20.0 + 5.0 * 20.0;
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{mode}: {} vs {want}", area(&s, "Strip")); // (measured on meshes)
|
||||
// SMLib's area, integrated on the exact surface to 1e-8: the run-off is exactly 5 long.
|
||||
assert!((area(&s, "Strip") - want).abs() < want * 1e-6, "{mode}: {} vs {want}", area(&s, "Strip"));
|
||||
let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
|
||||
assert!((area(&cold, "Strip") - area(&s, "Strip")).abs() < 1e-9, "{mode}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
+144
-10
@@ -33,7 +33,9 @@ use crate::{KernelError, Result, guard, record};
|
||||
pub enum SplitTool<'a> {
|
||||
/// A plane (unbounded).
|
||||
Plane(Plane),
|
||||
/// The surface of another body's face (`face` in that body's face order), extended.
|
||||
/// The surface of another body's face (`face` in that body's face order), extended. Split
|
||||
/// Body by a face of a surface body joined tangentially to others cuts with their smooth
|
||||
/// sheet as it is ([`split_body`]).
|
||||
Face { body: &'a Body, face: usize },
|
||||
/// 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.
|
||||
@@ -535,29 +537,51 @@ fn new_lines(split: &Body, h: &History) -> Result<Vec<Vec<Vec3>>> {
|
||||
}
|
||||
|
||||
/// Split a body into the parts on either side of a tool: a plane, another face's surface
|
||||
/// (extended), or one sketch line swept along its direction. Every part is closed with the piece
|
||||
/// (extended; a face of a surface body joined tangentially to others: their smooth sheet as it
|
||||
/// is, which must cross the body), or one sketch line swept along its direction. Every part is closed with the piece
|
||||
/// of the tool's surface inside the body; parts on the tool's back come first, each side's in
|
||||
/// face order. A body the tool misses comes back whole. Each part's history is over `[body]`:
|
||||
/// its faces the body's (or pieces of them), the section new.
|
||||
pub fn split_body(body: &Body, tool: &SplitTool) -> Result<Vec<Body>> {
|
||||
let _span = solidcraft_profile::span("kernel", "split_body");
|
||||
const NAME: &str = "split body";
|
||||
body.require_brep(NAME)?;
|
||||
body.require_brep(SPLIT_BODY)?;
|
||||
if let SplitTool::Face { body: sheet, face } = tool {
|
||||
let faces = smooth_sheet(sheet, *face)?;
|
||||
if faces.len() > 1 {
|
||||
return split_by_sheet(body, sheet, *face, &faces);
|
||||
}
|
||||
}
|
||||
let reach = reach_of(body);
|
||||
let groups = cutters(tool, &reach)?;
|
||||
let [group] = groups.as_slice() else { return Err(invalid("a body is split by a plane or a face")) };
|
||||
let [patch] = group.as_slice() else { return Err(invalid("a body is split by a plane, a face or one sketch line")) };
|
||||
let Some(surface) = smlib_tools(std::slice::from_ref(group), &reach)?.pop() else {
|
||||
return Ok(vec![crate::boolean_record::operand(body, 0, &record::counts(&[body]))]);
|
||||
};
|
||||
sliced(body, patch.flip, |sb| sb.split_body(&surface))
|
||||
}
|
||||
|
||||
const SPLIT_BODY: &str = "split body";
|
||||
|
||||
/// `body` cut in two by `cut` (SMLib's slice of its tagged copy, giving the parts behind and in
|
||||
/// front of the tool's surface), the parts in the tool's order of sides (`flip`: the tool's side
|
||||
/// is its surface's back), each solid of a part its own body. The body whole where the tool
|
||||
/// cuts nothing.
|
||||
fn sliced(
|
||||
body: &Body,
|
||||
flip: bool,
|
||||
cut: impl FnOnce(&solidcraft_smlib::Brep) -> solidcraft_smlib::Result<Option<(solidcraft_smlib::Brep, solidcraft_smlib::Brep)>>,
|
||||
) -> Result<Vec<Body>> {
|
||||
let counts = record::counts(&[body]);
|
||||
let whole = || crate::boolean_record::operand(body, 0, &counts);
|
||||
let Some(surface) = smlib_tools(std::slice::from_ref(group), &reach)?.pop() else { return Ok(vec![whole()]) };
|
||||
guard(NAME, || {
|
||||
let (sb, ob) = tagged(NAME, body)?;
|
||||
let Some((back, front)) = sb.split_body(&surface).map_err(|e| failed(NAME, e))? else { return Ok(vec![whole()]) };
|
||||
guard(SPLIT_BODY, || {
|
||||
let (sb, ob) = tagged(SPLIT_BODY, body)?;
|
||||
let Some((back, front)) = cut(&sb).map_err(|e| failed(SPLIT_BODY, e))? else { return Ok(vec![whole()]) };
|
||||
// SMLib's sides are the surface's; the tool's are the face's.
|
||||
let sides = if patch.flip { [front, back] } else { [back, front] };
|
||||
let sides = if flip { [front, back] } else { [back, front] };
|
||||
let (mut parts, mut cut) = (Vec::new(), false);
|
||||
for side in &sides {
|
||||
let (part, h) = brought_back(NAME, body, &ob, side)?;
|
||||
let (part, h) = brought_back(SPLIT_BODY, body, &ob, side)?;
|
||||
// The section comes from no face of the body.
|
||||
cut |= h.faces.iter().any(|f| f.origins.is_empty());
|
||||
let part = part.with_checked_history(Some(h), &counts);
|
||||
@@ -574,6 +598,61 @@ pub fn split_body(body: &Body, tool: &SplitTool) -> Result<Vec<Body>> {
|
||||
Ok(if cut { parts } else { vec![whole()] })
|
||||
})
|
||||
}
|
||||
|
||||
/// The faces of the surface body `sheet` joined to its face `face` tangentially, through edges
|
||||
/// along which the faces' normals agree all along ([`crate::tangent_edge`], within the one angle
|
||||
/// for smooth, [`crate::smooth_edges::ANGLE`]), and through those faces' tangent neighbours in
|
||||
/// turn: the smooth surface the face is part of, in face order. Only `face` for a closed body
|
||||
/// (a solid's face splits with its own surface extended).
|
||||
fn smooth_sheet(sheet: &Body, face: usize) -> Result<Vec<usize>> {
|
||||
sheet.require_brep("a split tool")?;
|
||||
let r = sheet.record();
|
||||
if r.faces.get(face).is_none() {
|
||||
return Err(invalid(format!("the tool body has no face {face}")));
|
||||
}
|
||||
if !r.edges.iter().any(|e| e.uses.len() == 1) {
|
||||
return Ok(vec![face]);
|
||||
}
|
||||
let sides = crate::surfaces::face_sides(r);
|
||||
let sign = |f: usize| sides.get(f).map(|forward| if *forward { 1.0 } else { -1.0 });
|
||||
let mut joined = std::collections::BTreeSet::from([face]);
|
||||
let mut todo = vec![face];
|
||||
while let Some(f) = todo.pop() {
|
||||
let Some(this) = r.faces.get(f) else { continue };
|
||||
for l in &this.loops {
|
||||
let brep::Loop::Edges { edges } = l else { continue };
|
||||
for u in edges {
|
||||
let e = u.edge as usize;
|
||||
let Some([a, b]) = r.edges.get(e).map(|edge| edge.uses.as_slice()) else { continue };
|
||||
let g = if a.face as usize == f { b.face } else { a.face } as usize;
|
||||
if g == f || joined.contains(&g) {
|
||||
continue;
|
||||
}
|
||||
if crate::tangent_edge::tangent_all_along(r, sign, e, crate::smooth_edges::ANGLE)? {
|
||||
joined.insert(g);
|
||||
todo.push(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(joined.into_iter().collect())
|
||||
}
|
||||
|
||||
/// `body` cut in two by the faces `faces` of the surface body `sheet` as they are (a smooth sheet
|
||||
/// of several faces, bounded where they end), its sides those of `sheet`'s face `face`: SMLib's
|
||||
/// slice by the sheet ([`solidcraft_smlib::Brep::split_body_by_sheet`]). A sheet that does not
|
||||
/// cross the body cuts nothing.
|
||||
fn split_by_sheet(body: &Body, sheet: &Body, face: usize, faces: &[usize]) -> Result<Vec<Body>> {
|
||||
let picked: Vec<(usize, bool)> = faces.iter().map(|f| (*f, false)).collect();
|
||||
let c = crate::surfaces::Parts::of(sheet.record(), &picked)?.canonical()?;
|
||||
let at = c.faces.iter().position(|p| faces.get(*p) == Some(&face)).ok_or_else(|| failed(SPLIT_BODY, "the tool face is not in its sheet"))?;
|
||||
let (tool, order) = crate::native::smlib_record_ordered(&c.brep)?;
|
||||
let order = order.ok_or_else(|| failed(SPLIT_BODY, "SMLib numbers the tool sheet's faces unlike its record"))?;
|
||||
// SMLib's face `i` is the record's `order.faces[i]` (the same where none is given).
|
||||
let k = if order.faces.is_empty() { Some(at) } else { order.faces.iter().position(|f| *f == at) };
|
||||
let k = k.ok_or_else(|| failed(SPLIT_BODY, "the tool face has no SMLib face"))?;
|
||||
sliced(body, !sheet.face_forward(face), |sb| sb.split_body_by_sheet(&tool, k))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -700,6 +779,61 @@ mod tests {
|
||||
assert!(tops.iter().all(|a| rel(*a, half) < 1e-3), "{tops:?}");
|
||||
}
|
||||
|
||||
/// Cubic spans of a spline, each with its x control points evenly spaced (so x runs linearly
|
||||
/// along it and y is a cubic in x), meeting tangent, extruded from z = -5 to 15.
|
||||
fn spans(ys: &[[f64; 4]]) -> Body {
|
||||
let chain = ys
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, y)| {
|
||||
let x0 = -3.0 + 6.0 * i as f64;
|
||||
let p = |k: usize| Vec2::new(x0 + 2.0 * k as f64, y[k]);
|
||||
Seg2::Cubic { p0: p(0), p1: p(1), p2: p(2), p3: p(3) }
|
||||
})
|
||||
.collect();
|
||||
crate::extrude_sheet(&Plane::XY, &[chain], -5.0, 15.0).unwrap()
|
||||
}
|
||||
|
||||
/// The face of `b` farthest to -x (by its centroid).
|
||||
fn leftmost(b: &Body) -> usize {
|
||||
let faces = b.faces(0.01).unwrap();
|
||||
(0..faces.len()).min_by(|i, j| faces[*i].centroid.x.total_cmp(&faces[*j].centroid.x)).unwrap()
|
||||
}
|
||||
|
||||
/// Split Body by a face of a smooth sheet cuts with the whole sheet (#3830): three spans
|
||||
/// meeting tangent cross the cube 0…10, the face of the first alone does not. The part
|
||||
/// under the spline is 10 ∫ y dx over x 0…10 (y a cubic in x on each span: Gauss–Legendre at
|
||||
/// three points is exact). Two spans that end inside the cube cut nothing.
|
||||
#[test]
|
||||
fn a_face_of_a_smooth_sheet_splits_with_the_whole_sheet() {
|
||||
let ys = [[5.0, 5.0, 4.0, 4.0], [4.0, 4.0, 6.0, 6.0], [6.0, 6.0, 5.0, 5.0]];
|
||||
let bern = |y: &[f64; 4], t: f64| {
|
||||
let s = 1.0 - t;
|
||||
y[0] * s * s * s + 3.0 * y[1] * s * s * t + 3.0 * y[2] * s * t * t + y[3] * t * t * t
|
||||
};
|
||||
// ∫ y dx over the span's t0…t1 (dx = 6 dt).
|
||||
let integral = |y: &[f64; 4], t0: f64, t1: f64| {
|
||||
let (m, h) = (0.5 * (t0 + t1), 0.5 * (t1 - t0));
|
||||
let g = (0.6f64).sqrt();
|
||||
6.0 * h * (5.0 * bern(y, m - h * g) + 8.0 * bern(y, m) + 5.0 * bern(y, m + h * g)) / 9.0
|
||||
};
|
||||
let under = 10.0 * (integral(&ys[0], 0.5, 1.0) + integral(&ys[1], 0.0, 1.0) + integral(&ys[2], 0.0, 1.0 / 6.0));
|
||||
let sheet = spans(&ys);
|
||||
assert_eq!(sheet.face_count(), 3);
|
||||
let first = leftmost(&sheet);
|
||||
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();
|
||||
let parts = split_body(&cube, &SplitTool::Face { body: &sheet, face: first }).unwrap();
|
||||
let v = volumes(&parts);
|
||||
assert_eq!(v.len(), 2, "{v:?}");
|
||||
assert!(rel(v[0], under) < 1e-6 && rel(v[1], 1000.0 - under) < 1e-6, "{v:?} vs {under}");
|
||||
|
||||
let short = spans(&ys[..2]);
|
||||
let first = leftmost(&short);
|
||||
let nicked = split_body(&cube, &SplitTool::Face { body: &short, face: first }).unwrap();
|
||||
let info: Vec<_> = nicked.iter().map(|b| (measure(b).unwrap().volume, b.face_count(), b.lumps().unwrap().len())).collect();
|
||||
assert_eq!(nicked.len(), 1, "{info:?}");
|
||||
}
|
||||
|
||||
fn volumes(parts: &[Body]) -> Vec<f64> {
|
||||
let mut v: Vec<f64> = parts.iter().map(|b| measure(b).unwrap().volume).collect();
|
||||
v.sort_by(f64::total_cmp);
|
||||
|
||||
@@ -11,7 +11,15 @@
|
||||
//! The face is extended where it is its surface's whole parameter box and the edge is a whole
|
||||
//! side of it: the box grows past that side, the sides next to it continue along the surface's
|
||||
//! parameter lines, and the face stays one face on the extended surface. Edges picked on two
|
||||
//! sides grow the box on both, meeting at the box's corner. Up to a target, the face is extended
|
||||
//! sides grow the box on both, meeting at the box's corner.
|
||||
//!
|
||||
//! A body of several faces grows face by face, each extended alone as above and the faces sewn
|
||||
//! back together. A side that lengthens is shared with the face next to it: that face grows too,
|
||||
//! past its edge continuing the picked one, when the two meet tangent along the side (the faces
|
||||
//! of one smooth surface, a spline's spans extruded, grow as one); across a crease it grows only
|
||||
//! when that edge is picked as well, and otherwise the extension is refused (it would run past
|
||||
//! the face beside it). The lengthened sides must meet again: faces whose extensions part are
|
||||
//! refused. Up to a target, the face is extended
|
||||
//! past it and trimmed back where the target meets it ([`crate::trim_keep`]: SMLib's exact
|
||||
//! intersection). Back to the bounds is the face untrimmed to its surface's box
|
||||
//! ([`crate::untrim`]). A plane's straight edges pushed out with their neighbours lengthened
|
||||
@@ -19,7 +27,9 @@
|
||||
//!
|
||||
//! Refused rather than built: edges between two faces, edges of holes, and (not supported yet)
|
||||
//! an edge that is not a whole side of its surface's box (a trimmed edge, whose extension is no
|
||||
//! curve SMLib holds exactly), or a body of more than one face.
|
||||
//! curve SMLib holds exactly).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::brep::{self, eval::CurveEval};
|
||||
@@ -29,7 +39,8 @@ use crate::body::Body;
|
||||
use crate::history::{Change, FaceOrigin};
|
||||
use crate::native::{body_from_smlib_ordered, smlib_body_ordered};
|
||||
use crate::surface_trim::TrimKeep;
|
||||
use crate::{KernelError, Result, SplitTool};
|
||||
use crate::surfaces::Parts;
|
||||
use crate::{KernelError, Result, SplitTool, record};
|
||||
|
||||
/// Most edge picks.
|
||||
const MAX_PICKS: usize = 10_000;
|
||||
@@ -104,11 +115,14 @@ pub fn extend_surface(body: &Body, at: &[Vec3], opts: &ExtendOptions) -> Result<
|
||||
{
|
||||
return crate::surfaces::extend(body, at, d);
|
||||
}
|
||||
let faces = picked_faces(&record, body.size(), at)?;
|
||||
let picked = picked_edges(&record, body.size(), at)?;
|
||||
match opts.limit {
|
||||
ExtendLimit::Bounds => back_to_bounds(body, &faces),
|
||||
ExtendLimit::Distance(d) => continued(body, at, d, opts.mode),
|
||||
ExtendLimit::UpTo(tool) => up_to(body, at, tool, opts.mode),
|
||||
ExtendLimit::Bounds => {
|
||||
let faces: BTreeSet<usize> = picked.iter().map(|(_, f)| *f).collect();
|
||||
back_to_bounds(body, &faces.into_iter().collect::<Vec<_>>())
|
||||
}
|
||||
ExtendLimit::Distance(d) => continued(body, at, &picked, d, opts.mode).map(|(out, _)| out),
|
||||
ExtendLimit::UpTo(tool) => up_to(body, at, &picked, tool, opts.mode),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,10 +134,10 @@ fn plain_planar(record: &brep::Brep) -> bool {
|
||||
&& edges.iter().all(|u| record.edges.get(u.edge as usize).is_some_and(|e| matches!(e.curve, brep::Curve::Line { .. })))
|
||||
}
|
||||
|
||||
/// The faces (in face order, each once) of the boundary edges the points pick: for each point,
|
||||
/// the record edge nearest it (by samples along each edge), within a twentieth of the body's
|
||||
/// size. An edge two faces share, or one of a hole, is refused.
|
||||
fn picked_faces(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result<Vec<usize>> {
|
||||
/// The boundary edges the points pick, each with its face: for each point, the record edge
|
||||
/// nearest it (by samples along each edge), within a twentieth of the body's size. An edge two
|
||||
/// faces share, or one of a hole, is refused.
|
||||
fn picked_edges(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result<Vec<(usize, usize)>> {
|
||||
let curves: Vec<CurveEval> = record
|
||||
.edges
|
||||
.iter()
|
||||
@@ -131,7 +145,7 @@ fn picked_faces(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result<Vec<usize
|
||||
.map(|(i, e)| CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("extend: edge {i}'s curve: {err}"))))
|
||||
.collect::<Result<_>>()?;
|
||||
let reach = size * 0.05 + 1e-6;
|
||||
let mut faces = Vec::new();
|
||||
let mut picked = Vec::with_capacity(at.len());
|
||||
for p in at {
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (i, (e, c)) in record.edges.iter().zip(&curves).enumerate() {
|
||||
@@ -144,8 +158,8 @@ fn picked_faces(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result<Vec<usize
|
||||
}
|
||||
}
|
||||
}
|
||||
let edge = match best {
|
||||
Some((d, i)) if d <= reach => record.edges.get(i),
|
||||
let (index, edge) = match best {
|
||||
Some((d, i)) if d <= reach => record.edges.get(i).map(|e| (i, e)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?;
|
||||
@@ -156,23 +170,163 @@ fn picked_faces(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result<Vec<usize
|
||||
if only.r#loop != 0 {
|
||||
return Err(KernelError::Invalid("not supported yet: extending an edge of a hole (Untrim takes holes away)".into()));
|
||||
}
|
||||
let face = only.face as usize;
|
||||
if !faces.contains(&face) {
|
||||
faces.push(face);
|
||||
picked.push((index, only.face as usize));
|
||||
}
|
||||
Ok(picked)
|
||||
}
|
||||
|
||||
/// The faces of `body` continued `distance` past the picked edges (`at`, which `picked` names
|
||||
/// with their faces), as `mode` says, and the faces that grew. One face is extended by SMLib
|
||||
/// ([`one_face`]); a body of several grows face by face ([`grown`] says which past which edges),
|
||||
/// each face extended alone and the faces sewn back together, each the face it was. Faces whose
|
||||
/// lengthened sides part (no longer one edge) are refused.
|
||||
fn continued(body: &Body, at: &[Vec3], picked: &[(usize, usize)], distance: f64, mode: ExtendMode) -> Result<(Body, Vec<usize>)> {
|
||||
if body.face_count() == 1 {
|
||||
return Ok((one_face(body, at, distance, mode)?, vec![0]));
|
||||
}
|
||||
let r = body.record();
|
||||
let grow = grown(r, picked)?;
|
||||
let mut pieces = Vec::with_capacity(grow.len() + 1);
|
||||
for (&f, edges) in &grow {
|
||||
let alone = crate::surfaces::taken(body, r, &[(f, false)])?;
|
||||
let points = edges.iter().map(|e| edge_middle(r, *e)).collect::<Result<Vec<_>>>()?;
|
||||
let longer = one_face(&alone, &points, distance, mode)?;
|
||||
pieces.push((longer.record().clone(), vec![record::from_face(0, f, Change::Modified)]));
|
||||
}
|
||||
let rest: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !grow.contains_key(f)).map(|f| (f, false)).collect();
|
||||
if !rest.is_empty() {
|
||||
let c = Parts::of(r, &rest)?.canonical()?;
|
||||
let kept = c
|
||||
.faces
|
||||
.iter()
|
||||
.map(|p| rest.get(*p).map(|(f, _)| record::from_face(0, *f, Change::Kept)))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| failed("sew", "a face of the rest of the body is missing"))?;
|
||||
pieces.push((c.brep, kept));
|
||||
}
|
||||
let out = crate::surfaces::sheet_of(pieces, true, &[body])?;
|
||||
if (out.face_count(), out.edge_count()) != (body.face_count(), body.edge_count()) {
|
||||
return Err(KernelError::Invalid(
|
||||
"the extended faces part along the sides they lengthen: their extensions don't meet again (extend each face on its own)".into(),
|
||||
));
|
||||
}
|
||||
Ok((out, grow.into_keys().collect()))
|
||||
}
|
||||
|
||||
/// The boundary edges each face grows past (by face): the `picked` ones (edge, face), and those
|
||||
/// that continue a grown edge across a side it lengthens onto a face meeting its own tangent
|
||||
/// there. A side lengthening along a crease onto a face that does not grow past the edge
|
||||
/// continuing the grown one is refused: the extension would run past that face.
|
||||
fn grown(r: &brep::Brep, picked: &[(usize, usize)]) -> Result<BTreeMap<usize, BTreeSet<usize>>> {
|
||||
let sides = crate::surfaces::face_sides(r);
|
||||
let sign = |f: usize| sides.get(f).map(|forward| if *forward { 1.0 } else { -1.0 });
|
||||
let mut grow: BTreeMap<usize, BTreeSet<usize>> = BTreeMap::new();
|
||||
let mut todo = picked.to_vec();
|
||||
// (face, its edge that must grow, the creased side between): checked once all have grown.
|
||||
let mut creased = Vec::new();
|
||||
let mut count = 0usize;
|
||||
while let Some((e, f)) = todo.pop() {
|
||||
if !grow.entry(f).or_default().insert(e) {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
if count > MAX_PICKS {
|
||||
return Err(KernelError::Invalid("too many edges to extend".into()));
|
||||
}
|
||||
for (side, at) in next_to(r, f, e)? {
|
||||
let uses = &record_edge(r, side)?.uses;
|
||||
let other = match uses.as_slice() {
|
||||
[_] => continue,
|
||||
[a, b] => [a.face, b.face].into_iter().map(|g| g as usize).find(|g| *g != f),
|
||||
_ => return Err(KernelError::Invalid(format!("not supported yet: extending along edge {side}, which more than two faces share"))),
|
||||
};
|
||||
// A seam: the face lengthens along it on both sides at once.
|
||||
let Some(g) = other else { continue };
|
||||
let cont = continuing(r, g, side, at)?;
|
||||
if !matches!(record_edge(r, cont)?.uses.as_slice(), [only] if only.r#loop == 0) {
|
||||
return Err(KernelError::Invalid(format!(
|
||||
"not supported yet: extending past edge {e}, whose side {side} runs on into the inside of the face next to it"
|
||||
)));
|
||||
}
|
||||
if crate::tangent_edge::tangent_all_along(r, sign, side, crate::smooth_edges::ANGLE)? {
|
||||
todo.push((cont, g));
|
||||
} else {
|
||||
creased.push((g, cont, side));
|
||||
}
|
||||
}
|
||||
}
|
||||
faces.sort_unstable();
|
||||
Ok(faces)
|
||||
for (g, cont, side) in creased {
|
||||
if !grow.get(&g).is_some_and(|edges| edges.contains(&cont)) {
|
||||
return Err(KernelError::Invalid(format!(
|
||||
"extending the edge lengthens its face along edge {side}, a crease with the face next to it: pick that face's edge {cont} too"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(grow)
|
||||
}
|
||||
|
||||
fn record_edge(r: &brep::Brep, e: usize) -> Result<&brep::Edge> {
|
||||
r.edges.get(e).ok_or_else(|| failed("topology", format!("no edge {e}")))
|
||||
}
|
||||
|
||||
/// The outer loop of face `f` and where edge `e` is in it.
|
||||
fn in_outer_loop(r: &brep::Brep, f: usize, e: usize) -> Result<(&[brep::OrientedEdge], usize)> {
|
||||
let face = r.faces.get(f).ok_or_else(|| failed("topology", format!("no face {f}")))?;
|
||||
let Some(brep::Loop::Edges { edges }) = face.loops.first() else { return Err(failed("topology", format!("face {f} has no edge loop"))) };
|
||||
let i = edges.iter().position(|u| u.edge as usize == e).ok_or_else(|| failed("topology", format!("edge {e} is not on face {f}'s outer loop")))?;
|
||||
Ok((edges, i))
|
||||
}
|
||||
|
||||
/// The vertices edge use `u` runs from and to round its loop.
|
||||
fn ends(r: &brep::Brep, u: &brep::OrientedEdge) -> Result<[u32; 2]> {
|
||||
let [a, b] = record_edge(r, u.edge as usize)?.vertices;
|
||||
Ok(if u.forward { [a, b] } else { [b, a] })
|
||||
}
|
||||
|
||||
/// The sides of face `f` next to its edge `e` round its outer loop, each with the vertex it
|
||||
/// shares with `e`: the edges an extension past `e` lengthens.
|
||||
fn next_to(r: &brep::Brep, f: usize, e: usize) -> Result<Vec<(usize, u32)>> {
|
||||
let (edges, i) = in_outer_loop(r, f, e)?;
|
||||
let n = edges.len();
|
||||
let (Some(prev), Some(this), Some(next)) = (edges.get((i + n - 1) % n), edges.get(i), edges.get((i + 1) % n)) else { return Ok(Vec::new()) };
|
||||
let [from, to] = ends(r, this)?;
|
||||
let mut out = Vec::with_capacity(2);
|
||||
for (u, v) in [(prev, from), (next, to)] {
|
||||
if u.edge as usize != e && !out.iter().any(|(s, _)| *s == u.edge as usize) {
|
||||
out.push((u.edge as usize, v));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The edge of face `g`'s outer loop that meets its side `side` at vertex `at`.
|
||||
fn continuing(r: &brep::Brep, g: usize, side: usize, at: u32) -> Result<usize> {
|
||||
let (edges, i) = in_outer_loop(r, g, side)?;
|
||||
let n = edges.len();
|
||||
let this = edges.get(i).ok_or_else(|| failed("topology", "a loop position"))?;
|
||||
let [from, to] = ends(r, this)?;
|
||||
let k = if from == at {
|
||||
(i + n - 1) % n
|
||||
} else if to == at {
|
||||
(i + 1) % n
|
||||
} else {
|
||||
return Err(failed("topology", format!("edge {side} does not end at vertex {at}")));
|
||||
};
|
||||
match edges.get(k) {
|
||||
Some(u) if u.edge as usize != side => Ok(u.edge as usize),
|
||||
_ => Err(KernelError::Invalid(format!("not supported yet: extending along edge {side}, the only side of the face next to it"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The point halfway along record edge `e`.
|
||||
fn edge_middle(r: &brep::Brep, e: usize) -> Result<Vec3> {
|
||||
let edge = record_edge(r, e)?;
|
||||
let c = CurveEval::new(edge.parameters()).map_err(|err| failed("edge", format!("edge {e}'s curve: {err}")))?;
|
||||
c.point(0.5 * (edge.interval[0] + edge.interval[1])).ok_or_else(|| failed("edge", format!("edge {e} has no middle")))
|
||||
}
|
||||
|
||||
/// The one face of `body` continued `distance` past each picked edge, as `mode` says.
|
||||
fn continued(body: &Body, at: &[Vec3], distance: f64, mode: ExtendMode) -> Result<Body> {
|
||||
if body.face_count() != 1 {
|
||||
return Err(KernelError::Invalid(format!(
|
||||
"not supported yet: extending a surface of more than one face (this one has {})",
|
||||
body.face_count()
|
||||
)));
|
||||
}
|
||||
fn one_face(body: &Body, at: &[Vec3], distance: f64, mode: ExtendMode) -> Result<Body> {
|
||||
let how = match mode {
|
||||
ExtendMode::Natural => Continuation::Natural,
|
||||
ExtendMode::Tangent => Continuation::Tangent,
|
||||
@@ -186,7 +340,9 @@ fn continued(body: &Body, at: &[Vec3], distance: f64, mode: ExtendMode) -> Resul
|
||||
solidcraft_smlib::Error::Unsupported => KernelError::Invalid(
|
||||
"not supported yet: extending an edge that is not a whole side of its surface's parameter box (a trimmed edge)".into(),
|
||||
),
|
||||
solidcraft_smlib::Error::NotExact => KernelError::Invalid("the extension would run past a pole of its surface or wrap round it".into()),
|
||||
solidcraft_smlib::Error::NotExact => KernelError::Invalid(format!(
|
||||
"the surface cannot be extended exactly {distance} mm there: the extension would run past a pole of its surface, wrap round it, or not reach that length"
|
||||
)),
|
||||
solidcraft_smlib::Error::NoMatch { .. } => KernelError::Invalid(format!("no edge at {p:?}")),
|
||||
e => failed("extend", e),
|
||||
})?;
|
||||
@@ -207,12 +363,12 @@ fn continued(body: &Body, at: &[Vec3], distance: f64, mode: ExtendMode) -> Resul
|
||||
Ok(out.with_checked_history(history, &crate::record::counts(&[body])))
|
||||
}
|
||||
|
||||
/// The face extended past the target and trimmed back where the target meets it, keeping the
|
||||
/// piece the face itself lies in.
|
||||
fn up_to(body: &Body, at: &[Vec3], tool: &SplitTool, mode: ExtendMode) -> Result<Body> {
|
||||
let inside = crate::surface_untrim::face_point(body, 0)?;
|
||||
let long = continued(body, at, body.size().max(1e-6) * REACH, mode)?;
|
||||
let cut = crate::trim_keep(&long, tool, TrimKeep::Regions(&[inside]))?;
|
||||
/// The faces extended past the target and trimmed back where the target meets them, keeping the
|
||||
/// pieces the faces themselves lie in.
|
||||
fn up_to(body: &Body, at: &[Vec3], picked: &[(usize, usize)], tool: &SplitTool, mode: ExtendMode) -> Result<Body> {
|
||||
let (long, faces) = continued(body, at, picked, body.size().max(1e-6) * REACH, mode)?;
|
||||
let inside = faces.iter().map(|f| crate::surface_untrim::face_point(body, *f)).collect::<Result<Vec<_>>>()?;
|
||||
let cut = crate::trim_keep(&long, tool, TrimKeep::Regions(&inside))?;
|
||||
Ok(crate::record::after(cut, &long, &crate::record::counts(&[body])))
|
||||
}
|
||||
|
||||
@@ -411,6 +567,57 @@ mod tests {
|
||||
assert!((measure(&back).unwrap().bbox.max.z - 15.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Three cubic spans of a spline meeting tangent, extruded 0…20 along Z: a sheet of three
|
||||
/// faces, as a fit-point spline's surface is (#3830).
|
||||
fn spline_spans() -> Body {
|
||||
let v = Vec2::new;
|
||||
let c = |p0, p1, p2, p3| Seg2::Cubic { p0, p1, p2, p3 };
|
||||
let chain = vec![
|
||||
c(v(0.0, 0.0), v(5.0, 0.0), v(10.0, 5.0), v(15.0, 5.0)),
|
||||
c(v(15.0, 5.0), v(20.0, 5.0), v(25.0, 0.0), v(30.0, 0.0)),
|
||||
c(v(30.0, 0.0), v(35.0, 0.0), v(40.0, 5.0), v(45.0, 5.0)),
|
||||
];
|
||||
crate::extrude_sheet(&Plane::XY, &[chain], 0.0, 20.0).unwrap()
|
||||
}
|
||||
|
||||
/// A sheet of several faces grows face by face (#3830): its end edge (the last span's
|
||||
/// generator) 10 further, the last span continued, 10 · 20 more; the middle span's top edge
|
||||
/// 5 up takes its tangent neighbours with it, the whole spline 25 tall. The faces stay three,
|
||||
/// sewn as before, each the face it was.
|
||||
#[test]
|
||||
fn a_sheet_of_tangent_faces_grows_face_by_face() {
|
||||
let s = spline_spans();
|
||||
assert_eq!(s.face_count(), 3);
|
||||
let base = area(&s);
|
||||
let end = extend_surface(&s, &[Vec3::new(45.0, 5.0, 10.0)], &natural(10.0)).unwrap();
|
||||
assert!(rel(area(&end), base + 200.0) < 1e-4, "{} vs {}", area(&end), base + 200.0); // (measured on meshes)
|
||||
assert_eq!((end.face_count(), edges(&end)), (3, edges(&s)));
|
||||
assert!(measure(&end).unwrap().bbox.max.x > 50.0, "{:?}", measure(&end).unwrap().bbox);
|
||||
let h = end.history().unwrap();
|
||||
let changes: Vec<Change> = h.faces.iter().map(|f| f.change).collect();
|
||||
assert_eq!(changes.iter().filter(|c| **c == Change::Modified).count(), 1, "{changes:?}");
|
||||
|
||||
let up = extend_surface(&s, &[Vec3::new(22.5, 2.5, 20.0)], &natural(5.0)).unwrap();
|
||||
assert!(rel(area(&up), base * 25.0 / 20.0) < 1e-4, "{} vs {}", area(&up), base * 25.0 / 20.0); // (measured on meshes)
|
||||
assert_eq!((up.face_count(), edges(&up)), (3, edges(&s)));
|
||||
assert!((measure(&up).unwrap().bbox.max.z - 25.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Across a crease the face next door grows only when its edge is picked too: an L of two
|
||||
/// planes, one top edge refused (it would run past the other wall), both 5 up, 25 · 20.
|
||||
#[test]
|
||||
fn a_crease_grows_only_when_both_edges_are_picked() {
|
||||
let l =
|
||||
vec![Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(10.0, 0.0) }, Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 10.0) }];
|
||||
let s = crate::extrude_sheet(&Plane::XY, &[l], 0.0, 20.0).unwrap();
|
||||
assert_eq!(s.face_count(), 2);
|
||||
let e = extend_surface(&s, &[Vec3::new(5.0, 0.0, 20.0)], &natural(5.0)).unwrap_err();
|
||||
assert!(e.to_string().contains("crease"), "{e}");
|
||||
let both = extend_surface(&s, &[Vec3::new(5.0, 0.0, 20.0), Vec3::new(10.0, 5.0, 20.0)], &natural(5.0)).unwrap();
|
||||
assert!(rel(area(&both), 500.0) < 1e-9, "{}", area(&both));
|
||||
assert_eq!((both.face_count(), edges(&both)), (2, edges(&s)));
|
||||
}
|
||||
|
||||
/// Hostile and unsupported requests are refused, never panic.
|
||||
#[test]
|
||||
fn hostile_requests_are_refused() {
|
||||
|
||||
@@ -236,7 +236,7 @@ impl Parts {
|
||||
|
||||
/// Whether each face of `r` is used along its surface's natural normal (by its first oriented
|
||||
/// face).
|
||||
fn face_sides(r: &Brep) -> Vec<bool> {
|
||||
pub(crate) fn face_sides(r: &Brep) -> Vec<bool> {
|
||||
let mut side = vec![None; r.faces.len()];
|
||||
for s in &r.shells {
|
||||
if let b::Shell::Faces { faces, .. } = s {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The split block of `capi/include/smlib.h` (`smlib_split_faces`, `smlib_split_body`; the
|
||||
//! The split block of `capi/include/smlib.h` (`smlib_split_faces`, `smlib_split_body`,
|
||||
//! `smlib_split_body_by_sheet`; the
|
||||
//! fork's `capi/src/smlib_split.cpp`), declared by hand. Part of the FFI boundary, like its
|
||||
//! parent: called only through [`crate::split`].
|
||||
|
||||
@@ -27,6 +28,7 @@ unsafe extern "C" {
|
||||
made: *mut i64,
|
||||
) -> i32;
|
||||
fn smlib_split_body(body: *const RawBrep, tool: *const RawSurface, back: *mut *mut RawBrep, front: *mut *mut RawBrep) -> i32;
|
||||
fn smlib_split_body_by_sheet(body: *const RawBrep, sheet: *const RawBrep, face: i64, back: *mut *mut RawBrep, front: *mut *mut RawBrep) -> i32;
|
||||
}
|
||||
|
||||
/// `body` with `faces` cut by `tools` in turn, and per face how many faces it became besides
|
||||
@@ -48,10 +50,23 @@ pub fn split_faces(body: &Handle, faces: &[i64], tools: &[&SurfaceHandle]) -> Re
|
||||
/// The parts of `body` behind and in front of `tool`.
|
||||
#[cfg(feature = "native")]
|
||||
pub fn split_body(body: &Handle, tool: &SurfaceHandle) -> Result<(Handle, Handle), i32> {
|
||||
// SAFETY: the handles are live; the out-pointers are written only on success.
|
||||
two_parts(|back, front| unsafe { smlib_split_body(body.raw(), tool.raw(), back, front) })
|
||||
}
|
||||
|
||||
/// The parts of `body` behind and in front of `sheet`, its sides those of its face `face`.
|
||||
#[cfg(feature = "native")]
|
||||
pub fn split_body_by_sheet(body: &Handle, sheet: &Handle, face: i64) -> Result<(Handle, Handle), i32> {
|
||||
// SAFETY: the handles are live; the out-pointers are written only on success.
|
||||
two_parts(|back, front| unsafe { smlib_split_body_by_sheet(body.raw(), sheet.raw(), face, back, front) })
|
||||
}
|
||||
|
||||
/// The two bodies a call writing a back and a front part gives, owned.
|
||||
#[cfg(feature = "native")]
|
||||
fn two_parts(call: impl FnOnce(*mut *mut RawBrep, *mut *mut RawBrep) -> i32) -> Result<(Handle, Handle), i32> {
|
||||
let mut back: *mut RawBrep = std::ptr::null_mut();
|
||||
let mut front: *mut RawBrep = std::ptr::null_mut();
|
||||
// SAFETY: the handles are live; the out-pointers are written only on success.
|
||||
let s = unsafe { smlib_split_body(body.raw(), tool.raw(), &mut back, &mut front) };
|
||||
let s = call(&mut back, &mut front);
|
||||
let (b, f) = (std::ptr::NonNull::new(back), std::ptr::NonNull::new(front));
|
||||
match (s, b, f) {
|
||||
(OK, Some(b), Some(f)) => Ok((Handle(b), Handle(f))),
|
||||
@@ -74,3 +89,8 @@ pub fn split_faces(_: &Handle, _: &[i64], _: &[&SurfaceHandle]) -> Result<(Handl
|
||||
pub fn split_body(_: &Handle, _: &SurfaceHandle) -> Result<(Handle, Handle), i32> {
|
||||
Err(NOT_BUILT)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn split_body_by_sheet(_: &Handle, _: &Handle, _: i64) -> Result<(Handle, Handle), i32> {
|
||||
Err(NOT_BUILT)
|
||||
}
|
||||
@@ -37,4 +37,19 @@ impl Brep {
|
||||
Err(s) => Err(error(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifold solid `self` cut in two by the sheet `sheet` as it is (its faces joined edge
|
||||
/// to edge; it must cross the body to cut it), as [`Brep::split_body`] cuts it: its faces'
|
||||
/// surfaces turned to agree with face `face`'s (in SMLib's face order), the part behind that
|
||||
/// normal and the part in front. A `sheet` that is no sheet, or a `face` it does not have, is
|
||||
/// [`Error::Argument`].
|
||||
pub fn split_body_by_sheet(&self, sheet: &Brep, face: usize) -> Result<Option<(Brep, Brep)>> {
|
||||
init()?;
|
||||
let face = i64::try_from(face).map_err(|_| Error::Argument)?;
|
||||
match ffi::split::split_body_by_sheet(&self.0, &sheet.0, face) {
|
||||
Ok((b, f)) => Ok(Some((Brep(b), Brep(f)))),
|
||||
Err(ffi::ops::ERR_NO_CUT) => Ok(None),
|
||||
Err(s) => Err(error(s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
],
|
||||
"what": "split a thin-walled cup (shell of a d30 cylinder) with a surface body: an extruded spline surface, extended at both ends",
|
||||
"source": "analytic",
|
||||
"method": "cup = cylinder r15 h30 shelled 1 mm inward with its top removed: V = pi*15^2*30 - pi*14^2*29 = 3349.04. The surface crosses the whole cup from above its rim to below its floor, so it splits the cup in two; splitting only divides material: two valid bodies whose volumes add up to 3349.04",
|
||||
"body_count": 2,
|
||||
"method": "cup = cylinder r15 h30 shelled 1 mm inward with its top removed: V = pi*15^2*30 - pi*14^2*29 = 3349.04. The surface crosses the whole cup from above its rim to below its floor, so it splits the cup in two; splitting only divides material: two valid bodies whose volumes add up to 3349.04; the surface body that cut it stays, a third body",
|
||||
"body_count": 3,
|
||||
"volume_mm3": 3348.938
|
||||
}
|
||||
@@ -3,4 +3,3 @@
|
||||
# and on a listed case that passes: a fix removes its line in the same pull request.
|
||||
# Baseline: develop 5ada4fc8a with SMLib 90aabff (the run on 60b1c6a, aarch64 Linux).
|
||||
3604-cut-with-g2-swept-tool-along-projected-edge step 12 (solid.sweep): the path curves are not connected end to end
|
||||
3830-split-cup-by-extended-spline-surface not supported yet: surface.extend of a surface of more than one face (this one has 3)
|
||||
Reference in new issue
Block a user