Wave 210/509: doc, engine, kernel: solid.fillet and solid.chamfer round each picked edge's tangent chain by default (and 3 more)

4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop.

- 84bd2daad jyviko: doc, engine, kernel: solid.fillet and solid.chamfer round each picked edge's tangent chain by default
- d0ff1dcfa jyviko: doc: an extrude's taper without a corner rule picks one per profile
- 5e7aba8df jyviko: loft sections matched to their neighbours
- 2752eee61 jyviko: kernel: merged topology counts no seam edge (a face on both sides of it)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyvikoandClaude Opus 5.5 committed 2026-10-22 14:24:15 -04:00
1 parent 227e4b7794
commit 9aedc5faed
22 files changed
+311 -99

No files matched your search

+7 -1
View File
@@ -187,7 +187,13 @@ mod tests {
}
assert!(std::sync::Arc::ptr_eq(&reference, &mb.mesh()));
assert_eq!(mb.display_plan_at(DisplayQuality::Normal).unwrap().vertex_count(), {
let plan = mb.body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: (mb.body.size() * 1e-3).max(1e-3), angle: Some(solidcraft_kernel::DISPLAY_ANGLE) }).unwrap();
let plan = mb
.body
.mesh_plan(&solidcraft_kernel::MeshTolerance {
chord: (mb.body.size() * 1e-3).max(1e-3),
angle: Some(solidcraft_kernel::DISPLAY_ANGLE),
})
.unwrap();
plan.vertex_count()
});
}
+14 -8
View File
@@ -274,10 +274,6 @@ impl ExtrudeConvention {
}
}
fn draft_corner_is_default(c: &solidcraft_kernel::DraftCorner) -> bool {
*c == solidcraft_kernel::DraftCorner::default()
}
/// Extent of an extrude.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
pub struct Extent {
@@ -305,10 +301,13 @@ pub struct Extent {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(angle = "Taper angle")]
pub taper: Option<Expr>,
/// How a taper closes the profile's sharp corners ([`solidcraft_kernel::draft_corners`] says
/// what each rule gives at each corner).
#[serde(default, skip_serializing_if = "draft_corner_is_default")]
pub corner: solidcraft_kernel::DraftCorner,
/// How a taper closes the profile's sharp corners, when the user chose
/// ([`solidcraft_kernel::draft_corners`] says what each rule gives at each corner). Without
/// it each profile takes preserve curvature where the kernel can build it exactly and the
/// tangent rule where a curve that is neither a line nor an arc has a corner, and the
/// feature's warning says so.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub corner: Option<solidcraft_kernel::DraftCorner>,
/// To Object: end at the face (or vertex/point) at this point, instead of `distance`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to: Option<FacePick>,
@@ -657,6 +656,10 @@ pub enum FeatureKind {
/// (default) or a G2 patch repeating each blend up to the second order.
#[serde(default, skip_serializing_if = "FilletCorner::is_rolling")]
corner: FilletCorner,
/// Round each picked edge's tangent chain with it (the default: edges continuing it
/// smoothly at its ends, as far as they go), or only the picked edges.
#[serde(default = "yes", skip_serializing_if = "is_yes")]
tangent_chain: bool,
},
Chamfer {
edges: Vec<Position>,
@@ -675,6 +678,9 @@ pub enum FeatureKind {
flip: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
body: Option<BodyName>,
/// Cut each picked edge's tangent chain with it (the default), or only the picked edges.
#[serde(default = "yes", skip_serializing_if = "is_yes")]
tangent_chain: bool,
},
Box {
#[serde(with = "point_expr")]
+55 -8
View File
@@ -301,7 +301,10 @@ impl ModelBody {
if k == 0 {
return Some((self.display_plan_at(q)?, self.plan_mesh_at(q)?));
}
let plan = match self.body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(self.body.size(), k), angle: Some(q.refined_angle(k)) }) {
let plan = match self
.body
.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(self.body.size(), k), angle: Some(q.refined_angle(k)) })
{
Ok(plan) => plan,
Err(e) => {
log::debug!("{}: no display plan refined {k} steps ({e})", self.name);
@@ -2454,6 +2457,28 @@ pub fn draft_corner_options(ss: &SolvedSketch, sel: &ProfileSel, distance: f64,
Ok(out)
}
/// The corner rule a taper takes for profile `r` of `ss` when the user chose none: preserve
/// curvature, unless a corner of the profile cannot keep it exactly (a curve that is neither a
/// line nor an arc), then the tangent rule, with a note in `notes` saying where and why.
fn draft_corner_for(ss: &SolvedSketch, r: &Region2, distance: f64, taper: f64, notes: &mut Vec<String>) -> Result<kernel::DraftCorner> {
let reports = kernel::draft_corners(r, distance, taper)?;
let inexact = reports.iter().find(|c| {
c.options.iter().any(|o| o.rule == kernel::DraftCorner::PreserveCurvature && o.fill == Err(kernel::CornerRefusal::NotExact))
});
Ok(match inexact {
Some(c) => {
notes.push(format!(
"the taper's corners of profile at ({}, {}) in {} use the tangent rule: a curve of it is neither a line nor an arc, so its walls cannot continue as themselves exactly; corner: round also builds",
show_mm(c.at.x),
show_mm(c.at.y),
ss.name
));
kernel::DraftCorner::Tangent
}
None => kernel::DraftCorner::PreserveCurvature,
})
}
pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result<Vec<Region2>> {
let ps = &ss.profiles;
if ps.is_empty() {
@@ -4463,6 +4488,7 @@ fn feature_tools_with_constructor(
st: &ModelState,
constructor: &mut Option<ExtrudeConstructor>,
to_body: &mut Option<String>,
warning: &mut Option<String>,
) -> Result<Vec<Traced>> {
*to_body = None;
let unnamed = |bodies: Vec<Body>| -> Vec<Traced> { bodies.into_iter().map(Traced::unnamed).collect() };
@@ -4550,15 +4576,22 @@ fn feature_tools_with_constructor(
];
// How far a tool grows past its profile, at most: its sides' run over its length.
let growth = len * taper.tan().abs();
let mut notes = Vec::new();
let tools: Vec<Traced> = regions
.iter()
.map(|r| {
let roles =
crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() };
let body = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper, extent.corner)?;
let roles = crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() };
let corner = match extent.corner {
Some(c) => c,
None => draft_corner_for(&ss, r, len, taper, &mut notes)?,
};
let body = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper, corner)?;
Ok(roles.tool(body, None))
})
.collect::<Result<_>>()?;
for note in notes {
append_warning(warning, note);
}
// Profiles apart by more than the tools grow (the letters of a text): the tools
// are apart too, and go into the body as one, in one boolean rather than one per
// profile, each on a body grown or cut by the ones before. (A join meeting several
@@ -5895,7 +5928,7 @@ fn replay(
// points follow their named faces, as the feature's own did (#2121): a To Object
// extrude's copies reach the face where it is now, not where it was picked.
let moved = with_named_face_points(doc, st, src).map(|(g, _)| g);
let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None)?;
let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None, &mut None)?;
for (k, m) in mats.iter().enumerate() {
let start = copies.len();
for t in &tools {
@@ -6089,8 +6122,10 @@ fn trim_to_body(tools: Vec<Traced>, target: &ModelBody, dist_to_start: impl Fn(V
let lineages = crate::lineage::Lineage::lumps(&cut.body, cut.lineage.as_ref(), &lumps);
for (lump, lineage) in lumps.into_iter().zip(lineages) {
let tol = (lump.size() * 1e-4).max(1e-6);
let touches =
lump.mesh(&solidcraft_kernel::MeshTolerance::chord((lump.size() * 1e-2).max(1e-2))).map(|m| m.positions.iter().any(|q| dist_to_start(*q) < tol)).unwrap_or(false);
let touches = lump
.mesh(&solidcraft_kernel::MeshTolerance::chord((lump.size() * 1e-2).max(1e-2)))
.map(|m| m.positions.iter().any(|q| dist_to_start(*q) < tol))
.unwrap_or(false);
if touches {
out.push(Traced { body: lump, lineage });
}
@@ -6421,7 +6456,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
| FeatureKind::Sweep { operation, targets, .. } => {
let mut constructor = None;
let mut to_body = None;
let tools = feature_tools_with_constructor(doc, vals, f, st, &mut constructor, &mut to_body)?;
let tools = feature_tools_with_constructor(doc, vals, f, st, &mut constructor, &mut to_body, warning)?;
// Cuts through sheet metal become cut-outs of its flat pattern.
if matches!(operation, Operation::Cut | Operation::Intersect) && matches!(f.kind, FeatureKind::Extrude { .. }) && !st.sheets.is_empty() {
let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();
@@ -6847,11 +6882,22 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
}
let (mut found, mut notes, mut fitted, mut tapered_all) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut reduced = false;
// The kernel blends exactly the edges given: the feature adds each one's tangent
// chain when it asks for it. A radius law runs along one edge, so a variable or
// spline round takes its edge alone.
let chain = match &f.kind {
FeatureKind::Fillet { tangent_chain, style, .. } => {
*tangent_chain && !matches!(style, crate::FilletStyle::Variable { .. } | crate::FilletStyle::Spline { .. })
}
FeatureKind::Chamfer { tangent_chain, .. } => *tangent_chain,
_ => false,
};
let mut blended = Vec::new();
for (ti, idx) in &groups {
let Some(mb) = st.bodies.get(*ti) else { return Err(DocError::Invalid("body".into())) };
let mut w = None;
let edges = blend_edges_on(mb, f, edges, idx, &mut w)?;
let edges = if chain { kernel::tangent_chain(&mb.body, &edges)? } else { edges };
if let Some(w) = w {
notes.push(w);
}
@@ -7864,6 +7910,7 @@ mod chain_tests {
style: crate::FilletStyle::Constant,
fit: Default::default(),
corner: Default::default(),
tangent_chain: true,
},
None,
)
@@ -0,0 +1,4 @@
//! A fillet or chamfer saves `tangent_chain: false` when it blends only its picked edges; absent,
//! the default, it blends each picked edge's tangent chain too, as designs before this change were
//! built (SMLib followed the chains itself). An older design has none and keeps its chains. The
//! last release refuses a design with this change (the newer format number).
@@ -1,6 +1,7 @@
//! An extrude's taper saves how it closes the profile's sharp corners: `extent.corner`,
//! `tangent` or `round` (each offset curve continued straight along its end tangent, or an arc
//! about the corner); absent for `preserve_curvature`, the default, where each wall continues as
//! itself until it meets its neighbour. An older design has none and takes the default, the rule
//! its tapers were built with before SMLib (the walls meeting where the curves' offsets cross). The
//! last release refuses a design with this change (the newer format number).
//! An extrude's taper saves how it closes the profile's sharp corners when the user chose:
//! `extent.corner`, `preserve_curvature` (each wall continues as itself until it meets its
//! neighbour), `tangent` (each offset curve continued straight along its end tangent) or `round`
//! (an arc about the corner). Without it each profile preserves curvature where every curve is a
//! line or an arc and takes the tangent rule where another curve has a corner, the feature's
//! warning saying so; an older design has none and gets that choice. The last release refuses a
//! design with this change (the newer format number).
+4 -2
View File
@@ -322,8 +322,10 @@ fn profile_points(doc: &Document, st: &ModelState, p: &CamProfile, cam: &super::
}
// Each body sampled to its own size (a large part beside the cam leaves the cam fine).
// Each body's edges with the faces beside them.
let meshes: Vec<solidcraft_geom::Mesh> =
bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tolerance(b.body.size())))).collect::<std::result::Result<_, _>>()?;
let meshes: Vec<solidcraft_geom::Mesh> = bodies
.iter()
.map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tolerance(b.body.size()))))
.collect::<std::result::Result<_, _>>()?;
let edges: Vec<(usize, &Vec<Vec3>, &[u32])> = meshes
.iter()
.enumerate()
+2
View File
@@ -262,6 +262,7 @@ fn box_fillet_cut_timeline() {
style: Default::default(),
fit: Default::default(),
corner: Default::default(),
tangent_chain: true,
},
None,
)
@@ -334,6 +335,7 @@ fn errors_are_reported_not_fatal() {
style: Default::default(),
fit: Default::default(),
corner: Default::default(),
tangent_chain: true,
},
None,
)
+29 -7
View File
@@ -55,7 +55,16 @@ fn intersection_never_keeps_material_outside_the_trimming_cylinder() {
let before = volume(&s, "Base");
let r = s.execute("solid.cylinder", &json!({"radius": 16.65, "height": 14.59, "operation": "intersect", "targets": ["Base"]}));
let state = s.model.state();
let reach = state.body("Base").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().positions.iter().map(|p| p.x.hypot(p.y)).fold(0.0, f64::max);
let reach = state
.body("Base")
.unwrap()
.body
.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3))
.unwrap()
.positions
.iter()
.map(|p| p.x.hypot(p.y))
.fold(0.0, f64::max);
match r {
Ok(_) => assert!(reach < 16.65 + 1e-2, "kept material out to radius {reach}"),
Err(e) => assert!((volume(&s, "Base") - before).abs() < 1e-9 && reach > 16.9, "{e}"),
@@ -544,7 +553,8 @@ fn joined_loft_frames_plan_their_display_at_every_quality() {
let body = &state.body(name).unwrap().body;
for q in DisplayQuality::ALL {
for k in 0..=MAX_REFINE {
let plan = body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(body.size(), k), angle: Some(q.refined_angle(k)) });
let plan =
body.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: q.refined_chord(body.size(), k), angle: Some(q.refined_angle(k)) });
assert!(plan.is_ok(), "{name} at {} + {k}: {:?}", q.id(), plan.err());
}
}
@@ -595,7 +605,10 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() {
// Faces meshed coarsely keep to their surfaces: chords cut a little area off round faces,
// and nothing adds any (triangles fanning across a chamfer from the notch's hole or from the
// cuts' trims, folded over each other, added a few mm² each).
let (coarse, fine) = (body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap().measure().area, body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().area);
let (coarse, fine) = (
body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap().measure().area,
body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().area,
);
assert!(coarse < fine && coarse > fine - 2.0, "area meshed at 0.05: {coarse} vs {fine}");
println!(
"ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}",
@@ -611,7 +624,8 @@ fn notch_into_a_ring_chamfer_is_cut_exactly() {
let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap();
let steps = script.get("commands").and_then(Value::as_array).unwrap();
let mut s = Session::default();
let measure = |s: &Session| s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume;
let measure =
|s: &Session| s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume;
s.run_script(&Value::Array(steps[..5].to_vec())).unwrap();
let before = measure(&s);
// The notch's sketch and its cut.
@@ -942,7 +956,10 @@ fn imported_rotated_face_extrusions_preserve_other_operations_and_bodies() {
let reference = expected.body(&body.name).unwrap();
// Fixed fine chord tolerance: cap subdivision can change the default
// adaptive mesh's cylinder faceting without changing its analytic surface.
let (a, b) = (body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume, reference.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume);
let (a, b) = (
body.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume,
reference.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume,
);
assert!((a - b).abs() < b.max(1.) * 1e-6, "{operation}: {} {a} vs {b}", body.name);
assert!(body.body.validity().is_empty(), "{operation}: {}", body.name);
let (a, b) = (body.mesh(), reference.mesh());
@@ -957,7 +974,11 @@ fn imported_rotated_face_extrusions_preserve_other_operations_and_bodies() {
let unchanged = &actual.body("Other").unwrap().body;
assert_eq!(unchanged.face_count(), other.face_count());
assert_eq!(unchanged.color(), other.color());
assert_eq!(unchanged.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions, other.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions, "unaffected imported body");
assert_eq!(
unchanged.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions,
other.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().positions,
"unaffected imported body"
);
}
}
}
@@ -1135,7 +1156,8 @@ fn cut_up_to_the_plate_top_face_opens_the_hole() {
// The same design without the cut.
script["commands"].as_array_mut().unwrap().pop();
let before = replay_value(&script);
let fine = |s: &Session| s.model.state().body("Body7").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume;
let fine =
|s: &Session| s.model.state().body("Body7").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume;
let (removed, want) = (fine(&before) - fine(&s), std::f64::consts::PI * 3.04 * 3.04 * 1.2);
assert!((removed - want).abs() < 0.01, "removed {removed} mm³, want {want}");
}
+5 -3
View File
@@ -161,9 +161,11 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result<Value> {
// Meshed within a quarter of the tolerance (the kernel goes no finer than a millionth of a
// body's size), so two meshes of one surface agree well within it.
let chord = tolerance / 4.0;
let mut done = solidcraft_kernel::map_on_threads(&[ba, bb], 2, |b| (super::inspect::measure_json(b), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(chord))))
.into_iter()
.zip([&na, &nb]);
let mut done = solidcraft_kernel::map_on_threads(&[ba, bb], 2, |b| {
(super::inspect::measure_json(b), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(chord)))
})
.into_iter()
.zip([&na, &nb]);
let mut next = || -> Result<(Value, solidcraft_geom::Mesh)> {
let Some((r, name)) = done.next() else { return Err(bad(cmd, "no such body")) };
let (m, mesh) = r.ok_or_else(|| bad(cmd, format!("`{name}`: measuring it failed")))?;
+16 -5
View File
@@ -489,16 +489,26 @@ fn transferred_frozen_face_paint_ignores_consumed_legacy_offset() {
fn boundary_material_proof_requires_resolvable_stock_and_void() {
use solidcraft_geom::Vec3;
let a = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
let b = solidcraft_kernel::box_solid(Vec3::new(1e-5, 0., 0.), Vec3::new(10.00001, 10., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
let b = solidcraft_kernel::box_solid(Vec3::new(1e-5, 0., 0.), Vec3::new(10.00001, 10., 10.))
.unwrap()
.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3))
.unwrap();
let p = Vec3::new(5e-6, 5., 5.);
assert_ne!(a.contains(p), b.contains(p));
assert!((super::mesh_distance(&a, p) - 5e-6).abs() < 1e-12);
assert!((super::mesh_distance(&b, p) - 5e-6).abs() < 1e-12);
assert!(super::material_probe_matches(&a, &b, p, 1e-3, 1e-3));
let shifted = solidcraft_kernel::box_solid(Vec3::new(1., 0., 0.), Vec3::new(11., 10., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
let shifted = solidcraft_kernel::box_solid(Vec3::new(1., 0., 0.), Vec3::new(11., 10., 10.))
.unwrap()
.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3))
.unwrap();
assert!(!super::material_probe_matches(&a, &shifted, p, 1e-3, 1e-3));
let thin = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 1e-4)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)).unwrap();
let thin_shifted = solidcraft_kernel::box_solid(Vec3::new(0., 0., 1e-4), Vec3::new(10., 10., 2e-4)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)).unwrap();
let thin =
solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(10., 10., 1e-4)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6)).unwrap();
let thin_shifted = solidcraft_kernel::box_solid(Vec3::new(0., 0., 1e-4), Vec3::new(10., 10., 2e-4))
.unwrap()
.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-6))
.unwrap();
// Every resolvable replacement is void: thin ambiguous material is refused.
assert!(!super::material_probe_matches(&thin, &thin_shifted, Vec3::new(5., 5., 5e-5), 1e-3, 1e-3));
assert!(!super::material_probe_matches(&a, &b, p, f64::INFINITY, 1e-3));
@@ -519,7 +529,8 @@ fn frozen_bore_boundary_copy_preserves_stock_void_and_reopen() {
// cardinal angle, so its distance is bounded by the requested sag tolerance.
assert!(super::mesh_distance(&source, Vec3::new(6., 10., 5.)) <= 1e-3);
let shifted = bore(11.).model.state().body("Drilled").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
let lost = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30., 20., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
let lost =
solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30., 20., 10.)).unwrap().mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap();
assert!(!super::material_probe_matches(&source, &shifted, Vec3::new(6.5, 10., 5.), 1e-3, 1e-3));
assert!(!super::material_probe_matches(&source, &lost, Vec3::new(10., 10., 5.), 1e-3, 1e-3));
let created = run(&mut s, "component.from_bodies", json!({"bodies":["Drilled"]}));
@@ -203,7 +203,11 @@ fn legacy_v9_annulus_outer_side_emboss_keeps_its_original_heuristic_anchor() {
}
let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap());
assert!(reopened.model.result(feature_id).unwrap().error.is_none());
assert!((reopened.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - volume).abs() < 1e-8);
assert!(
(reopened.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - volume)
.abs()
< 1e-8
);
}
#[test]
+7 -5
View File
@@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.key("E")
.contract(&EXTRUDE_CONTRACT)
.output(output_schema_for::<FeatureResult>)
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Default preserve_curvature, which needs lines and arcs at the corners); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
CommandSpec::new("solid.revolve", "Revolve", revolve)
.at("SOLID", "CREATE")
.icon("revolve")
@@ -49,8 +49,8 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SOLID", "MODIFY")
.icon("fillet")
.key("F")
.params("edges: [[x,y,z] point on edge | {body, index}] (exactly these edges are rounded: a tangent chain is not followed, so list every edge of it); radius: expr; body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),
CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] (exactly these edges are cut: a tangent chain is not followed, so list every edge of it); distance: expr; distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),
.params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),
CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),
CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),
CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect)
.at("SOLID", "CREATE")
@@ -1109,8 +1109,8 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result<Extent>
check_expr(s, t, Kind::Angle, cmd, "taper")?;
}
let corner = match p.get("corner") {
None => solidcraft_kernel::DraftCorner::default(),
Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`corner` must be preserve_curvature, tangent or round"))?,
None => None,
Some(value) => Some(serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`corner` must be preserve_curvature, tangent or round"))?),
};
let direction = match str_(p, "direction").map(str::to_ascii_lowercase).as_deref() {
None | Some("positive") | Some("one_side") => Direction::Positive,
@@ -1635,6 +1635,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
style,
fit,
corner,
tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),
},
)?;
// The radii the fillet used, when `fit: reduce` reduced it.
@@ -1676,6 +1677,7 @@ fn chamfer(s: &mut Session, p: &Value) -> Result<Value> {
angle,
flip,
body: str_(p, "body").map(BodyName::from),
tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),
},
)
}
+33 -11
View File
@@ -630,7 +630,13 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() {
.world_state()
.bodies
.iter()
.find(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcraft_geom::Vec3::new(40.5 + pick_offset, 0., 7.5)))
.find(|b| {
b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcraft_geom::Vec3::new(
40.5 + pick_offset,
0.,
7.5,
))
})
.unwrap()
.name
.clone();
@@ -654,7 +660,13 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() {
assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02);
let world = s.world_state();
for x in [39.5, 119.5] {
assert!(world.bodies.iter().any(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcraft_geom::Vec3::new(x, 0., 7.5))));
assert!(
world.bodies.iter().any(|b| b
.body
.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001))
.unwrap()
.contains(solidcraft_geom::Vec3::new(x, 0., 7.5)))
);
}
let mut loaded = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Default::default() };
loaded.refresh();
@@ -802,7 +814,15 @@ fn check_body_offset(auto: bool) {
assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02);
assert_eq!(s.doc.body_offsets["Sleeve"], offset);
assert_eq!(s.doc.body_component("Sleeve", s.model.state().body("Sleeve").unwrap().feature), holder);
assert!(s.world_state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(solidcraft_geom::Vec3::new(0., 10.5, 7.5)));
assert!(
s.world_state()
.body("Sleeve")
.unwrap()
.body
.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001))
.unwrap()
.contains(solidcraft_geom::Vec3::new(0., 10.5, 7.5))
);
}
#[test]
@@ -984,7 +1004,11 @@ fn cylinder_auto_inference_saves_a_profile_anchor_and_replays_both_depth_signs()
let body = &state.body("Sleeve").unwrap().body;
assert_eq!(body.shell_count(), 1);
assert_eq!(
body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(Vec3::new(0., if mode == "emboss" { 10.5 } else { 9.5 }, 7.5)),
body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().contains(Vec3::new(
0.,
if mode == "emboss" { 10.5 } else { 9.5 },
7.5
)),
mode == "emboss"
);
run(&mut s, "edit.undo", json!({}));
@@ -1022,7 +1046,10 @@ fn cylinder_auto_inference_ignores_remote_finite_tangent_walls_in_each_body_orde
let remote = s.model.state().body("Remote").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume;
run(&mut s, "solid.emboss", json!({"sketch":"Badge","depth":1}));
assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02);
assert_eq!(s.model.state().body("Remote").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume, remote);
assert_eq!(
s.model.state().body("Remote").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume,
remote
);
}
}
@@ -1865,12 +1892,7 @@ fn a_ring_cut_round_a_hole_takes_in_the_hole_it_is_drawn_round() {
let before = volume(&mut s);
// Profile 2: the ring between the hole's wall and the larger circle.
let r = s.execute("solid.extrude", &json!({"direction":"negative","distance":"3","operation":"cut","profiles":[2]}));
let clean = r
.as_ref()
.ok()
.and_then(|v| v["feature"].as_u64())
.and_then(|id| s.model.result(id))
.is_some_and(|f| f.error.is_none());
let clean = r.as_ref().ok().and_then(|v| v["feature"].as_u64()).and_then(|id| s.model.result(id)).is_some_and(|f| f.error.is_none());
(r.is_ok(), before - volume(&mut s), clean)
};
let taken = std::f64::consts::PI * (36.0 - 9.0) * 3.0;
+4 -1
View File
@@ -195,7 +195,10 @@ pub fn collisions(s: &Session) -> Vec<(String, String, f64)> {
/// Edges are tested for crossing the other's surface too: plates crossing face to face have
/// no sample point inside (#3323).
fn overlap(a: &Body, b: &Body) -> Option<f64> {
let (ma, mb) = (a.mesh(&solidcraft_kernel::MeshTolerance::chord((a.size() * 1e-3).max(1e-3))).ok()?, b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * 1e-3).max(1e-3))).ok()?);
let (ma, mb) = (
a.mesh(&solidcraft_kernel::MeshTolerance::chord((a.size() * 1e-3).max(1e-3))).ok()?,
b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * 1e-3).max(1e-3))).ok()?,
);
mesh_overlap(&ma, &mb, 1e-4 * a.size().max(b.size()).max(1.0))
}
@@ -662,7 +662,9 @@ fn a_rectangle_put_onto_a_projected_edge_stays_a_closed_profile() {
// Picked by a point inside, it extrudes to a 20 x 15 x 10 block of its own.
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"sketch": id, "profiles": [{"point": [15, 7.5]}], "distance": 10, "operation": "new", "body_name": "Pad"}));
let volume = |s: &Session, name: &str| s.model.state().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume;
let volume = |s: &Session, name: &str| {
s.model.state().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume
};
assert!((volume(&s, "Pad") - 3000.0).abs() < 1e-6, "{}", volume(&s, "Pad"));
assert!((volume(&s, &block) - 24000.0).abs() < 1e-6, "{}", volume(&s, &block));
let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
+6 -1
View File
@@ -41,7 +41,12 @@ fn enclosure() -> Session {
}
fn bodies(s: &Session) -> Vec<(String, f64)> {
s.model.state().bodies.iter().map(|b| (b.name.clone(), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume)).collect()
s.model
.state()
.bodies
.iter()
.map(|b| (b.name.clone(), b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume))
.collect()
}
#[test]
+2
View File
@@ -1048,6 +1048,7 @@ mod tests {
style: Default::default(),
fit: Default::default(),
corner: Default::default(),
tangent_chain: true,
},
None,
)
@@ -1133,6 +1134,7 @@ mod tests {
style: Default::default(),
fit: Default::default(),
corner: Default::default(),
tangent_chain: true,
},
None,
)
+62 -1
View File
@@ -2,7 +2,7 @@
//! ([`crate::blend_smlib`]): the blend faces, the corners where blends meet (a sphere, a patch, a
//! bevel or a mitre, as its fillet corners choose) and the end faces rebuilt round them. A blend
//! whose contact lines would leave the faces it rolls on is SMLib's refusal, reported as
//! [`KernelError::TooLarge`]. A tangent chain is the caller's to select.
//! [`KernelError::TooLarge`]. A tangent chain is the caller's to select ([`tangent_chain`]).
//!
//! The helpers here read a body's schema 4 record: planar faces' outward normals, the direction
//! into a face across an edge, an edge's tangent at its ends.
@@ -389,6 +389,67 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl
crate::blend_smlib::chamfer_sides(body, edges, d1, side, flip)
}
/// The picked edges' tangent chains, for a blend that is to run along them: `picks` (each the
/// nearest edge of `body` to it), then a point on every other edge that continues one of them
/// tangentially (within 0.5° at a shared vertex), until no more do. An edge only one face uses
/// ends a chain. Picks that find no edge are refused.
pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result<Vec<Vec3>> {
/// Edges meeting at an angle below this continue one another.
const TANGENT_DEGREES: f64 = 0.5;
if picks.is_empty() || picks.len() > 1000 || picks.iter().any(|p| !p.is_finite()) {
return Err(KernelError::Invalid("select 1…1000 edges by finite points".into()));
}
let rec = Faces::of(body)?;
let size = body.size();
let mut chain: Vec<usize> = Vec::new();
for p in picks {
let (e, dist) = body.nearest_edge(*p, (size * 2e-3).max(1e-3))?.ok_or_else(|| KernelError::Invalid("the body has no edges".into()))?;
if dist > size * 0.05 + 1e-3 {
return Err(KernelError::Invalid(format!("no edge near the pick at ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)));
}
if !chain.contains(&e) {
chain.push(e);
}
}
let picked = chain.len();
// The unit direction edge `e` leaves its end `v` in.
let leaving = |e: usize, v: u32| -> Option<Vec3> {
let [a, b] = rec.rec.edges.get(e)?.vertices;
if a == b {
return None;
}
if a == v { rec.tangent(e, false) } else { rec.tangent(e, true).map(|t| t * -1.0) }
};
let cos = TANGENT_DEGREES.to_radians().cos();
let mut k = 0;
while k < chain.len() {
let Some(&e) = chain.get(k) else { break };
k += 1;
let Some(edge) = rec.rec.edges.get(e) else { continue };
for v in edge.vertices {
let Some(d) = leaving(e, v) else { continue };
for (f, other) in rec.rec.edges.iter().enumerate() {
if chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) {
continue;
}
if leaving(f, v).is_some_and(|g| d.dot(g) < -cos) {
chain.push(f);
}
}
}
}
let mut out = picks.to_vec();
for e in chain.into_iter().skip(picked) {
let edge = rec.rec.edges.get(e).ok_or_else(|| KernelError::Failed("a chain edge".into()))?;
let mid = CurveEval::new(&edge.curve)
.ok()
.and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1])))
.ok_or_else(|| KernelError::Failed("a point on a chain edge".into()))?;
out.push(mid);
}
Ok(out)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
+30 -35
View File
@@ -1056,7 +1056,12 @@ pub(crate) fn loft_reversed(sections: &[(Plane, Loop2)]) -> Result<bool> {
/// The loft's sections as the walls are built through them: in canonical order (`reversed`
/// turns them round), each oriented the same way, re-split to the same number of segments and
/// started at the segment that lines up with the lead section's first.
/// started at the segment that lines up with the section before it. Every section is matched to
/// its neighbour, as the walls pair them: it winds the way the section before it does about the
/// normal they share (its plane's normal, turned over where it faces back from the one before),
/// so sections whose planes turn on round the loft (a bar bent half a turn) keep one winding;
/// and it starts where its vertices line up best with the section before it. The first section is
/// matched to the one with the most segments, whose count every section takes.
pub(crate) fn loft_numbered_loops(sections: &[(Plane, NumberedLoop)], reversed: bool) -> Result<Vec<(Plane, NumberedLoop)>> {
let n = sections.iter().map(|(_, l)| l.lp.segs.len()).max().unwrap_or(0);
if n == 0 || n > MAX_SEGS {
@@ -1067,45 +1072,35 @@ pub(crate) fn loft_numbered_loops(sections: &[(Plane, NumberedLoop)], reversed:
if reversed {
ordered.reverse();
}
// Orient every section counter-clockwise about the first section's normal (`Body::new`
// turns the solid outward), then match segment counts and starting points to the section
// with the most segments.
let n0 = ordered.first().map(|(p, _)| p.normal()).unwrap_or(Vec3::Z);
let parallel = ordered.iter().all(|(p, _)| p.normal().dot(n0).abs() > 1.0 - 1e-9);
let oriented: Vec<(Plane, NumberedLoop)> = ordered
.iter()
.map(|(p, l)| {
let ccw = p.normal().dot(n0) >= 0.0;
(*p, l.oriented(!ccw))
})
.collect();
let lead = oriented.iter().max_by_key(|(_, l)| l.lp.segs.len()).ok_or_else(|| KernelError::Invalid("no sections".into()))?;
let lead_c = lead.0.to_world(lead.1.lp.centroid());
let lead_dirs: Vec<Vec3> = lead.1.lp.segs.iter().map(|s| lead.0.to_world(s.start()) - lead_c).collect();
let mut out = Vec::with_capacity(oriented.len());
for (p, l) in &oriented {
let c = l.lp.centroid();
// Break angles: the lead section's vertex directions seen in this plane.
let angles: Vec<f64> = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y)).angle()).collect();
let mut r = l.resample(n, &angles);
// Circle resampling creates increasing local angles. An antiparallel sketch
// plane must run clockwise locally to keep the same winding in world space.
// Curving a run through a right angle does not reverse a section's winding.
if parallel && p.normal().dot(n0) < 0.0 {
r = r.oriented(true);
}
// Start where every vertex lines up best with the lead's vertex of the same number (the
// largest sum of dot products of their directions from the centroids). The one vertex
// closest in direction to the lead's first vertex twisted non-convex sections (#881): a
// zig-zag's centroid sits off its outline, so its first vertex can point away from the
// lead's.
let dirs: Vec<Vec2> = lead_dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y))).collect();
let lead = ordered.iter().max_by_key(|(_, l)| l.lp.segs.len()).ok_or_else(|| KernelError::Invalid("no sections".into()))?;
let corners = |p: &Plane, l: &NumberedLoop| -> (Vec3, Vec<Vec3>) {
let c = p.to_world(l.lp.centroid());
(c, l.lp.segs.iter().map(|s| p.to_world(s.start()) - c).collect())
};
let first_normal = ordered.first().map(|(p, _)| p.normal()).ok_or_else(|| KernelError::Invalid("no sections".into()))?;
// What each section is matched to: the normal the windings share, and the corners' directions
// from the centre (the lead's for the first section, then the section before).
let (mut normal, mut dirs) = (first_normal, corners(&lead.0, &lead.1.oriented(lead.0.normal().dot(first_normal) < 0.0)).1);
let mut out = Vec::with_capacity(ordered.len());
for (p, l) in &ordered {
let back = p.normal().dot(normal) < 0.0;
let local: Vec<Vec2> = dirs.iter().map(|d| Vec2::new(d.dot(p.x), d.dot(p.y))).collect();
// Break angles: the matched corners seen in this plane. A re-split circle runs counter-
// clockwise in its plane; wound the other way when the plane faces back.
let angles: Vec<f64> = local.iter().map(|d| d.angle()).collect();
let mut r = l.oriented(back).resample(n, &angles).oriented(back);
// Start where every vertex lines up best with the matched one of the same number (the
// largest sum of dot products of their directions from the centroids): the single vertex
// closest in direction twisted non-convex sections (#881).
let c = r.lp.centroid();
let m = r.lp.segs.len();
let fit =
|k: usize| -> f64 { dirs.iter().enumerate().filter_map(|(i, d)| r.lp.segs.get((i + k) % m).map(|s| (s.start() - c).dot(*d))).sum() };
|k: usize| -> f64 { local.iter().enumerate().filter_map(|(i, d)| r.lp.segs.get((i + k) % m).map(|s| (s.start() - c).dot(*d))).sum() };
if let Some(k) = (0..m).min_by(|a, b| fit(*b).total_cmp(&fit(*a))) {
r.rotate_left(k);
}
normal = if back { p.normal() * -1.0 } else { p.normal() };
dirs = corners(p, &r).1;
out.push((*p, r));
}
Ok(out)
+5 -2
View File
@@ -39,7 +39,7 @@ impl DraftCorner {
pub enum CornerRefusal {
/// The continued curves do not meet (two parallel lines, two circles that part).
Apart,
/// A curve at the corner is neither a line nor an arc: its wall has no exact continuation.
/// A curve of the profile is neither a line nor an arc: its wall has no exact continuation.
NotExact,
/// A wall at the corner closes before the far end (its arc shrinks to its centre).
WallCloses,
@@ -97,6 +97,9 @@ pub fn draft_corners(region: &Region2, distance: f64, taper: f64) -> Result<Vec<
let segs = &outer.segs;
let d = distance * taper.tan();
let n = segs.len();
// The walls are built as one exact set: a profile with a sharp corner keeps its curvature only
// when every curve is a line or an arc.
let free = segs.iter().any(|s| matches!(carrier(s, d), Carrier::Free));
let mut out = Vec::new();
for k in 0..n {
let (Some(a), Some(b)) = (segs.get((k + n - 1) % n), segs.get(k)) else { continue };
@@ -111,7 +114,7 @@ pub fn draft_corners(region: &Region2, distance: f64, taper: f64) -> Result<Vec<
let (ea, eb) = (a.end() + right(ta) * d, b.start() + right(tb) * d);
// A left turn opens a gap when the profile grows, a right turn when it shrinks.
let gap = (turn > 0.0) == (d > 0.0);
let curvature = continued(ca, cb, ea, eb, p, d);
let curvature = if free { Err(CornerRefusal::NotExact) } else { continued(ca, cb, ea, eb, p, d) };
let options = if gap {
[
CornerOption { rule: DraftCorner::PreserveCurvature, fill: curvature },
+1 -1
View File
@@ -150,7 +150,7 @@ mod validity;
pub mod watch;
mod whole_face;
pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each};
pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each, tangent_chain};
pub use blend_corner::fillet_radii;
pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper};
pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, MeshTolerance, Paint};
+10
View File
@@ -122,6 +122,8 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result<TopoCounts> {
let mut weld_e: HashMap<(usize, usize, (i64, i64, i64)), usize> = HashMap::new();
let mut welded_faces: Vec<Vec<usize>> = Vec::new();
let mut welded_ends: Vec<(usize, usize)> = Vec::new();
// How many face uses each welded edge has (a seam: two, on one face).
let mut welded_uses: Vec<usize> = Vec::new();
// A record edge standing for each welded edge (for its points).
let mut rep: Vec<u32> = Vec::new();
for (ei, (e, between)) in record.edges.iter().zip(edge_faces(record)).enumerate() {
@@ -133,8 +135,12 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result<TopoCounts> {
if we == welded_faces.len() {
welded_faces.push(Vec::new());
welded_ends.push((a, z));
welded_uses.push(0);
rep.push(ei as u32);
}
if let Some(n) = welded_uses.get_mut(we) {
*n += e.uses.len();
}
if let Some(fs) = welded_faces.get_mut(we) {
for f in between {
if !fs.contains(&f) {
@@ -206,8 +212,12 @@ pub fn merged_topology(b: &Body, mesh: &Mesh) -> Result<TopoCounts> {
}
continue;
}
// An edge between two pieces of one merged face, or a seam (one face on both its sides),
// is no edge of the merged topology; one face on one side only is an open edge.
let seam = welded_uses.get(we).is_some_and(|n| *n >= 2);
let pair = match gs[..] {
[a, b] if a == b => continue,
[_] if seam => continue,
[a, b] => (a.min(b), a.max(b)),
[a] => (a, a),
_ => (usize::MAX, usize::MAX),