Skip to content

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

Fillet: Mitre or Swept corners where two rounds meet (#11498)

jyvikof74c6605c41e
diff --git a/assets/locales/pending/fillet-turn.json b/assets/locales/pending/fillet-turn.json
new file mode 100644
index 0000000000..62ca952166
--- /dev/null
+++ b/assets/locales/pending/fillet-turn.json
@@ -0,0 +1,50 @@
+{
+ "en": {
+ "ui.fillet_turn": "Turns",
+ "ui.fillet_turn_mitre": "Mitre",
+ "ui.fillet_turn_swept": "Swept",
+ "ui.fillet_turn_tip": "Where two rounds turn round a sharp corner edge between them, such as the rounds along a boss's base at its upright edges.\nMitre: the rounds run on until they meet in a mitre.\nSwept: the rounds stop at the corner edge and turn round it, the corner a torus tangent to both. Only for rounds of one radius round a straight, convex corner edge."
+ },
+ "ar": {
+ "ui.fillet_turn": "المنعطفات",
+ "ui.fillet_turn_mitre": "وصلة مائلة",
+ "ui.fillet_turn_swept": "مُدار",
+ "ui.fillet_turn_tip": "حيث يلتف تقويسان حول حافة ركن حادة بينهما، مثل التقويسات على قاعدة بروز عند حوافه القائمة.\nوصلة مائلة: يمتد التقويسان حتى يلتقيا في وصلة مائلة.\nمُدار: يتوقف التقويسان عند حافة الركن ويلتفان حولها، والركن طارة مماسة لكليهما. فقط لتقويسين بنصف قطر واحد حول حافة ركن مستقيمة ومحدبة."
+ },
+ "de": {
+ "ui.fillet_turn": "Wendungen",
+ "ui.fillet_turn_mitre": "Gehrung",
+ "ui.fillet_turn_swept": "Geschwenkt",
+ "ui.fillet_turn_tip": "Wo zwei Rundungen um eine scharfe Eckkante zwischen ihnen herumlaufen, etwa die Rundungen am Fuß eines Zapfens an seinen senkrechten Kanten.\nGehrung: Die Rundungen laufen weiter, bis sie sich in einer Gehrung treffen.\nGeschwenkt: Die Rundungen enden an der Eckkante und schwenken um sie herum; die Ecke ist ein Torus, tangential zu beiden. Nur für Rundungen mit einem Radius um eine gerade, konvexe Eckkante."
+ },
+ "he": {
+ "ui.fillet_turn": "פניות",
+ "ui.fillet_turn_mitre": "מיטר",
+ "ui.fillet_turn_swept": "מסובב",
+ "ui.fillet_turn_tip": "היכן ששני עיגולים מסתובבים סביב קצה פינה חד ביניהם, כמו העיגולים בבסיס בליטה ליד הקצוות הזקופים שלה.\nמיטר: העיגולים נמשכים עד שהם נפגשים במיטר.\nמסובב: העיגולים נעצרים בקצה הפינה ומסתובבים סביבו, והפינה היא טורוס המשיק לשניהם. רק לעיגולים ברדיוס אחד סביב קצה פינה ישר וקמור."
+ },
+ "ja": {
+ "ui.fillet_turn": "曲がり角",
+ "ui.fillet_turn_mitre": "留め継ぎ",
+ "ui.fillet_turn_swept": "回転",
+ "ui.fillet_turn_tip": "2 つのフィレットが間にある鋭いコーナーエッジを回り込む所(ボスの根元のフィレットが立ち上がりエッジを回る所など)。\n留め継ぎ: フィレットは延びて留め継ぎで出会います。\n回転: フィレットはコーナーエッジで止まり、その周りを回ります。コーナーは両方に接するトーラスです。同じ半径のフィレットが、まっすぐな凸のコーナーエッジを回る場合のみ。"
+ },
+ "ko": {
+ "ui.fillet_turn": "꺾임",
+ "ui.fillet_turn_mitre": "마이터",
+ "ui.fillet_turn_swept": "회전",
+ "ui.fillet_turn_tip": "두 라운드가 사이의 날카로운 코너 모서리를 돌아가는 곳(보스 밑동의 라운드가 세로 모서리를 도는 곳 등).\n마이터: 라운드가 계속 이어져 마이터로 만납니다.\n회전: 라운드가 코너 모서리에서 멈추고 그 둘레를 돕니다. 코너는 둘 모두에 접하는 토러스입니다. 반지름이 같은 라운드가 곧고 볼록한 코너 모서리를 돌 때만."
+ },
+ "vi": {
+ "ui.fillet_turn": "Chỗ rẽ",
+ "ui.fillet_turn_mitre": "Vát góc",
+ "ui.fillet_turn_swept": "Quét vòng",
+ "ui.fillet_turn_tip": "Nơi hai góc lượn rẽ quanh một cạnh góc sắc nằm giữa chúng, ví dụ các góc lượn ở chân một khối lồi tại các cạnh đứng của nó.\nVát góc: các góc lượn kéo dài cho đến khi gặp nhau theo đường vát.\nQuét vòng: các góc lượn dừng ở cạnh góc và quay quanh nó, góc là một mặt xuyến tiếp xúc với cả hai. Chỉ cho các góc lượn cùng bán kính quanh một cạnh góc thẳng và lồi."
+ },
+ "zh": {
+ "ui.fillet_turn": "转角",
+ "ui.fillet_turn_mitre": "斜接",
+ "ui.fillet_turn_swept": "旋转",
+ "ui.fillet_turn_tip": "两个圆角绕过它们之间尖锐的角边处,例如凸台根部的圆角绕过其竖直边。\n斜接:圆角继续延伸,直到以斜接相遇。\n旋转:圆角止于角边并绕它旋转,转角是与两者相切的圆环面。仅用于同一半径的圆角绕过笔直的凸角边时。"
+ }
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index d3fafdd013..e2fb074e6b 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -734,6 +734,10 @@ pub enum FeatureKind {
/// from the vertex instead of where the rounds meet (a constant-radius fillet only).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
setbacks: Vec<CornerSetback>,
+ /// How two rounds turn where they meet at a sharp side edge: in a mitre (the default) or
+ /// swept round it (a constant-radius, exact, rolling-corner fillet without setbacks only).
+ #[serde(default, skip_serializing_if = "FilletTurn::is_mitre")]
+ turn: FilletTurn,
/// 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")]
@@ -1971,6 +1975,38 @@ impl FilletCorner {
}
}
+/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to
+/// both on a plane, such as the rounds along a boss's base at its upright edges.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FilletTurn {
+ /// The rounds run on to where they cross and meet in a mitre.
+ #[default]
+ Mitre,
+ /// The rounds end at the side edge and the corner is their section revolved about it, a
+ /// torus tangent to both (`solidcraft_kernel::FilletTurn::Swept`).
+ Swept,
+}
+
+/// Why a swept turn is refused with a fillet's other options: the kernel sweeps the turn of two
+/// constant rounds of one radius, at its own corners only.
+pub const SWEPT_TAKES: &str = "a swept corner turns two constant rounds of one radius: `turn: swept` takes `type: constant`, \
+`corner: rolling`, no `setbacks` and `fit: exact` or `reduce`";
+
+impl FilletTurn {
+ pub fn is_mitre(&self) -> bool {
+ *self == FilletTurn::Mitre
+ }
+
+ /// The kernel's turn.
+ pub fn kernel(self) -> solidcraft_kernel::FilletTurn {
+ match self {
+ FilletTurn::Mitre => solidcraft_kernel::FilletTurn::Mitre,
+ FilletTurn::Swept => solidcraft_kernel::FilletTurn::Swept,
+ }
+ }
+}
+
/// How Extend continues a surface past its edges.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 50d7595ef2..c1d435336b 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -409,13 +409,14 @@ fn fillet_fitted(
edges: &[Vec3],
r: f64,
fit: crate::FilletFit,
+ turn: kernel::FilletTurn,
) -> std::result::Result<(kernel::Body, Option<Vec<f64>>, Vec<Vec3>), kernel::KernelError> {
- match kernel::fillet_removing(body, edges, r) {
+ match kernel::fillet_removing(body, edges, r, turn) {
Ok((b, gone)) => Ok((b, None, gone)),
Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Exact => {
- Err(with_largest_fit(why, "radius", || kernel::fillet_max(body, edges, r)))
+ Err(with_largest_fit(why, "radius", || kernel::fillet_max(body, edges, r, turn)))
}
- Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Reduce => match kernel::fillet_max_each(body, edges, r)? {
+ Err(kernel::KernelError::TooLarge(why)) if fit == crate::FilletFit::Reduce => match kernel::fillet_max_each(body, edges, r, turn)? {
// Built at the radius asked for after all (the groups apart): nothing reduced.
Some((used, b)) => Ok((b, used.iter().any(|u| *u < r).then_some(used), Vec::new())),
None => Err(kernel::KernelError::TooLarge(why)),
@@ -4014,6 +4015,11 @@ fn blend_body(
) -> Result<(Traced, Option<Vec<f64>>, Tapered)> {
let input = mb.traced();
let (mut used, mut tapered) = (None, Vec::new());
+ if let FeatureKind::Fillet { turn: crate::FilletTurn::Swept, style, fit, corner, setbacks, .. } = &f.kind
+ && (!style.is_constant() || *fit == crate::FilletFit::Taper || !corner.is_rolling() || !setbacks.is_empty())
+ {
+ return Err(DocError::Invalid(crate::SWEPT_TAKES.into()));
+ }
// The blended body, and the lineage of what the last blend started from.
let (nb, from) = match &f.kind {
// A curvature-continuous fillet's corners are G2 patches, whatever `corner` says: SMLib's
@@ -4061,8 +4067,8 @@ fn blend_body(
tapered = edges.iter().copied().zip(tapers).filter_map(|(p, t)| Some((p, t?))).collect();
(b, input)
}
- FeatureKind::Fillet { fit, .. } => {
- let (b, u, gone) = fillet_fitted(&mb.body, edges, r, *fit)?;
+ FeatureKind::Fillet { fit, turn, .. } => {
+ let (b, u, gone) = fillet_fitted(&mb.body, edges, r, *fit, turn.kernel())?;
if let Some(u) = &u {
append_warning(warning, reduced_note(u, r));
}
@@ -6323,12 +6329,12 @@ fn replay(
let nb = match &src.kind {
FeatureKind::Chamfer { distance2, angle, flip, .. } => chamfer_with(vals, &mb.body, &moved, r, distance2, angle, *flip)?,
// A copy is congruent to the original: the radius it was reduced to first.
- FeatureKind::Fillet { fit, .. } => match st.fitted.get(&src.id) {
+ FeatureKind::Fillet { fit, turn, .. } => match st.fitted.get(&src.id) {
Some(used) => {
let used: Vec<f64> = idx.iter().map(|i| used.get(*i).copied().unwrap_or(r)).collect();
- kernel::fillet_each(&mb.body, &moved, &used)?
+ kernel::fillet_each(&mb.body, &moved, &used, turn.kernel())?
}
- None => fillet_fitted(&mb.body, &moved, r, *fit)?.0,
+ None => fillet_fitted(&mb.body, &moved, r, *fit, turn.kernel())?.0,
},
_ => kernel::fillet(&mb.body, &moved, r)?,
};
@@ -8550,6 +8556,7 @@ mod chain_tests {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain: true,
},
None,
@@ -8578,6 +8585,7 @@ mod chain_tests {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain,
}
}
diff --git a/crates/doc/src/format/pending/fillet-turn.rs b/crates/doc/src/format/pending/fillet-turn.rs
new file mode 100644
index 0000000000..34c49ca990
--- /dev/null
+++ b/crates/doc/src/format/pending/fillet-turn.rs
@@ -0,0 +1,5 @@
+//! A fillet saves `turn: "swept"` when two of its rounds that turn round a sharp side edge (the
+//! rounds along a boss's base, at its upright edges) are swept round that edge, their corner an
+//! exact torus; absent, the default `mitre`, they meet in a mitre, as designs before this change were
+//! built. An older design has none and keeps its mitres. The last release refuses a design with
+//! this change (the newer format number).
diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs
index ee1034e24b..dca6b1fa84 100644
--- a/crates/doc/src/tests.rs
+++ b/crates/doc/src/tests.rs
@@ -295,6 +295,7 @@ fn box_fillet_cut_timeline() {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain: true,
},
None,
@@ -370,6 +371,7 @@ fn errors_are_reported_not_fatal() {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain: true,
},
None,
@@ -867,12 +869,39 @@ fn fillet_setbacks_default_to_none_and_round_trip() {
fit: Default::default(),
corner: Default::default(),
setbacks: vec![CornerSetback { vertex: Position(Vec3::new(60.0, 40.0, 20.0)), distance: "8 mm".into() }],
+ turn: Default::default(),
tangent_chain: true,
};
let back: FeatureKind = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap();
assert_eq!(back, set);
}
+/// A fillet saved before turns reads as mitred and writes no `turn`; a swept one saves
+/// `turn: "swept"` and keeps it through a save and an open; a turn of another name is refused.
+#[test]
+fn fillet_turn_defaults_to_mitre_round_trips_and_refuses_unknown_turns() {
+ let old = serde_json::json!({"type": "fillet", "edges": [[15.0, 0.0, 10.0]], "radius": "2"});
+ let kind: FeatureKind = serde_json::from_value(old.clone()).unwrap();
+ let FeatureKind::Fillet { turn, .. } = &kind else { panic!("{kind:?}") };
+ assert_eq!(*turn, crate::FilletTurn::Mitre);
+ assert!(serde_json::to_value(&kind).unwrap().get("turn").is_none());
+ let mut swept = old.clone();
+ swept["turn"] = serde_json::json!("swept");
+ let kind: FeatureKind = serde_json::from_value(swept).unwrap();
+ assert!(matches!(kind, FeatureKind::Fillet { turn: crate::FilletTurn::Swept, .. }), "{kind:?}");
+ assert_eq!(serde_json::to_value(&kind).unwrap()["turn"], "swept");
+ let mut doc = Document::new("turn");
+ doc.add_feature(kind.clone(), None).unwrap();
+ let saved = doc.to_json();
+ let opened = Document::from_json(&saved).unwrap();
+ assert_eq!(opened.features.last().map(|f| &f.kind), Some(&kind));
+ assert_eq!(opened.to_json(), saved);
+ let mut unknown = old;
+ unknown["turn"] = serde_json::json!("round");
+ let e = serde_json::from_value::<FeatureKind>(unknown).unwrap_err().to_string();
+ assert!(e.contains("unknown variant `round`") && e.contains("mitre") && e.contains("swept"), "{e}");
+}
+
#[test]
fn timeline_group_legacy_json_omits_empty_joint_membership() {
let old = serde_json::json!({"id":100, "name":"Folder", "parent":null, "features":[]});
diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs
index 22564ac5b7..26bd9441f6 100644
--- a/crates/doc/src/walk.rs
+++ b/crates/doc/src/walk.rs
@@ -54,6 +54,7 @@ impl Walk for solidcraft_kernel::DraftCorner {}
impl Walk for crate::document::Direction {}
impl Walk for crate::document::FilletFit {}
impl Walk for crate::document::FilletCorner {}
+impl Walk for crate::document::FilletTurn {}
impl Walk for crate::document::MeshData {}
impl Walk for crate::document::RevolveConvention {}
impl Walk for crate::document::RailFit {}
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index de283be166..311bfe3336 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -13,8 +13,8 @@ use solidcraft_geom::prelude::*;
use super::{CommandSpec, not_in_sketch};
use crate::params::{UNKNOWN_COMMAND, bad, bool_, expr, expr_problem, req_expr, str_, string_list, string_list_or_default, vec2, vec3};
use crate::schema::features::{
- BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice, FeatureResult, NoticeAction, OffsetPlaneParams,
- PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,
+ AppliedRadius, BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice, FeatureResult, FilletParams,
+ FilletResult, NoticeAction, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -30,6 +30,7 @@ const BOUNDING_SOLID_CONTRACT: TypedContract<BoundingSolidParams> = TypedContrac
const SCALE_CONTRACT: TypedContract<ScaleParams> = TypedContract::new();
const OFFSET_PLANE_CONTRACT: TypedContract<OffsetPlaneParams> = TypedContract::new();
const PLANE_AT_ANGLE_CONTRACT: TypedContract<PlaneAtAngleParams> = TypedContract::new();
+const FILLET_CONTRACT: TypedContract<FilletParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("solid.extrude", "Extrude", crate::checked!("solid.extrude", extrude))
@@ -78,11 +79,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&CONE_CONTRACT)
.output(output_schema_for::<FeatureResult>)
.params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, touching?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.fillet", "Fillet", fillet)
+ CommandSpec::new("solid.fillet", "Fillet", crate::checked!("solid.fillet", fillet))
.at("SOLID", "MODIFY")
.icon("fillet")
.key("F")
- .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; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; 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)"),
+ .contract(&FILLET_CONTRACT)
+ .output(output_schema_for::<FilletResult>)
+ .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; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); turn?: mitre|swept (where two rounds turn round a sharp, straight, convex side edge square to both on a plane, such as the rounds along a boss's base at its upright edges: mitre, the default, runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus; swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; 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; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),
CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect)
@@ -1788,6 +1791,15 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`setbacks` are built for a constant-radius fillet (`type: constant`, `fit: exact`) only"));
}
}
+ // How two rounds turn at a sharp side edge.
+ let turn = match str_(p, "turn").map(str::to_ascii_lowercase).as_deref() {
+ None | Some("mitre") => solidcraft_doc::FilletTurn::Mitre,
+ Some("swept") => solidcraft_doc::FilletTurn::Swept,
+ Some(o) => return Err(bad(cmd, format!("unknown turn `{o}` (mitre or swept)"))),
+ };
+ if !turn.is_mitre() && (!style.is_constant() || fit == solidcraft_doc::FilletFit::Taper || !corner.is_rolling() || !setbacks.is_empty()) {
+ return Err(bad(cmd, solidcraft_doc::SWEPT_TAKES));
+ }
let mut out = add_feature(
s,
p,
@@ -1799,6 +1811,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
fit,
corner,
setbacks,
+ turn,
tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),
},
)?;
@@ -1808,9 +1821,9 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
&& let Some(r) = state.fitted_radius(id)
{
out["radius_applied"] = serde_json::json!(r);
- let each: Vec<Value> =
- state.fitted_edges(id).unwrap_or_default().into_iter().map(|(p, r)| serde_json::json!({"edge": [p.x, p.y, p.z], "radius": r})).collect();
- out["radii_applied"] = Value::Array(each);
+ let each: Vec<AppliedRadius> =
+ state.fitted_edges(id).unwrap_or_default().into_iter().map(|(p, radius)| AppliedRadius { edge: [p.x, p.y, p.z], radius }).collect();
+ out["radii_applied"] = serde_json::to_value(each).map_err(|e| EngineError::Internal(cmd.into(), e.to_string()))?;
}
Ok(out)
}
@@ -3567,6 +3580,87 @@ mod corner_tests {
eprintln!("mixed corner g2: {err}");
assert!(err.contains("not supported yet") && err.contains("(40.000, 20.000, 20.000)") && err.contains("all convex or all concave"), "{err}");
}
+
+ /// `solid.fillet turn?: mitre|swept` on the four base edges of a 10 x 10 x 5 boss on a
+ /// 40 x 30 x 10 plate, r 1: at each upright boss edge the two rounds turn round it. Each base
+ /// edge gains the spandrel A = (1 - π/4) r² along its 10, and the corners the rounds' part
+ /// beyond both walls, whose section's first moment about the upright edge is
+ /// M = (5/6 - π/4) r³: mitred (the default), 8 M; swept, that section revolved a quarter turn at
+ /// each corner, 2π M, the corner's face the horn torus of radii r, r about the upright edge,
+ /// centred r above the plate. The turn is saved; an unknown turn and a swept chord round are
+ /// refused as parameters, and swept rounds along a pocket's floor (its upright edges concave)
+ /// with the kernel's reason.
+ #[test]
+ fn rounds_turning_round_a_boss_edge_are_mitred_or_swept() {
+ use std::f64::consts::PI;
+ const BASE: [[f64; 3]; 4] = [[20.0, 10.0, 10.0], [25.0, 15.0, 10.0], [20.0, 20.0, 10.0], [15.0, 15.0, 10.0]];
+ let boss = || {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "B"}));
+ run(&mut s, "solid.box", &json!({"corner": [15, 10, 10], "length": 10, "width": 10, "height": 5, "operation": "join"}));
+ s
+ };
+ let turned = |turn: Option<&str>| {
+ let mut s = boss();
+ let mut p = json!({"edges": BASE, "radius": 1});
+ if let Some(t) = turn {
+ p["turn"] = json!(t);
+ }
+ let reply = run(&mut s, "solid.fillet", &p);
+ assert_eq!(reply["warning"], json!(null), "{reply}");
+ let body = s.world_state().unwrap().body("B").unwrap().body.clone();
+ assert!(body.validity().is_empty(), "{:?}", body.validity());
+ (s, solidcraft_kernel::measure(&body).unwrap(), body)
+ };
+ let (mitred, mitre, _) = turned(None);
+ let (_, named, _) = turned(Some("mitre"));
+ let (swept_session, swept, body) = turned(Some("swept"));
+ eprintln!("mitre: {} faces, {:.9}; swept: {} faces, {:.9}", mitre.faces, mitre.volume, swept.faces, swept.volume);
+ let r: f64 = 1.0;
+ let (a, m) = ((1.0 - PI / 4.0) * r * r, (5.0 / 6.0 - PI / 4.0) * r * r * r);
+ let near = |v: f64, want: f64| (v - want).abs() < 1e-9 * want;
+ assert!(near(mitre.volume, 12500.0 + 40.0 * a + 8.0 * m), "{}", mitre.volume);
+ assert!(near(swept.volume, 12500.0 + 40.0 * a + 2.0 * PI * m), "{}", swept.volume);
+ assert_eq!(named.volume.to_bits(), mitre.volume.to_bits(), "mitre is the default");
+ assert_eq!((mitre.faces, swept.faces), (15, 19));
+ // The four corner faces (the record's torus is a ring torus, so a horn torus is its exact
+ // rational form): every point on the horn torus about its upright edge.
+ let mut corners = 0;
+ for f in &body.record().faces {
+ if !matches!(f.surface, solidcore_record::brep::Surface::RationalSpline { .. }) {
+ continue;
+ }
+ corners += 1;
+ let eval = solidcraft_geom::brep::eval::SurfaceEval::new(&f.surface).unwrap();
+ let [[u0, u1], [v0, v1]] = f.domain;
+ for i in 0..=4 {
+ for j in 0..=4 {
+ let p = eval.point([u0 + (u1 - u0) * f64::from(i) / 4.0, v0 + (v1 - v0) * f64::from(j) / 4.0]).unwrap();
+ let (cx, cy) = (if p.x < 20.0 { 15.0 } else { 25.0 }, if p.y < 15.0 { 10.0 } else { 20.0 });
+ let rho = (p.x - cx).hypot(p.y - cy);
+ let off = ((rho - r).powi(2) + (p.z - 10.0 - r).powi(2)).sqrt() - r;
+ assert!(off.abs() < 1e-9, "{p:?} is {off} off the horn torus");
+ }
+ }
+ }
+ assert_eq!(corners, 4);
+ assert!(!mitred.doc.to_json().contains("\"turn\""));
+ assert!(swept_session.doc.to_json().contains("\"turn\": \"swept\""));
+ let mut s = boss();
+ let e = s.execute("solid.fillet", &json!({"edges": BASE, "radius": 1, "turn": "round"})).unwrap_err().to_string();
+ assert!(e.contains("unknown turn `round` (mitre or swept)"), "{e}");
+ let e = s.execute("solid.fillet", &json!({"edges": BASE, "radius": 1, "turn": "swept", "type": "chord"})).unwrap_err().to_string();
+ assert!(e.contains(solidcraft_doc::SWEPT_TAKES), "{e}");
+ // A pocket 5 deep in the plate, its floor's edges rounded: the rounds meet at its concave
+ // upright edges.
+ let mut s = Session::default();
+ run(&mut s, "solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "P"}));
+ run(&mut s, "solid.box", &json!({"corner": [10, 10, 5], "length": 20, "width": 10, "height": 6, "operation": "cut"}));
+ let rim = json!([[20, 10, 5], [30, 15, 5], [20, 20, 5], [10, 15, 5]]);
+ let e = s.execute("solid.fillet", &json!({"edges": rim, "radius": 1, "turn": "swept"})).unwrap_err().to_string();
+ eprintln!("swept along a pocket's rim: {e}");
+ assert!(e.contains("swept corner at (") && e.contains("round that edge at a radius of at least 1 first"), "{e}");
+ }
}
#[cfg(test)]
#[path = "fillet_connected_rounds_tests.rs"]
diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs
index c750114bbf..ee83f04a04 100644
--- a/crates/engine/src/schema/features.rs
+++ b/crates/engine/src/schema/features.rs
@@ -10,9 +10,10 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::types::{
- AngleExpr, AxisDir, AxisLine, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon, FromPoint,
- GeoRefParam, IdOrName, LengthExpr, NumberExpr, OperationParam, PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors,
- SketchRef, StringList, ThinSideParam, ToPoint, TouchingParam, feature_common, present,
+ AngleExpr, AxisDir, AxisLine, ConventionParam, DirectionParam, EdgeRefs, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon,
+ FilletCornerParam, FilletFitParam, FilletTurnParam, FilletTypeParam, FromPoint, GeoRefParam, IdOrName, LengthExpr, NumberExpr, OperationParam,
+ PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors, SketchRef, StringList, ThinSideParam, ToPoint, TouchingParam,
+ feature_common, present,
};
/// Add a box primitive.
@@ -432,6 +433,92 @@ pub struct PlaneAtAngleParams {
pub common: PlaneCommon,
}
+/// Round edges of a body: a constant radius by default, or a chord, a curvature-continuous
+/// section or a radius varying along each edge (`type`).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct FilletParams {
+ /// The edges to round: a point on each, or `{body, index}`.
+ pub edges: EdgeRefs,
+ /// The radius; the chord's width with `type: chord`, the equivalent circular setback with
+ /// `type: curvature`, the start radius with `type: variable` or `spline`.
+ pub radius: LengthExpr,
+ /// The body whose edges the points pick. Default: whichever body has an edge there.
+ #[serde(default)]
+ pub body: Option<String>,
+ /// Round each picked edge's tangent chain with it. Default: true; false rounds exactly the
+ /// picked edges.
+ #[serde(default)]
+ pub tangent_chain: Option<bool>,
+ #[serde(default, rename = "type")]
+ pub kind: Option<FilletTypeParam>,
+ /// `type: variable`: the radius at the end away from `start`; it or `radius` may be 0, where
+ /// the round closes to the corner.
+ #[serde(default)]
+ pub radius2: Option<LengthExpr>,
+ /// `type: variable` or `spline`: a point near the end the radius starts from.
+ #[serde(default)]
+ pub start: Option<Point3>,
+ /// `type: variable`: radii between the ends, each `[position, radius]`, the position between 0
+ /// and 1 from the start end. At most 100 are read.
+ #[serde(default)]
+ pub mid: Option<Vec<(f64, LengthExpr)>>,
+ /// `type: variable`: smooth instead of straight between the radii. Default: false.
+ #[serde(default)]
+ pub smooth: Option<bool>,
+ /// `type: spline`: the control radii after `radius`. At most 100 are read.
+ #[serde(default)]
+ pub radii: Option<Vec<LengthExpr>>,
+ /// `type: spline`: the knot vector from 0 to 1, as many knots as all control radii, the
+ /// degree (1 to 3) and one more.
+ #[serde(default)]
+ pub knots: Option<Vec<f64>>,
+ #[serde(default)]
+ pub fit: Option<FilletFitParam>,
+ #[serde(default)]
+ pub corner: Option<FilletCornerParam>,
+ /// Corner setbacks: the corner at the vertex nearest each `vertex`, where every edge meeting it
+ /// is rounded, starts its patch `distance` along each of those edges from the vertex, past
+ /// where the rounds would meet. Constant-radius exact fillets only.
+ #[serde(default)]
+ pub setbacks: Option<Vec<SetbackParam>>,
+ #[serde(default)]
+ pub turn: Option<FilletTurnParam>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// A fillet corner set back.
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct SetbackParam {
+ /// A point at the corner's vertex.
+ pub vertex: Point3,
+ /// How far along each edge there the corner's patch starts.
+ pub distance: LengthExpr,
+}
+
+/// The radius `fit: reduce` gave one edge.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct AppliedRadius {
+ /// A point on the edge.
+ pub edge: [f64; 3],
+ /// The radius it was rounded at.
+ pub radius: f64,
+}
+
+/// What `solid.fillet` returns: a feature command's reply, with the radii `fit: reduce` used.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct FilletResult {
+ #[serde(flatten)]
+ pub feature: FeatureResult,
+ /// With `fit: reduce` where it reduced the radius: the smallest radius used.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub radius_applied: Option<f64>,
+ /// With `fit: reduce` where it reduced the radius: each edge's radius.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub radii_applied: Option<Vec<AppliedRadius>>,
+}
+
/// What a feature command returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct FeatureResult {
diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs
index a2104369a4..bc55cbddba 100644
--- a/crates/engine/src/schema/features_tests.rs
+++ b/crates/engine/src/schema/features_tests.rs
@@ -1,8 +1,8 @@
use serde_json::{Value, json};
use super::{
- BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, OffsetPlaneParams, PipeParams, PlaneAtAngleParams,
- ScaleParams, SphereParams, TorusParams,
+ BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, FilletParams, FilletResult, OffsetPlaneParams,
+ PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,
};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};
@@ -87,6 +87,30 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<ScaleParams>(), &["bodies", "factor", "factors", "name", "origin", "participants"]);
assert_keys(input_schema_for::<OffsetPlaneParams>(), &["base", "name", "offset", "participants", "through"]);
assert_keys(input_schema_for::<PlaneAtAngleParams>(), &["angle", "axis", "base", "name", "participants"]);
+ assert_keys(
+ input_schema_for::<FilletParams>(),
+ &[
+ "body",
+ "body_name",
+ "body_names",
+ "corner",
+ "edges",
+ "fit",
+ "knots",
+ "mid",
+ "name",
+ "participants",
+ "radii",
+ "radius",
+ "radius2",
+ "setbacks",
+ "smooth",
+ "start",
+ "tangent_chain",
+ "turn",
+ "type",
+ ],
+ );
}
#[test]
@@ -157,6 +181,13 @@ fn strict_keeps_todays_errors() {
("construct.plane.at_angle", json!({"base": "XY", "axis": {"face": "x", "point": [0, 0, 0]}, "angle": 30})),
("construct.plane.at_angle", json!({"base": "XY", "axis": {"face": "x"}, "angle": 30})),
("construct.plane.at_angle", json!({"base": "XY", "axis": "X", "angle": true})),
+ ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "turn": "round"})),
+ ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "turn": "ROUND"})),
+ ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "type": "bogus"})),
+ ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "fit": "bogus"})),
+ ("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "corner": "round"})),
+ ("solid.fillet", json!({"edges": [], "radius": 1})),
+ ("solid.fillet", json!({"edges": 5, "radius": 1})),
]);
}
@@ -213,6 +244,47 @@ fn replies_match_the_output_schema() {
assert!(!conforms(schema, schema, &bad), "{bad}");
}
+/// `solid.fillet` replies with `FilletResult` in each of its forms, its contract taking each: a
+/// boss's base rounded with each turn and its options spelled out, a reduced round (with the radii
+/// it used), chord and curvature rounds, a smooth-patch corner with setbacks, and the variable and
+/// spline forms.
+#[test]
+fn fillet_replies_match_its_output_schema() {
+ let schema = output_schema_for::<FilletResult>();
+ let schema = schema.as_value();
+ // A 40 x 30 x 10 plate with a 10 x 10 x 5 boss on it, whose base edges `boss` are.
+ let run = |p: Value| {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 10, "body_name": "B"})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("solid.box", &json!({"corner": [15, 10, 10], "length": 10, "width": 10, "height": 5, "operation": "join"}))
+ .unwrap_or_else(|e| panic!("{e}"));
+ let r = s.execute("solid.fillet", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");
+ r
+ };
+ let boss = json!([[20, 10, 10], [25, 15, 10], [20, 20, 10], [15, 15, 10]]);
+ run(
+ json!({"edges": boss, "radius": 1, "turn": "mitre", "type": "constant", "fit": "exact", "corner": "rolling", "tangent_chain": true, "body": "B", "name": "Round"}),
+ );
+ run(json!({"edges": boss, "radius": "1 mm", "turn": "Swept"}));
+ run(json!({"edges": boss, "radius": 1, "turn": "swept", "fit": "reduce"}));
+ let reduced = run(json!({"edges": [[20, 0, 10]], "radius": 15, "fit": "reduce"}));
+ assert!(reduced.get("radius_applied").is_some_and(Value::is_number) && reduced.get("radii_applied").is_some_and(Value::is_array), "{reduced}");
+ run(json!({"edges": [[20, 0, 10]], "radius": 1, "type": "chord"}));
+ run(json!({"edges": [{"body": "B", "index": 0}], "radius": 0.5, "tangent_chain": false}));
+ run(json!({"edges": [[20, 0, 10]], "radius": 1, "type": "curvature"}));
+ // Variable and spline radii: solidcore fails a variable round on a box edge at this pin (status
+ // 1001, as `variable_radius_on_a_box_edge`), so their forms are checked against the contract.
+ for p in [
+ json!({"edges": [[20, 0, 10]], "radius": 1, "type": "variable", "radius2": 2, "start": [0, 0, 10], "mid": [[0.5, "1.5 mm"]], "smooth": true}),
+ json!({"edges": [[20, 0, 10]], "radius": 1, "type": "spline", "start": [0, 0, 10], "radii": [2], "knots": [0, 0, 1, 1]}),
+ ] {
+ assert!(crate::schema::Contract::check(&crate::schema::TypedContract::<FilletParams>::new(), &p).is_empty(), "{p}");
+ }
+ run(json!({"edges": [[20, 0, 10], [40, 15, 10], [40, 0, 5]], "radius": 2, "corner": "g2", "setbacks": [{"vertex": [40, 0, 10], "distance": 4}]}));
+}
+
/// The feature commands converted after box and extrude answer with `FeatureResult` too, and
/// their contracts take every form these calls use: in Warn, a contract that refused one would
/// still run the command, so the replies are checked for warnings too.
diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs
index 3a5cdeccd3..13cdae9353 100644
--- a/crates/engine/src/schema/tests.rs
+++ b/crates/engine/src/schema/tests.rs
@@ -367,7 +367,7 @@ fn issues_are_read_from_the_commands_own_contract() {
assert_eq!(messages(&issues), ["unknown key `operaton`; did you mean `operation`?"]);
assert_eq!(issues, box_contract().check(&json!({"length": 1, "width": 1, "height": 1, "operaton": "cut"})));
// No contract, or no such command: nothing to say.
- assert!(super::issues("solid.fillet", &json!({"nonsense": 1})).is_empty());
+ assert!(super::issues("solid.chamfer", &json!({"nonsense": 1})).is_empty());
assert!(super::issues("no.such", &json!({"nonsense": 1})).is_empty());
}
diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs
index 72adae3a23..94b93e02dc 100644
--- a/crates/engine/src/schema/types.rs
+++ b/crates/engine/src/schema/types.rs
@@ -464,6 +464,66 @@ fn enum_schema(values: &[&str], description: &str) -> Schema {
json_schema!({"description": description, "type": "string", "enum": values})
}
+/// A keyword a handler reads with `str_` and lowercases, refusing any other word with `unknown
+/// <what> `<word>` (<expected>)`; the lowercased word is kept for the handler.
+macro_rules! keyword_param {
+ ($(#[$doc:meta])* $name:ident, $what:literal, $values:expr, $expected:literal, $description:literal) => {
+ $(#[$doc])*
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct $name(pub String);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let ok = |s: &str| $values.contains(&s.to_ascii_lowercase().as_str());
+ let unknown = |s: &str| whole(format!(concat!("unknown ", $what, " `{}` (", $expected, ")"), s.to_ascii_lowercase()));
+ string_matching(d, ok, $expected, unknown).map(|s| $name(s.to_ascii_lowercase()))
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ enum_schema($values, $description)
+ }
+ }
+ };
+}
+
+keyword_param!(
+ /// `solid.fillet`'s `type`.
+ FilletTypeParam,
+ "fillet type",
+ &["constant", "rolling_ball", "chord", "chord_length", "curvature", "g2", "variable", "spline"],
+ "constant, chord, variable, spline or curvature",
+ "The round's section: constant (the default; rolling_ball is an alias), chord (`radius` is the width across; alias chord_length), curvature (alias g2: curvature-continuous between planar faces along straight edges, `radius` the equivalent circular setback), variable (`radius` at the end nearest `start`, `radius2` at the other) or spline (the radius a clamped B-spline from `start`: `radius`, then `radii`, over `knots`). Matching ignores case."
+);
+keyword_param!(
+ /// `solid.fillet`'s `fit`.
+ FilletFitParam,
+ "fit",
+ &["exact", "reduce", "taper"],
+ "exact, reduce or taper",
+ "What a radius too large for the geometry around the edges does: exact (the default) refuses it naming the largest that fits, reduce reduces it where it doesn't fit, taper follows the room along straight edges between planar faces. reduce and taper take type: constant. Matching ignores case."
+);
+keyword_param!(
+ /// `solid.fillet`'s `corner`.
+ FilletCornerParam,
+ "corner",
+ &["rolling", "g2"],
+ "rolling or g2",
+ "What fills a corner where three rounded edges meet: rolling (the default), the rolling ball's sphere, or g2, a set-back patch meeting the rounds to the second order (type: constant, fit: exact only). Matching ignores case."
+);
+keyword_param!(
+ /// `solid.fillet`'s `turn`.
+ FilletTurnParam,
+ "turn",
+ &["mitre", "swept"],
+ "mitre or swept",
+ "How two rounds turn round a sharp, straight, convex side edge square to both on a plane (the rounds along a boss's base, at its upright edges): mitre (the default) runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus. swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent. Matching ignores case."
+);
+
/// How a feature combines with existing bodies, as `features::operation` reads it.
#[derive(Clone, Debug, PartialEq)]
pub struct OperationParam(pub Operation);
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index c2cfd8758d..a1d80a6892 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -308,7 +308,6 @@ solid.coil
solid.combine
solid.draft
solid.emboss
-solid.fillet
solid.hole
solid.loft
solid.mirror
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 9ba7d27e06..2f1dde8bd6 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -1296,6 +1296,7 @@ mod tests {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain: true,
},
None,
@@ -1418,6 +1419,7 @@ mod tests {
fit: Default::default(),
corner: Default::default(),
setbacks: Vec::new(),
+ turn: Default::default(),
tangent_chain: true,
},
None,
diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs
index d80590065a..0cb99e70de 100644
--- a/crates/kernel/src/blend.rs
+++ b/crates/kernel/src/blend.rs
@@ -234,22 +234,40 @@ fn closed(input: &Body, b: Body) -> Result<Body> {
}
}
+/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to
+/// both on a plane, such as the rounds along a boss's base at its upright edges.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum FilletTurn {
+ /// The rounds run on to where they cross and meet in a mitre.
+ #[default]
+ Mitre,
+ /// The rounds end at the side edge and the corner is their section revolved about it, a
+ /// torus tangent to both. Refused where it is not built (unequal or variable rounds, a
+ /// concave, curved or tangent side edge, a corner of four edges), with the reason.
+ Swept,
+}
+
/// Constant-radius fillet of the edges nearest to the given points. A radius too large for the
/// faces around the edges is refused with [`KernelError::TooLarge`] ([`fillet_max`] finds the
/// largest that works).
pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {
+ fillet_turning(body, edges, radius, FilletTurn::Mitre)
+}
+
+/// [`fillet`], its rounds turning at side edges as `turn` says.
+fn fillet_turning(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<Body> {
let _span = solidcraft_profile::span("kernel", "fillet");
body.require_brep("fillet")?;
- crate::blend_smlib::fillet(body, edges, radius).and_then(|b| closed(body, b))
+ crate::blend_smlib::fillet(body, edges, radius, turn).and_then(|b| closed(body, b))
}
-/// [`fillet`], with the picks whose edges are gone: where some of the rounds overflow their
-/// faces, those are built first, and a picked edge one of them removes whole is not rounded (the
-/// others round what is left of their edges).
-pub fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body, Vec<Vec3>)> {
+/// [`fillet`], its rounds turning at side edges as `turn` says, with the picks whose edges are
+/// gone: where some of the rounds overflow their faces, those are built first, and a picked edge
+/// one of them removes whole is not rounded (the others round what is left of their edges).
+pub fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<(Body, Vec<Vec3>)> {
let _span = solidcraft_profile::span("kernel", "fillet");
body.require_brep("fillet")?;
- let (b, gone) = crate::blend_smlib::fillet_removing(body, edges, radius)?;
+ let (b, gone) = crate::blend_smlib::fillet_removing(body, edges, radius, turn)?;
Ok((closed(body, b)?, gone))
}
@@ -515,10 +533,11 @@ fn radius_step(radius: f64) -> f64 {
/// them (a refusal of a fillet feature's exact fit runs it to name the largest that fits, and
/// so does `fit: reduce`). Only a refusal as too large
/// ([`KernelError::TooLarge`]) narrows the search: any other failure of a candidate is the
-/// search's error, since a smaller radius would not be the largest that fits.
-pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Result<Option<(f64, Body)>> {
+/// search's error, since a smaller radius would not be the largest that fits. The rounds turn at
+/// side edges as `turn` says.
+pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<Option<(f64, Body)>> {
let _span = solidcraft_profile::span("kernel", "fillet_max");
- largest_that_fits(radius, |r| fillet(body, edges, r))
+ largest_that_fits(radius, |r| fillet_turning(body, edges, r, turn))
}
/// [`fillet_max`] for an equal-distance chamfer of these edges: the largest distance below
@@ -566,21 +585,21 @@ fn largest_that_fits(size: f64, blend: impl Fn(f64) -> Result<Body>) -> Result<O
/// each reduced to fit, are too large together, or there are too many to search (each search is
/// up to 16 fillets, and this runs in the live preview). Any failure other than a refusal as too
/// large is the error.
-pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result<Option<(Vec<f64>, Body)>> {
+pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<Option<(Vec<f64>, Body)>> {
let _span = solidcraft_profile::span("kernel", "fillet_max_each");
const MAX_GROUPS: usize = 8;
const MAX_SEARCHES: usize = 2;
- let one = || -> Result<Option<(Vec<f64>, Body)>> { Ok(fillet_max(body, edges, radius)?.map(|(r, b)| (vec![r; edges.len()], b))) };
+ let one = || -> Result<Option<(Vec<f64>, Body)>> { Ok(fillet_max(body, edges, radius, turn)?.map(|(r, b)| (vec![r; edges.len()], b))) };
let Some(groups) = interacting_groups(body, edges).filter(|g| g.len() > 1 && g.len() <= MAX_GROUPS) else { return one() };
let mut radii = vec![radius; edges.len()];
let mut searches = 0;
for g in &groups {
let pts: Vec<Vec3> = g.iter().filter_map(|i| edges.get(*i).copied()).collect();
- let r = match fillet(body, &pts, radius) {
+ let r = match fillet_turning(body, &pts, radius, turn) {
Ok(_) => continue,
Err(KernelError::TooLarge(_)) if searches < MAX_SEARCHES => {
searches += 1;
- match fillet_max(body, &pts, radius)? {
+ match fillet_max(body, &pts, radius, turn)? {
Some((r, _)) => r,
None => return one(),
}
@@ -594,7 +613,7 @@ pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result<Optio
}
}
}
- match fillet_each(body, edges, &radii) {
+ match fillet_each(body, edges, &radii, turn) {
Ok(b) => Ok(Some((radii, b))),
Err(KernelError::TooLarge(_)) => one(),
Err(e) => Err(e),
@@ -603,16 +622,16 @@ pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result<Optio
/// The fillet of each edge at its own radius (`radii` in `edges`' order), all in one SMLib
/// blend.
-pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result<Body> {
+pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64], turn: FilletTurn) -> Result<Body> {
let _span = solidcraft_profile::span("kernel", "fillet_each");
if radii.len() != edges.len() {
return Err(KernelError::Invalid("one radius per edge".into()));
}
if let Some(r) = radii.first().filter(|r| radii.iter().all(|x| x.to_bits() == r.to_bits())) {
- return fillet(body, edges, *r);
+ return fillet_turning(body, edges, *r, turn);
}
body.require_brep("fillet")?;
- crate::blend_smlib::fillet_each(body, edges, radii).and_then(|b| closed(body, b))
+ crate::blend_smlib::fillet_each(body, edges, radii, turn).and_then(|b| closed(body, b))
}
/// The points' edges (each the edge a blend's pick there takes) grouped where they share a face
@@ -1599,7 +1618,7 @@ mod tests {
assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
let e = e.to_string();
assert!(e.contains("into the hollow at (0.000, 30.000, 40.000) and open the part"), "{e}");
- let (largest, _) = fillet_max(&case, &[top], 7.0).unwrap().unwrap();
+ let (largest, _) = fillet_max(&case, &[top], 7.0, FilletTurn::Mitre).unwrap().unwrap();
assert!((largest - 6.828).abs() < 1e-9, "{largest}");
// Just short of the corner it rounds, its whole section along the 104.
@@ -1613,8 +1632,8 @@ mod tests {
// inner R7's arc (centre (23, 33)) only at sqrt2 (r - 9) + 7 = r, r = 13.83.
let inside = Vec3::new(0.0, 30.0, 40.0);
assert!(fillet(&case, &[top, inside], 7.0).is_ok());
- assert!(fillet_each(&case, &[top, inside], &[13.8, 7.0]).is_ok());
- let e = fillet_each(&case, &[top, inside], &[13.9, 7.0]).unwrap_err().to_string();
+ assert!(fillet_each(&case, &[top, inside], &[13.8, 7.0], FilletTurn::Mitre).is_ok());
+ let e = fillet_each(&case, &[top, inside], &[13.9, 7.0], FilletTurn::Mitre).unwrap_err().to_string();
assert!(e.contains("into the hollow at"), "{e}");
}
diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs
index ef4efdb390..d7b72a052b 100644
--- a/crates/kernel/src/blend_corner.rs
+++ b/crates/kernel/src/blend_corner.rs
@@ -261,7 +261,7 @@ pub fn fillet_radii(body: &Body, edges: &[(Vec3, f64)]) -> Result<Body> {
return Err(KernelError::Invalid("fillet size must be positive".into()));
}
let (points, radii): (Vec<Vec3>, Vec<f64>) = edges.iter().copied().unzip();
- crate::blend_smlib::fillet_each(body, &points, &radii)
+ crate::blend_smlib::fillet_each(body, &points, &radii, crate::FilletTurn::Mitre)
}
#[cfg(test)]
diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs
index a2bddd8151..bbfbe8a5ab 100644
--- a/crates/kernel/src/blend_smlib.rs
+++ b/crates/kernel/src/blend_smlib.rs
@@ -17,7 +17,7 @@ use solidcore_record::Vec3;
use crate::blend_variable::RadiusSpline;
use crate::body::Body;
-use crate::{KernelError, Result};
+use crate::{FilletTurn, KernelError, Result};
/// What SMLib cannot build yet.
pub(crate) fn unsupported(what: &str) -> KernelError {
@@ -25,22 +25,24 @@ pub(crate) fn unsupported(what: &str) -> KernelError {
}
/// A constant-radius round of the edges nearest `edges` ([`crate::fillet`]).
-pub(crate) fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {
- imp::blend(body, "fillet", Kind::Round, edges, &vec![radius; edges.len()])
+/// The rounds turn at side edges as `turn` says.
+pub(crate) fn fillet(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<Body> {
+ imp::blend(body, "fillet", Kind::Round(turn), edges, &vec![radius; edges.len()])
}
/// [`fillet`], with the picks whose edges a larger, overflowing round removed whole.
-pub(crate) fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body, Vec<Vec3>)> {
- let (b, dropped) = imp::blend_dropping(body, "fillet", Kind::Round, edges, &vec![radius; edges.len()])?;
+pub(crate) fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64, turn: FilletTurn) -> Result<(Body, Vec<Vec3>)> {
+ let (b, dropped) = imp::blend_dropping(body, "fillet", Kind::Round(turn), edges, &vec![radius; edges.len()])?;
Ok((b, edges.iter().zip(dropped).filter(|(_, d)| *d).map(|(p, _)| *p).collect()))
}
-/// Each edge rounded at its own radius ([`crate::fillet_each`]).
-pub(crate) fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result<Body> {
+/// Each edge rounded at its own radius ([`crate::fillet_each`]), turning at side edges as `turn`
+/// says.
+pub(crate) fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64], turn: FilletTurn) -> Result<Body> {
if radii.len() != edges.len() {
return Err(KernelError::Invalid("one radius per edge".into()));
}
- imp::blend(body, "fillet", Kind::Round, edges, radii)
+ imp::blend(body, "fillet", Kind::Round(turn), edges, radii)
}
/// A constant-radius round whose corners at `setbacks` (a point at each corner's vertex, and the
@@ -63,7 +65,7 @@ pub(crate) struct OpenCorners {
/// that would fill each corner, for the caller to fill.
/// `curvature`: the rounds' sections are curvature-continuous ([`fillet_g2`]), else circular.
pub(crate) fn fillet_setback_open(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)], curvature: bool) -> Result<OpenCorners> {
- let kind = if curvature { Kind::Curvature } else { Kind::Round };
+ let kind = if curvature { Kind::Curvature } else { Kind::Round(FilletTurn::Mitre) };
imp::blend_setback_open(body, kind, edges, &vec![radius; edges.len()], setbacks)
}
@@ -104,7 +106,8 @@ pub(crate) fn picked_edges(body: &Body, picks: &[Vec3]) -> Result<(Vec<usize>, V
#[derive(Clone, Copy)]
enum Kind {
- Round,
+ /// Constant-radius rounds, turning at side edges as the [`FilletTurn`] says.
+ Round(FilletTurn),
Curvature,
Chord,
Chamfer,
@@ -115,7 +118,7 @@ mod imp {
use std::collections::BTreeSet;
use solidcore_record::Vec3;
- use solidcraft_smlib::{Blend, Brep, ChamferSecond, CheckLevel, Error as SmError};
+ use solidcraft_smlib::{Blend, Brep, ChamferSecond, CheckLevel, Error as SmError, Turn};
use super::Kind;
use crate::blend_variable::RadiusSpline;
@@ -225,13 +228,21 @@ mod imp {
/// SMLib's blend of each kind.
fn blend_kind(kind: Kind) -> Blend {
match kind {
- Kind::Round => Blend::Round,
+ Kind::Round(_) => Blend::Round,
Kind::Curvature => Blend::Curvature,
Kind::Chord => Blend::Chord,
Kind::Chamfer => Blend::Chamfer,
}
}
+ /// SMLib's turn of each kind of turn.
+ fn smlib_turn(turn: crate::FilletTurn) -> Turn {
+ match turn {
+ crate::FilletTurn::Mitre => Turn::Mitre,
+ crate::FilletTurn::Swept => Turn::Swept,
+ }
+ }
+
pub(super) fn blend(body: &Body, what: &str, kind: Kind, edges: &[Vec3], sizes: &[f64]) -> Result<Body> {
blend_dropping(body, what, kind, edges, sizes).map(|(b, _)| b)
}
@@ -243,21 +254,22 @@ mod imp {
sizes_ok(what, sizes)?;
let picked = resolve(body, edges)?;
let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?;
- if matches!(kind, Kind::Round) {
+ if matches!(kind, Kind::Round(_)) {
crate::blend::rounds_too_small(body, edges, &picked.edges, sizes)?;
crate::blend::rounds_into_hollow(body, edges, &picked.edges, sizes)?;
}
let tol = pick_tolerance(body);
- let Kind::Round = kind else {
+ let Kind::Round(turn) = kind else {
let kind = blend_kind(kind);
- return run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(kind, &picked.points, sizes, tol))
+ return run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(kind, Turn::Mitre, &picked.points, sizes, tol))
.map(|(out, dropped, _)| (out, dropped))
.map_err(|e| crate::blend::with_continuation(e, next));
};
// Constant-radius rounds: the body keeps what they were made on, and a later round at a
// corner where they meet blends them again with it (crate::blend_corner).
+ let turn = smlib_turn(turn);
let out = match crate::blend_corner::later_corners(body, &picked.edges, sizes)? {
- Some((later, new)) => reblend(body, what, &later).map(|(b, dropped_new)| {
+ Some((later, new)) => reblend(body, what, &later, turn).map(|(b, dropped_new)| {
// A picked seam has no round of its own: only the new edges can be removed.
let dropped = picked
.edges
@@ -266,7 +278,7 @@ mod imp {
.collect();
(b.with_rounds(body, new), dropped)
}),
- None => run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(Blend::Round, &picked.points, sizes, tol))
+ None => run_with(body, what, &picked.edges, &[], |b| b.blend_dropping(Blend::Round, turn, &picked.points, sizes, tol))
.map(|(out, dropped, _)| (out.with_rounds(body, picked.edges.iter().copied().zip(sizes.iter().copied()).collect()), dropped)),
};
out.map_err(|e| crate::blend::with_continuation(e, next))
@@ -275,8 +287,9 @@ mod imp {
/// The blend `later` makes of its base, every round from the earliest meeting the new edges'
/// corners on and the new edges in one, with its history over `body`, the body the later
/// round was given ([`crate::blend_corner::rebase`]), and whether each new edge (in
- /// `later`'s order) was removed whole by a larger, overflowing round.
- fn reblend(body: &Body, what: &str, later: &crate::blend_corner::Later) -> Result<(Body, Vec<bool>)> {
+ /// `later`'s order) was removed whole by a larger, overflowing round. The rounds turn at side
+ /// edges as `turn` says.
+ fn reblend(body: &Body, what: &str, later: &crate::blend_corner::Later, turn: Turn) -> Result<(Body, Vec<bool>)> {
let base = &later.base;
let mesh = base.mesh(&crate::MeshTolerance::chord((base.size() * 2e-3).max(1e-3)))?;
let mut indices = Vec::with_capacity(later.edges.len());
@@ -291,7 +304,7 @@ mod imp {
}
sizes_ok(what, &radii)?;
let tol = pick_tolerance(base);
- let (out, dropped, _) = run_with(base, what, &indices, &[], |b| b.blend_dropping(Blend::Round, &points, &radii, tol))?;
+ let (out, dropped, _) = run_with(base, what, &indices, &[], |b| b.blend_dropping(Blend::Round, turn, &points, &radii, tol))?;
// The new edges are the last of `later.edges`.
let dropped_new = dropped.get(dropped.len().saturating_sub(later.new_count())..).map(<[bool]>::to_vec).unwrap_or_default();
let history = out.history().and_then(|h| crate::blend_corner::rebase(h, later, body));
@@ -446,6 +459,11 @@ mod imp {
run on tangentially into each other, or meet in a way no blend corner builds)"
)),
SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")),
+ // Not a size a smaller radius fixes: solidcore builds no swept turn there.
+ SmError::TurnRefused { why, at, .. } => {
+ let at = at.map(|[x, y, z]| format!(" at ({x:.3}, {y:.3}, {z:.3})")).unwrap_or_default();
+ KernelError::Invalid(format!("the {what}'s swept corner{at} is not built: {why}"))
+ }
SmError::TooLarge { size, kind, at, why } => {
let mut beside = match at {
Some([x, y, z]) => format!(", at the edge at ({x:.3}, {y:.3}, {z:.3})"),
@@ -594,7 +612,7 @@ mod tests {
fn a_round_loses_its_corner_and_its_face_comes_from_the_edge() {
let b = cube();
let at = Vec3::new(10.0, 20.0, 20.0);
- let r = imp::blend(&b, "fillet", Kind::Round, &[at], &[2.0]).unwrap();
+ let r = imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[at], &[2.0]).unwrap();
assert!(near(volume(&r), 8000.0 - QUARTER * 4.0 * 20.0), "{}", volume(&r));
assert_eq!(r.face_count(), 7);
let h = r.history().expect("a history");
@@ -608,8 +626,8 @@ mod tests {
// (20, 20, 10) is on the vertical edge only; (20, 20, 20) is a corner of three edges, which
// the body's own order resolves, never left to SMLib.
let b = cube();
- assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(20.0, 20.0, 20.0)], &[1.0]).is_ok());
- assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(60.0, 60.0, 60.0)], &[1.0]).is_err());
+ assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(20.0, 20.0, 20.0)], &[1.0]).is_ok());
+ assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(60.0, 60.0, 60.0)], &[1.0]).is_err());
}
/// A ball's rim on a block's back face, tangent to the back face's bottom edge at (2.5, 22.5, 0).
@@ -677,7 +695,7 @@ mod tests {
fn each_edge_takes_its_own_size() {
let b = cube();
let picks = [Vec3::new(10.0, 20.0, 20.0), Vec3::new(10.0, 0.0, 20.0)];
- let r = imp::blend(&b, "fillet", Kind::Round, &picks, &[2.0, 3.0]).unwrap();
+ let r = imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &picks, &[2.0, 3.0]).unwrap();
assert!(near(volume(&r), 8000.0 - QUARTER * 13.0 * 20.0), "{}", volume(&r));
let c = imp::blend(&b, "chamfer", Kind::Chamfer, &picks, &[2.0, 3.0]).unwrap();
assert!(near(volume(&c), 8000.0 - 0.5 * 13.0 * 20.0), "{}", volume(&c));
@@ -750,9 +768,9 @@ mod tests {
// A radius law down to zero inside the edge would pinch the round to a point.
let pinch = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 0.5, 1.0, 1.0], radii: vec![4.0, 0.0, 4.0] };
assert!(imp::variable(&b, Vec3::new(10.0, 20.0, 20.0), Vec3::new(0.0, 20.0, 20.0), &pinch).is_err());
- assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(10.0, 20.0, 20.0)], &[f64::NAN]).is_err());
- assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(f64::NAN, 20.0, 20.0)], &[1.0]).is_err());
- assert!(imp::blend(&b, "fillet", Kind::Round, &[], &[]).is_err());
+ assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(10.0, 20.0, 20.0)], &[f64::NAN]).is_err());
+ assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(f64::NAN, 20.0, 20.0)], &[1.0]).is_err());
+ assert!(imp::blend(&b, "fillet", Kind::Round(FilletTurn::Mitre), &[], &[]).is_err());
}
/// A smooth edge (a round's seam with the face it runs into) has nothing to round: refused
@@ -764,30 +782,30 @@ mod tests {
#[test]
fn smooth_edges_and_unfinished_tangent_chains_are_refused_saying_why() {
let b = cube();
- let rounded = fillet(&b, &[Vec3::new(10.0, 20.0, 20.0)], 3.0).unwrap();
+ let rounded = fillet(&b, &[Vec3::new(10.0, 20.0, 20.0)], 3.0, FilletTurn::Mitre).unwrap();
// the seam where the r3 round meets the top, 3 in from the old edge
- let seam = imp::blend(&rounded, "fillet", Kind::Round, &[Vec3::new(10.0, 17.0, 20.0)], &[1.0]).unwrap_err().to_string();
+ let seam = imp::blend(&rounded, "fillet", Kind::Round(FilletTurn::Mitre), &[Vec3::new(10.0, 17.0, 20.0)], &[1.0]).unwrap_err().to_string();
assert!(seam.contains("is smooth: its faces meet tangentially, so there is nothing to round"), "{seam}");
// the end face's top edge runs on tangentially into the round's end arc: its r1 round
// goes on along y through the r3 round until that drops below it, at y = 17 + sqrt(5)
// (the rig case's closed form: 8000 - 20 (9 - 9 pi/4) - 17 (1 - pi/4) - 0.218236)
let top = Vec3::new(0.0, 8.0, 20.0);
- let alone = fillet(&rounded, &[top], 1.0).unwrap();
+ let alone = fillet(&rounded, &[top], 1.0, FilletTurn::Mitre).unwrap();
assert!((volume(&alone) - 7957.505202).abs() < 1e-3, "{}", volume(&alone));
let chain = crate::tangent_chain(&rounded, &[top]).unwrap();
assert!(chain.len() > 1, "{chain:?}");
- let whole = fillet(&rounded, &chain, 1.0).unwrap();
+ let whole = fillet(&rounded, &chain, 1.0, FilletTurn::Mitre).unwrap();
assert!(volume(&whole) < volume(&rounded));
// r5 and r3 on two top edges at a corner, then r2 on the vertical edge under them: it
// runs on up the r5 round's end arc, and SMLib ends it there
let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap();
- let b = fillet(&b, &[Vec3::new(30.0, 40.0, 20.0)], 5.0).unwrap();
- let b = fillet(&b, &[Vec3::new(60.0, 20.0, 20.0)], 3.0).unwrap();
+ let b = fillet(&b, &[Vec3::new(30.0, 40.0, 20.0)], 5.0, FilletTurn::Mitre).unwrap();
+ let b = fillet(&b, &[Vec3::new(60.0, 20.0, 20.0)], 3.0, FilletTurn::Mitre).unwrap();
let vertical = Vec3::new(60.0, 40.0, 8.0);
let chain = crate::tangent_chain(&b, &[vertical]).unwrap();
assert!(chain.len() > 1, "{chain:?}");
- let run_on = fillet(&b, &[vertical], 2.0).unwrap();
+ let run_on = fillet(&b, &[vertical], 2.0, FilletTurn::Mitre).unwrap();
assert!(volume(&run_on) < volume(&b));
}
}
diff --git a/crates/kernel/src/issue_1080_tests.rs b/crates/kernel/src/issue_1080_tests.rs
index 9b3c3fc762..f1f30e32e4 100644
--- a/crates/kernel/src/issue_1080_tests.rs
+++ b/crates/kernel/src/issue_1080_tests.rs
@@ -88,7 +88,7 @@ fn chamfers_crossing_each_other_are_refused() {
too_large(crate::chamfer(&rib, &edges, 3.0));
too_large(crate::fillet(&rib, &edges, 3.0));
assert_eq!(crate::chamfer_max(&rib, &edges, 3.0).unwrap().map(|x| x.0), Some(2.0));
- assert_eq!(crate::fillet_max(&rib, &edges, 3.0).unwrap().map(|x| x.0), Some(2.0));
+ assert_eq!(crate::fillet_max(&rib, &edges, 3.0, crate::FilletTurn::Mitre).unwrap().map(|x| x.0), Some(2.0));
// Below half the width both build.
let b = crate::chamfer(&rib, &edges, 1.5).unwrap();
assert!((b.volume_at(0.01).unwrap() - (3200.0 - 2.0 * 0.5 * 1.5 * 1.5 * 40.0)).abs() < 1e-6);
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 54a83b3c57..6ee0794b8d 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -156,7 +156,7 @@ mod validity;
pub mod watch;
pub use blend::{
- ChamferSide, SETBACK_AT_LEAST, blend_edges, chamfer, chamfer_max, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners,
+ ChamferSide, FilletTurn, SETBACK_AT_LEAST, blend_edges, chamfer, chamfer_max, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners,
fillet_g2_with_g2_corners, fillet_least_setback, fillet_max, fillet_max_each, fillet_removing, fillet_setback, largest_fit_note,
names_largest_fit, tangent_chain, with_fit_note,
};
diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs
index ec600e11b9..cb0493222c 100644
--- a/crates/kernel/src/tests.rs
+++ b/crates/kernel/src/tests.rs
@@ -331,14 +331,14 @@ fn fillet_max_finds_the_largest_radius_that_works() {
let b = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap();
let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)];
assert!(too_large(&b, &mids, 3.5));
- let (r, body) = fillet_max(&b, &mids, 3.5).unwrap().unwrap();
+ let (r, body) = fillet_max(&b, &mids, 3.5, FilletTurn::Mitre).unwrap().unwrap();
assert_eq!(r, 3.0);
assert!(rel(measure(&body).unwrap().volume, 840.0 - (4.0 - PI) * 90.0) < 2e-4);
// No edge there: the fillet's own error, not a smaller radius (only a refusal as too large
// narrows the search).
let e = fillet(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0).unwrap_err();
assert!(!matches!(e, KernelError::TooLarge(_)), "{e}");
- assert_eq!(fillet_max(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0).unwrap_err().to_string(), e.to_string());
+ assert_eq!(fillet_max(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0, FilletTurn::Mitre).unwrap_err().to_string(), e.to_string());
}
/// Edges that share no face get their own largest radius: a 2 mm fin's top edge takes at most
@@ -360,7 +360,7 @@ fn fillet_max_each_reduces_only_where_the_radius_does_not_fit() {
// at its edge less the quarter disc about (17, 26), inside the fin (x >= 19): 2 x 4 less the
// disc's part, in closed form; the corner's round (1 − π/4)·16 along 20.
let both = fillet(&body, &edges, 4.0).unwrap();
- let (radii, b) = fillet_max_each(&body, &edges, 4.0).unwrap().unwrap();
+ let (radii, b) = fillet_max_each(&body, &edges, 4.0, FilletTurn::Mitre).unwrap().unwrap();
assert_eq!(radii, vec![4.0, 4.0], "{radii:?}");
assert!(b.validity().is_empty(), "{:?}", b.validity());
let disc = |a: f64| 0.5 * (a * (16.0 - a * a).max(0.0).sqrt() + 16.0 * (a / 4.0).asin());
@@ -371,7 +371,7 @@ fn fillet_max_each_reduces_only_where_the_radius_does_not_fit() {
// The post's four edges limit each other: one radius, as `fillet_max`.
let post = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap();
let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)];
- assert_eq!(fillet_max_each(&post, &mids, 3.5).unwrap().map(|x| x.0), Some(vec![3.0; 4]));
+ assert_eq!(fillet_max_each(&post, &mids, 3.5, FilletTurn::Mitre).unwrap().map(|x| x.0), Some(vec![3.0; 4]));
}
/// R21 on an edge of a 20 mm cube overflows on its tangent sides, which a round may, taking all
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index a5df10c952..ed7e114db0 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -3480,9 +3480,9 @@ fn a_bridged_server_checks_calls_at_its_param_check_level() {
assert_eq!(r["result"]["isError"], json!(true), "{r}");
assert!(text(&r).contains(&format!("invalid parameters for `solid.box`: {warning}")), "{r}");
assert_eq!(sent("engine.execute solid.box"), 0, "refused unsent");
- let r = raw_tool(&mut s, "execute", json!({"command": "solid.fillet", "params": {"nonsense": 1}}));
+ let r = raw_tool(&mut s, "execute", json!({"command": "solid.chamfer", "params": {"nonsense": 1}}));
assert_ne!(r["result"]["isError"], json!(true), "{r}");
- assert_eq!(sent("engine.execute solid.fillet"), 1, "no contract here: the app decides");
+ assert_eq!(sent("engine.execute solid.chamfer"), 1, "no contract here: the app decides");
let r = raw_tool(&mut s, "batch", json!({"commands": [good, misspelt]}));
assert_eq!(r["result"]["isError"], json!(true), "{r}");
let reply: Value = serde_json::from_str(&text(&r)).unwrap();
diff --git a/crates/smlib/src/core/blend.rs b/crates/smlib/src/core/blend.rs
index 76965069ff..930927751e 100644
--- a/crates/smlib/src/core/blend.rs
+++ b/crates/smlib/src/core/blend.rs
@@ -53,7 +53,7 @@ use solidcore::topology::topology_traverser::Marks;
use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId, FaceuseId, VertexId, edge, vertex};
use super::{Body, answer};
-use crate::{Blend, ChamferSecond, Error, Hole, HoleEdge, MAX_POINTS, Result};
+use crate::{Blend, ChamferSecond, Error, Hole, HoleEdge, MAX_POINTS, Result, Turn};
/// Why solidcore refuses the 3x2 mixed-convexity corner whose rails cross
/// (`fixes.fillet_refuse_mixed_corner_crossing_rails`, [`MIXED_CORNER_RAILS_CROSS`]): it builds no
@@ -248,7 +248,9 @@ fn chamfer_radius(k: &Kernel, b: &mut Brep, e: EdgeId, distance: f64) -> solidco
/// What `round_edges` makes: the capi's kinds less the chamfer, which `chamfer_offsets` makes.
#[derive(Clone, Copy, PartialEq)]
enum Section<'a> {
- Round,
+ /// A circular section of constant radius (or of a variable radius's law), the turns of two
+ /// such rounds at a side edge as the [`Turn`] says (`SetSweptTurns`).
+ Round(Turn),
/// The curvature-continuous section (`SM_FSG_BLEND_CURVE`): the Gⁿ generator's order 2 at the
/// equal-area thumbweight (`SMLIB_BLEND_THUMBWEIGHT`, fork 6148773; solidcore#2261 under
/// `fillet_gn_section_generator`), which takes off what the ball's circle does.
@@ -338,6 +340,23 @@ fn room_reason(r: NoRoomReason) -> Option<crate::RoomReason> {
})
}
+/// The refusal of a swept turn `CreateFilletCorners` noted at its vertex (`SmBlendCorner::Classify`
+/// with `GetSweptTurns()`): [`Error::TurnRefused`] with solidcore's reason, without its "Fillet
+/// Error: " prefix, and where it is; `None` for a note of another kind.
+fn turn_refusal(info: &ErrorInfo<FilletObject>) -> Option<Error> {
+ let room = match info.code {
+ c if c == FilletErrorType::NoRoom as i32 => true,
+ c if c == FilletErrorType::CornerUnsupported as i32 => false,
+ _ => return None,
+ };
+ let why = info.comment.trim();
+ if why.is_empty() {
+ return None;
+ }
+ let why = why.strip_prefix("Fillet Error:").map_or(why, str::trim_start).to_owned();
+ Some(Error::TurnRefused { room, why, at: info.location.map(|p| [p.x, p.y, p.z]) })
+}
+
/// [`blend_failure`] where solidcore gives no size.
fn blend_failure_unsized(info: &ErrorInfo<FilletObject>, e: SolidError, corner: bool) -> Error {
if e.is_unported() {
@@ -433,13 +452,16 @@ fn blend_edges_stopping(
let mut fit_edge = None;
let done = {
let mut s = FilletSession::new(k, b)?;
+ // `SetSweptTurns`: read as the corners are made (`fixes.fillet_blend_corner`).
+ let swept = section == Section::Round(Turn::Swept);
+ s.set_swept_turns(swept);
// `SetFilletParameters(b, es, sections, solvers, values, laws, -1, -1, -1, -1,
// continuity 1, thumbweight 1)`: the session sets the executive's global merge first, as
// `SmApiFilletEdges` does, and `SetFilletParameters` resets it, as in the capi.
let prepared = match (section, law) {
- (Section::Round, None) => s.prepare_per_edge_constant_radius(k, edges, sizes, &[FilletSurfaceGeneratorType::Circular], 1, 1.0),
+ (Section::Round(_), None) => s.prepare_per_edge_constant_radius(k, edges, sizes, &[FilletSurfaceGeneratorType::Circular], 1, 1.0),
// The size is the start radius (`smlib_fillet_variable`).
- (Section::Round, Some(law)) => match sizes.first() {
+ (Section::Round(_), Some(law)) => match sizes.first() {
Some(&size) => s.prepare_variable_radius_edges(k, edges, size, law, 1, 1),
None => return Ok(Err(Err(Error::Argument))),
},
@@ -459,7 +481,10 @@ fn blend_edges_stopping(
s.add_set_back_vertex(sb.vertex);
}
}
+ let prepared_ok = prepared.is_ok();
let mut step = prepared.and_then(|()| s.create_corners(k, None)).map(|()| Ok(Vec::new()));
+ // A swept turn `CreateFilletCorners` refused, with solidcore's reason ([`turn_refusal`]).
+ let refused_turn = if swept && prepared_ok && step.is_err() { turn_refusal(s.error_info()) } else { None };
// A vertex `CreateFilletCorners` made no corner for, noted before a later step notes its
// own failure over it ([`blend_failure`]).
let corner = step.is_ok() && s.error_info().code == FilletErrorType::CornerUnsupported as i32;
@@ -488,11 +513,14 @@ fn blend_edges_stopping(
}
},
Ok(Err(refusal)) => Ok(Err(refusal)),
- Err(e) => {
- let (why, edge) = blend_failure(&s, e, corner);
- fit_edge = edge;
- Ok(Err(Err(why)))
- }
+ Err(e) => match refused_turn {
+ Some(why) => Ok(Err(Err(why))),
+ None => {
+ let (why, edge) = blend_failure(&s, e, corner);
+ fit_edge = edge;
+ Ok(Err(Err(why)))
+ }
+ },
}
};
let done: solidcore::Result<std::result::Result<(Vec<usize>, Vec<(usize, FaceId)>), std::result::Result<usize, Error>>> = done;
@@ -825,9 +853,9 @@ pub(crate) fn blend(
/// `smlib_blend_dropping`: [`blend`] with one size per point, no corners, and per point whether it
/// picked an edge that a larger round, overflowing its faces, removed whole.
-pub(crate) fn blend_dropping(body: &Body, kind: Blend, points: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Body, Vec<bool>)> {
+pub(crate) fn blend_dropping(body: &Body, kind: Blend, turn: Turn, points: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Body, Vec<bool>)> {
let mut dropped = vec![false; points.len()];
- let (b, _) = blend_call(body, kind, points, sizes, tolerance, &[], &[], Corners::Filled, &mut dropped)?;
+ let (b, _) = blend_call(body, kind, turn, points, sizes, tolerance, &[], &[], Corners::Filled, &mut dropped)?;
Ok((b, dropped))
}
@@ -846,15 +874,17 @@ pub(crate) fn blend_holes(
setbacks: &[f64],
open: Corners,
) -> Result<(Body, Vec<Hole>)> {
- blend_call(body, kind, points, sizes, tolerance, corners, setbacks, open, &mut vec![false; points.len()])
+ blend_call(body, kind, Turn::Mitre, points, sizes, tolerance, corners, setbacks, open, &mut vec![false; points.len()])
}
/// `blend_call`: [`blend_holes`], with per point in `dropped` whether it picked an edge an
-/// overflowing round removed whole ([`overflow_first`]).
+/// overflowing round removed whole ([`overflow_first`]), and the rounds' turns at side edges as
+/// `turn` says (a swept turn is for [`Blend::Round`] only).
#[allow(clippy::too_many_arguments)] // the capi's blend_call
fn blend_call(
body: &Body,
kind: Blend,
+ turn: Turn,
points: &[[f64; 3]],
sizes: &[f64],
tolerance: f64,
@@ -869,6 +899,7 @@ fn blend_call(
|| !(one_size || sizes.len() == points.len())
|| !points_ok(corners, true)
|| setbacks.len() != corners.len()
+ || (turn == Turn::Swept && kind != Blend::Round)
{
return Err(Error::Argument);
}
@@ -898,7 +929,7 @@ fn blend_call(
}
let solid_in = brep_p2::is_manifold_solid(&w)?;
let section = match kind {
- Blend::Round => Section::Round,
+ Blend::Round => Section::Round(turn),
// Every edge of one call takes the equal-area thumbweight of the first's wedge
// (solidcore#2250's comment 6563419897): edges of other wedges would take off another
// area than their own, so they are not built together.
@@ -1380,7 +1411,7 @@ pub(crate) fn fillet_variable(
// (`NoRoomReason::BallsFold`), [`Error::NoRoom`].
let solid_in = brep_p2::is_manifold_solid(&w)?;
let (r0, r1) = (radii.first().copied().unwrap_or(0.0), radii.last().copied().unwrap_or(0.0));
- Ok(match blend_edges(k, &mut w, &[e], &[r0.max(r1)], Section::Round, Some(law), &[], None)? {
+ Ok(match blend_edges(k, &mut w, &[e], &[r0.max(r1)], Section::Round(Turn::Mitre), Some(law), &[], None)? {
Ok(()) => finish(w, solid_in)?,
Err(Ok(_)) => Err(Error::Unsupported),
Err(Err(e)) => Err(e),
diff --git a/crates/smlib/src/core/blend_tests.rs b/crates/smlib/src/core/blend_tests.rs
index f9d80d69ec..e620c1b3e7 100644
--- a/crates/smlib/src/core/blend_tests.rs
+++ b/crates/smlib/src/core/blend_tests.rs
@@ -12,7 +12,7 @@ use super::blend::{Corners, blend, blend_dropping, blend_holes, chamfer_sides, f
use super::boolean::boolean;
use super::{Body, counts, make_box, make_cylinder, to_arrays, volume};
use crate::export::native;
-use crate::{Blend, BooleanOp, ChamferSecond, Error};
+use crate::{Blend, BooleanOp, ChamferSecond, Error, Turn};
/// A case longer than this is a hang.
const TIMEOUT: Duration = Duration::from_secs(300);
@@ -399,7 +399,7 @@ fn overflow_goes_first() {
];
for (points, sizes, dropped, want, bound) in cases {
let got = timed("overflow_first", move || {
- let (b, d) = blend_dropping(&Shape::Box([0.0; 3], [20.0; 3]).core(), Blend::Round, points, sizes, 1.0).unwrap();
+ let (b, d) = blend_dropping(&Shape::Box([0.0; 3], [20.0; 3]).core(), Blend::Round, Turn::Mitre, points, sizes, 1.0).unwrap();
native(&to_arrays(&b).unwrap()).unwrap();
(volume(&b, 1e-8).unwrap(), d)
});
@@ -445,6 +445,71 @@ fn rounds_at_a_concave_face_corner_are_mitred() {
assert!(rel(got, v) < 1e-8, "{got} vs {v}");
}
+/// A 40 x 30 x 10 plate with a 10 x 10 x 5 boss on it (x 15..25, y 10..20), the boss's four base
+/// edges rounded at r 1: at each upright boss edge two concave rounds turn round the sharp convex
+/// edge. Each base edge gains the spandrel A = (1 - π/4) r² along its 10, and each corner the
+/// rounds' part beyond both walls, whose section's first moment about the upright edge is
+/// M = (5/6 - π/4) r³: mitred, 8 M in all; swept, the section revolved a quarter turn at each,
+/// 2π M, the corner a horn torus of radii r, r. Swept with unequal radii, or along a pocket's floor
+/// (its upright edges sharp and concave), is refused with solidcore's reason.
+#[test]
+fn rounds_turning_round_a_boss_edge_mitred_or_swept() {
+ let made = |a: Body, b: Body, op| boolean(&a, &b, op).unwrap().unwrap();
+ let boss =
+ move || made(make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), make_box([15.0, 10.0, 10.0], [10.0, 10.0, 5.0]).unwrap(), BooleanOp::Union);
+ let pocket =
+ move || made(make_box([0.0; 3], [40.0, 30.0, 10.0]).unwrap(), make_box([10.0, 10.0, 5.0], [20.0, 10.0, 6.0]).unwrap(), BooleanOp::Subtract);
+ const BASE: [[f64; 3]; 4] = [[20.0, 10.0, 10.0], [25.0, 15.0, 10.0], [20.0, 20.0, 10.0], [15.0, 15.0, 10.0]];
+ const RIM: [[f64; 3]; 4] = [[20.0, 10.0, 5.0], [30.0, 15.0, 5.0], [20.0, 20.0, 5.0], [10.0, 15.0, 5.0]];
+ let r = 1.0;
+ let rounded =
+ move |body: Body, at: [[f64; 3]; 4], turn, sizes: [f64; 4]| blend_dropping(&body, Blend::Round, turn, &at, &sizes, 0.1).map(|(b, _)| b);
+ // solidcore's tori, and the record's kinds of surface: its torus is a ring torus, so a horn
+ // torus's face there is its exact rational form.
+ let measured = |b: &Body| {
+ use solidcore::surface::surface::p2::SurfaceKind;
+ let (rec, _) = native(&to_arrays(b).unwrap()).unwrap();
+ rec.validate().unwrap();
+ let mut tori = Vec::new();
+ {
+ let g = b.0.lock().unwrap();
+ for f in solidcore::query::api_queries::get_faces(&g).unwrap() {
+ if let Some(s) = solidcore::topology::face::p2::surface(&g, f).unwrap()
+ && let SurfaceKind::Torus(t) = s.kind()
+ {
+ tori.push((t.major_radius(), t.minor_radius()));
+ }
+ }
+ }
+ (volume(b, 1e-10).unwrap(), counts(b).unwrap()[0], tori, kinds(&rec))
+ };
+ let (mitre, swept) =
+ timed("turn", move || (rounded(boss(), BASE, Turn::Mitre, [r; 4]).unwrap(), rounded(boss(), BASE, Turn::Swept, [r; 4]).unwrap()));
+ let (vm, fm, tm, km) = measured(&mitre);
+ let (vs, fs, ts, ks) = measured(&swept);
+ println!("mitre: {vm:.9}, {fm} faces {km:?}; swept: {vs:.9}, {fs} faces {ks:?}, tori {ts:?}");
+ let (a, m) = (spandrel(r), (5.0 / 6.0 - PI / 4.0) * r * r * r);
+ let base = 12500.0 + 40.0 * a;
+ assert!(rel(vm, base + 8.0 * m) < 1e-9, "mitre {vm} vs {}", base + 8.0 * m);
+ assert!(rel(vs, base + 2.0 * PI * m) < 1e-9, "swept {vs} vs {}", base + 2.0 * PI * m);
+ assert_eq!((fm, tm.len(), km.get("rational_spline")), (15, 0, None));
+ assert_eq!((fs, ts.len(), ks.get("rational_spline")), (19, 4, Some(&4)));
+ assert!(ts.iter().all(|(major, minor)| (major - r).abs() < 1e-12 && (minor - r).abs() < 1e-12), "{ts:?}");
+ // Swept is for rounds only.
+ assert_eq!(blend_dropping(&boss(), Blend::Chamfer, Turn::Swept, &BASE, &[r; 4], 0.1).err(), Some(Error::Argument));
+ let unequal = timed("turn unequal", move || rounded(boss(), BASE, Turn::Swept, [1.0, 1.5, 1.0, 1.5]).err());
+ let rim = timed("turn rim", move || rounded(pocket(), RIM, Turn::Swept, [r; 4]).err());
+ println!("unequal: {unequal:?}\nrim: {rim:?}");
+ assert!(
+ matches!(&unequal, Some(Error::TurnRefused { room: false, why, at: Some(_) }) if why.starts_with("a swept turn is built between constant rounds of one radius")),
+ "{unequal:?}"
+ );
+ assert!(
+ matches!(&rim, Some(Error::TurnRefused { room: true, why, at: Some(_) }) if why.contains("round that edge at a radius of at least 1 first")),
+ "{rim:?}"
+ );
+}
+
/// Solidcore alone: edge attributes across a cliff overflow. A 40 x 30 x 10 block notched below its
/// top at (40, 0), its front and right top edges rounded r8 (their rails run off over the notch).
/// The back and left top edges are each trimmed 8 by those rounds: (0, 30)-(32, 30) and (0, 8)-(0, 30)
diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs
index 8d04758c86..3a29a19a76 100644
--- a/crates/smlib/src/lib.rs
+++ b/crates/smlib/src/lib.rs
@@ -25,7 +25,7 @@ pub mod trim;
pub use check::{CheckLevel, CheckReport};
pub use measure::{MEASURE_ACCURACY, MassProperties, PointClass};
-pub use ops::{Blend, BooleanOp, ChamferSecond, Hole, HoleEdge, MAX_POINTS, MAX_UNION_BREPS};
+pub use ops::{Blend, BooleanOp, ChamferSecond, Hole, HoleEdge, MAX_POINTS, MAX_UNION_BREPS, Turn};
/// Why an SMLib call failed.
#[derive(Clone, Debug, PartialEq)]
@@ -61,6 +61,11 @@ pub enum Error {
Unsupported,
/// A blend's edges meet at a vertex of a kind no SMLib blend corner handles yet.
CornerUnsupported,
+ /// A swept turn ([`Turn::Swept`]) solidcore does not build at the corner `at`: `room` where
+ /// no radius builds it (a sharp concave side edge between the rounds, solidcore's `NoRoom`),
+ /// else not supported there (`CornerUnsupported`: unequal or variable rounds, a corner of
+ /// four edges, a curved, drafted or tangent side edge); `why` is solidcore's reason.
+ TurnRefused { room: bool, why: String, at: Option<[f64; 3]> },
/// SMLib does not set back the corner of corner point `corner`: SMLib sets back a corner
/// only where every edge meeting it is blended and they are all convex or all concave.
CornerRefused { corner: usize },
@@ -192,6 +197,13 @@ impl std::fmt::Display for Error {
}
Error::Unsupported => write!(f, "not supported yet: SMLib cannot build this exactly"),
Error::CornerUnsupported => write!(f, "not supported yet: a corner of this kind is not supported yet by SMLib's blends"),
+ Error::TurnRefused { why, at, .. } => {
+ write!(f, "the swept corner is not built")?;
+ if let Some([x, y, z]) = at {
+ write!(f, " at ({x:.3}, {y:.3}, {z:.3})")?;
+ }
+ write!(f, ": {why}")
+ }
Error::CornerRefused { corner } => write!(
f,
"not supported yet: SMLib does not set back corner {}: it sets back a corner only where every edge meeting it is blended, all convex or all concave",
diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs
index a23292ddfa..bbe352d923 100644
--- a/crates/smlib/src/ops.rs
+++ b/crates/smlib/src/ops.rs
@@ -58,6 +58,30 @@ impl Blend {
}
}
+/// How two constant rounds of one radius turn round a sharp, straight, convex side edge square to
+/// both on a plane (the rounds along a boss's base, at its upright edges): the turn of
+/// [`Brep::blend_dropping`]'s rounds ([`Blend::Round`] only).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Turn {
+ /// The rounds run on to where they cross and meet in a mitre, the plane section of the two.
+ #[default]
+ Mitre,
+ /// The rounds end on their sections at the side edge, and the corner's face is that section
+ /// revolved about the side edge, an exact torus tangent to both rounds. A corner where this
+ /// is not built is [`Error::TurnRefused`].
+ Swept,
+}
+
+impl Turn {
+ /// The turn's name in a trace ([`crate::trace`]).
+ pub fn word(self) -> &'static str {
+ match self {
+ Turn::Mitre => "mitre",
+ Turn::Swept => "swept",
+ }
+ }
+}
+
/// The second side of [`Brep::chamfer_sides`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChamferSecond {
@@ -172,18 +196,19 @@ impl Brep {
/// [`Brep::blend`], with whether each point picked an edge that a larger round, overflowing
/// its faces, removed whole: that edge is gone and not rounded (SMLib rounds the edges whose
- /// blends overflow first, then what is left of the others).
- pub fn blend_dropping(&self, kind: Blend, edges: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Brep, Vec<bool>)> {
+ /// blends overflow first, then what is left of the others). Two rounds turn at a side edge as
+ /// `turn` says; [`Turn::Swept`] is for [`Blend::Round`] only ([`Error::Argument`] otherwise).
+ pub fn blend_dropping(&self, kind: Blend, turn: Turn, edges: &[[f64; 3]], sizes: &[f64], tolerance: f64) -> Result<(Brep, Vec<bool>)> {
if edges.len() > MAX_POINTS || edges.is_empty() || sizes.len() != edges.len() {
return Err(Error::Argument);
}
- let r = core::blend::blend_dropping(self.core(), kind, edges, sizes, tolerance).map(|(b, d)| (Brep::made_core(b), d));
+ let r = core::blend::blend_dropping(self.core(), kind, turn, edges, sizes, tolerance).map(|(b, d)| (Brep::made_core(b), d));
trace::call(
"blend_dropping",
&[self],
&r,
|(b, _)| vec![b.id],
- || json!({"kind": kind.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes}),
+ || json!({"kind": kind.word(), "turn": turn.word(), "edges": trace::picks(self, PickKind::Edge, edges, tolerance), "sizes": sizes}),
);
r
}
diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rs
index 3820990a85..aaafbcdd36 100644
--- a/crates/smlib/src/tests.rs
+++ b/crates/smlib/src/tests.rs
@@ -191,7 +191,7 @@ fn every_entry_point_is_in_the_guard() {
fn every_entry_point_answers() {
use crate::sweeps::{Affine, Curve, DraftCorner, Ends, SweepFrame};
use crate::trim::{Continuation, Holes};
- use crate::{Blend, BooleanOp, ChamferSecond, CheckLevel};
+ use crate::{Blend, BooleanOp, ChamferSecond, CheckLevel, Turn};
fn says<T>(_name: &str, r: Result<T>) -> Option<T> {
r.ok()
}
@@ -222,7 +222,7 @@ fn every_entry_point_answers() {
says("fillet", a.fillet(&edge, 0.1, 1.0));
says("chamfer", a.chamfer(&edge, 0.1, 1.0));
says("blend", a.blend(Blend::Round, &edge, &[1.0], 0.1));
- says("blend_dropping", a.blend_dropping(Blend::Round, &edge, &[1.0], 0.1));
+ says("blend_dropping", a.blend_dropping(Blend::Round, Turn::Mitre, &edge, &[1.0], 0.1));
let corner = [p(10.0, 10.0, 10.0)];
let three = [p(5.0, 10.0, 10.0), p(10.0, 5.0, 10.0), p(10.0, 10.0, 5.0)];
says("blend_setback", a.blend_setback(Blend::Round, &three, &[1.0; 3], &corner, &[2.0], 0.1));
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 0b71595e91..b766acac05 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -6316,6 +6316,11 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
{
d.extra.insert("corner".into(), json!("g2"));
}
+ if let FeatureKind::Fillet { turn, .. } = &f.kind
+ && !turn.is_mitre()
+ {
+ d.extra.insert("turn".into(), json!("swept"));
+ }
// A fillet that reduces or tapers a radius too large for its edges.
if let FeatureKind::Fillet { fit, .. } = &f.kind {
use solidcraft_engine::doc::FilletFit;
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index 2cb85551cd..bb53620966 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -134,13 +134,17 @@ fn fillet_corner_tip() -> String {
/// radius and narrow it only where the faces run out.
const FILLET_FITS: [(&str, &str); 3] = [("ui.fillet_fit_exact", "exact"), ("ui.fillet_fit_reduce", "reduce"), ("ui.fillet_fit_taper", "taper")];
+/// How two rounds turn where they meet at a sharp corner edge (`turn`): in a mitre (the
+/// default) or swept round the edge.
+const FILLET_TURNS: [(&str, &str); 2] = [("ui.fillet_turn_mitre", "mitre"), ("ui.fillet_turn_swept", "swept")];
+
/// Which fillet options apply together, exactly as `solid.fillet` takes them (`fillet` in
/// crates/engine/src/cmd/features.rs):
///
-/// | Type | Face limits (`fit`) | Corners (`corner`) | Setback (`setbacks`) |
-/// |---------------|-------------------------|-------------------------------------|----------------------|
-/// | Constant | exact, reduce or taper | tangent; curvature with exact only | with curvature only |
-/// | any other | exact (not sent) | tangent (not sent) | none |
+/// | Type | Face limits (`fit`) | Corners (`corner`) | Setback (`setbacks`) | Turns (`turn`) |
+/// |---------------|-------------------------|-------------------------------------|----------------------|---------------------------------|
+/// | Constant | exact, reduce or taper | tangent; curvature with exact only | with curvature only | mitre; swept without taper, g2 |
+/// | any other | exact (not sent) | tangent (not sent) | none | mitre (not sent) |
///
/// The dialog shows an option's row only where it applies and sends the option only then, and a
/// choice that rules another out puts that one back to its default ([`settle_fillet_options`]).
@@ -150,6 +154,8 @@ pub(super) fn fillet_option_applies(extra: &serde_json::Map<String, Value>, key:
match key {
"fit" => constant,
"corner" | "setbacks" => constant && exact,
+ // A swept turn takes an exact or reduced radius and rolling-ball corners.
+ "turn" => constant && extra.get("fit").and_then(Value::as_str) != Some("taper") && extra.get("corner").and_then(Value::as_str) != Some("g2"),
_ => true,
}
}
@@ -159,15 +165,29 @@ pub(super) fn fillet_option_applies(extra: &serde_json::Map<String, Value>, key:
/// takes the exact radius. A type other than Constant clears both ([`choose_fillet_type`]).
fn settle_fillet_options(extra: &mut serde_json::Map<String, Value>, changed: &str, setback: &mut Option<String>) {
let fitted = extra.get("fit").and_then(Value::as_str).is_some_and(|fit| fit != "exact");
+ let tapered = extra.get("fit").and_then(Value::as_str) == Some("taper");
let patch = extra.get("corner").and_then(Value::as_str) == Some("g2");
+ let swept = extra.get("turn").and_then(Value::as_str) == Some("swept");
match changed {
"fit" if fitted => {
extra.remove("corner");
extra.remove("setbacks");
*setback = None;
+ if tapered {
+ extra.remove("turn");
+ }
}
"corner" if patch => {
extra.remove("fit");
+ extra.remove("turn");
+ }
+ "turn" if swept => {
+ extra.remove("corner");
+ extra.remove("setbacks");
+ *setback = None;
+ if tapered {
+ extra.remove("fit");
+ }
}
_ => {}
}
@@ -256,6 +276,17 @@ fn fillet_fit_rows(app: &SolveApp, ui: &mut egui::Ui, extra: &mut serde_json::Ma
}
}
+/// A Constant radius fillet's Turns row (`turn`): how two rounds turn where they meet at a sharp
+/// corner edge.
+fn fillet_turn_row(ui: &mut egui::Ui, extra: &mut serde_json::Map<String, Value>, setback: &mut Option<String>) {
+ let before = extra.get("turn").cloned();
+ let row = ui.scope(|ui| form_row(ui, "ui.fillet_turn", |ui| extra_choice(ui, extra, "fi_turn", "turn", &FILLET_TURNS)));
+ row.response.on_hover_text(tr("ui.fillet_turn_tip"));
+ if extra.get("turn") != before.as_ref() {
+ settle_fillet_options(extra, "turn", setback);
+ }
+}
+
/// The most instances a solid pattern makes in one direction (the document's own limit).
const MAX_PATTERN_INSTANCES: i64 = 1000;
@@ -293,6 +324,7 @@ fn choose_fillet_type(extra: &mut serde_json::Map<String, Value>, index: usize,
extra.remove("fit");
extra.remove("corner");
extra.remove("setbacks");
+ extra.remove("turn");
}
if index == 2 {
extra.entry("radius2").or_insert_with(|| json!("1 mm"));
@@ -544,6 +576,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
if rtype == 0 {
enter |= fillet_corner_rows(ui, &app.session, &mut d.extra, &d.inputs, radius, setback);
fillet_fit_rows(app, ui, &mut d.extra, setback);
+ fillet_turn_row(ui, &mut d.extra, setback);
}
}
if *chamfer && *ctype == 1 {
@@ -1281,13 +1314,46 @@ mod tests {
assert!(scenario::handle_at("dialog:ui.fillet_fit").is_none(), "a fitted radius is for Constant radius only");
}
+ /// Turns sends `turn: swept` with a Constant radius only, and a choice it rules out (a
+ /// narrowed radius, a curvature corner) puts the other back: Swept and those never go
+ /// together.
+ #[test]
+ fn turns_maps_to_turn_and_rules_out_what_a_swept_corner_does_not_take() {
+ let mut h = fillet_harness();
+ set_edges(&mut h, 3);
+ assert!(scenario::handle_at("dialog:ui.fillet_turn").is_some());
+ assert!(parameters(&h).get("turn").is_none(), "Mitre is the default, not sent");
+ choose(&mut h, "ui.fillet_turn", "ui.fillet_turn_swept");
+ assert_eq!(parameters(&h)["turn"], json!("swept"));
+ choose(&mut h, "ui.fillet_fit", "ui.fillet_fit_reduce");
+ assert_eq!((parameters(&h)["turn"].clone(), parameters(&h)["fit"].clone()), (json!("swept"), json!("reduce")));
+ choose(&mut h, "ui.fillet_fit", "ui.fillet_fit_taper");
+ assert!(parameters(&h).get("turn").is_none(), "a narrowed radius puts Turns back to Mitre");
+ choose(&mut h, "ui.fillet_turn", "ui.fillet_turn_swept");
+ assert!(parameters(&h).get("fit").is_none(), "Swept puts Face limits back to Exact radius");
+ choose(&mut h, "ui.corners", Continuity::G2.label_id());
+ assert!(parameters(&h).get("turn").is_none(), "a curvature corner puts Turns back to Mitre");
+ choose(&mut h, "ui.fillet_turn", "ui.fillet_turn_swept");
+ assert!(parameters(&h).get("corner").is_none(), "Swept puts Corners back to Tangent");
+ choose(&mut h, "ui.fillet_turn", "ui.fillet_turn_mitre");
+ assert!(parameters(&h).get("turn").is_none(), "Mitre is not sent");
+ choose(&mut h, "ui.fillet_turn", "ui.fillet_turn_swept");
+ choose(&mut h, "Type", "Chord length");
+ assert!(parameters(&h).get("turn").is_none() && scenario::handle_at("dialog:ui.fillet_turn").is_none(), "Turns is for Constant radius only");
+ }
+
/// The dialog follows the option model (`fillet_option_applies`): through every type, fit and
/// corner choice, in either order, each option it shows is one the others allow, and the
/// command it builds is never refused for its options (`solid.fillet` runs it on a copy of
/// the design). A choice that rules another out resets that one, visibly.
#[test]
fn no_reachable_fillet_option_state_is_refused_for_its_options() {
- let refused_for_options = |e: &str| e.contains("take a constant radius") || e.contains("is built for") || e.contains("are built for");
+ let refused_for_options = |e: &str| {
+ e.contains("take a constant radius")
+ || e.contains("is built for")
+ || e.contains("are built for")
+ || e.contains(solidcraft_engine::doc::SWEPT_TAKES)
+ };
// Each distinct command is run once.
let ran = std::cell::RefCell::new(std::collections::BTreeSet::new());
let check = |h: &Harness, what: &str| {
diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md
index 83581c7900..fb4948cd86 100644
--- a/docs/book/src/reference/glossary.md
+++ b/docs/book/src/reference/glossary.md
@@ -440,6 +440,18 @@ The ordered list of a design's features, which SolidCraft computes from first to
- **Elsewhere:** timeline, history, feature tree.
- **For translators:** not the undo history.
+### turn (of two rounds)
+
+How two rounds of a fillet continue where they turn round a sharp corner edge between them, such
+as the rounds along a boss's base at its upright edges: in a mitre, or swept round the corner
+edge as a torus.
+
+- **In SolidCraft:** the `turn` parameter of `solid.fillet` and its design-file key, `mitre`
+ (the default) or `swept`; the Fillet dialog's Turns row.
+- **Don't use:** corner (that is what fills a corner where three rounded edges meet, `corner`).
+- **Elsewhere:** mitred corner, swept corner, corner sweep.
+- **For translators:** "Mitre" and "Swept" name the two shapes, not a direction of travel.
+
### view angles
The yaw, pitch and roll, in degrees, that give the direction a view looks along and how its
diff --git a/tests/kernel-cases/fillets/KNOWN_FAILING b/tests/kernel-cases/fillets/KNOWN_FAILING
index 497859eb0d..5f094f7e95 100644
--- a/tests/kernel-cases/fillets/KNOWN_FAILING
+++ b/tests/kernel-cases/fillets/KNOWN_FAILING
@@ -15,8 +15,6 @@ cov-fillet-g2-four-edge-apex-corner [fail] step 11 (solid.fillet): invalid input
cov-fillet-g2-mixed-corner [unsupported] refused as on SMLib d01d7b0: a G2 corner is set back only where every edge meeting it is rounded and all are convex or all concave
cov-fillet-g2-oblique-three-edge-corner [unsupported] refused on solidcore: its three edges meet at different wedge angles, and one curvature fillet takes the first edge's equal-area thumbweight for every edge (solidcore#2250, issuecomment-6563419897); SMLib d01d7b0 fails it too
cov-fillet-g2-pocket-corner [fail] continuity_order: G1 at one seam where the corner patch meets a contact face (g2 wanted), as on SMLib d01d7b0
-cov-fillet-turn-swept-boss-base-r1 [fail] as on SMLib: solid.fillet has no `turn`; the corners are mitred (12508.9675, the Mitre case's volume)
-cov-fillet-turn-swept-pocket-sharp-corner-refused-r1 [fail] as on SMLib: solid.fillet has no `turn`, so the sharp concave corners are mitred, not refused
cov-junction-boss-tilt-20-root-round [fail] fillet status 1001 on a cylinder tilted 20 degrees into the plate, as on SMLib
cov-junction-boss-tilt-40-root-round [fail] fillet status 1001 on a cylinder tilted 40 degrees into the plate, as on SMLib
cov-junction-tee-equal-round [fail] the result is not a closed solid, as on SMLib: equal pipes' intersection is two plane ellipses crossing, a corner the old corner code cannot join (the corner step)