Skip to content

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

Edge flange: material outside and tangent bend positions (#5941) (#6060)

Ahmad Khan0f90fb7e8d5f
diff --git a/assets/locales/pending/sheet-flange-bend-positions.json b/assets/locales/pending/sheet-flange-bend-positions.json
new file mode 100644
index 0000000000..77941d8ac3
--- /dev/null
+++ b/assets/locales/pending/sheet-flange-bend-positions.json
@@ -0,0 +1,14 @@
+{
+ "en": {
+ "Material Outside": "Material Outside",
+ "Tangent to Edge": "Tangent to Edge"
+ },
+ "ja": {
+ "Material Outside": "材料外側",
+ "Tangent to Edge": "エッジに正接"
+ },
+ "zh": {
+ "Material Outside": "材料在外",
+ "Tangent to Edge": "与边相切"
+ }
+}
diff --git a/assets/locales/pending/sheet-flange-height-from.json b/assets/locales/pending/sheet-flange-height-from.json
new file mode 100644
index 0000000000..5957521825
--- /dev/null
+++ b/assets/locales/pending/sheet-flange-height-from.json
@@ -0,0 +1,20 @@
+{
+ "en": {
+ "Height From": "Height From",
+ "Inner Sharp": "Inner Sharp",
+ "Outer Sharp": "Outer Sharp",
+ "Tangent": "Tangent"
+ },
+ "ja": {
+ "Height From": "高さの基準",
+ "Inner Sharp": "内側仮想シャープ",
+ "Outer Sharp": "外側仮想シャープ",
+ "Tangent": "正接"
+ },
+ "zh": {
+ "Height From": "高度基准",
+ "Inner Sharp": "内侧虚拟尖点",
+ "Outer Sharp": "外侧虚拟尖点",
+ "Tangent": "相切"
+ }
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 0bfed99c69..5e45756867 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -1086,7 +1086,7 @@ pub enum FeatureKind {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(length = "Bend radius")]
radius: Option<Expr>,
- /// inside | outside | middle.
+ /// inside | outside | middle | material_outside | tangent (`sheet::SheetBody::add_flanges_each`).
#[serde(default = "inside_str")]
position: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -1102,6 +1102,11 @@ pub enum FeatureKind {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(length = "Corner relief")]
corner_relief: Option<Expr>,
+ /// Where the heights are measured from: `inner` (the inner virtual sharp) or `tangent`
+ /// (past 90° the line square to the flange touching the bend's outside); none is the outer
+ /// virtual sharp (`sheet::HeightFrom`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ height_from: Option<String>,
},
/// Flat hems on sheet edges.
SheetHem {
diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs
index 2e872b4d65..787f5e371b 100644
--- a/crates/doc/src/eval_more.rs
+++ b/crates/doc/src/eval_more.rs
@@ -561,7 +561,7 @@ pub(super) fn sheet_eval(
st.sheets.push(sh);
Ok(())
}
- FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief } => {
+ FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief, height_from } => {
let i = sheet_for(st, body, edges.first().map(|e| e.point.0))?;
let (h, a) = (val(vals, height, Kind::Length)?, val(vals, angle, Kind::Angle)?);
// Each edge's own height and angle, else the feature's.
@@ -598,6 +598,11 @@ pub(super) fn sheet_eval(
None => None,
},
};
+ let from = match height_from {
+ Some(name) => sheet::HeightFrom::parse(name)
+ .ok_or_else(|| DocError::Invalid(format!("unknown flange height datum `{name}` (outer, inner or tangent)")))?,
+ None => sheet::HeightFrom::Outer,
+ };
let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?;
if sh.flat {
return Err(DocError::Invalid("refold the sheet before adding flanges".into()));
@@ -606,7 +611,7 @@ pub(super) fn sheet_eval(
let each: Vec<sheet::EdgeFlange> = sheet_picks(sh, f, &points, warning)
.into_iter()
.zip(own)
- .map(|(pick, (height, angle))| sheet::EdgeFlange { pick, height, angle })
+ .map(|(pick, (height, angle))| sheet::EdgeFlange { pick, height, angle, from })
.collect();
let n0 = sh.flanges.len();
let (_, notes) = sh.add_flanges_each(&each, rr, position, *flip, relief)?;
diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs
index 88b466c9af..fce88e0780 100644
--- a/crates/doc/src/format.rs
+++ b/crates/doc/src/format.rs
@@ -1419,6 +1419,7 @@ mod tests {
body: None,
corner_relief_shape: shape.map(Into::into),
corner_relief: size.map(Into::into),
+ height_from: None,
};
let saved = |document: &Document| -> Value { serde_json::from_str(&document.to_json()).unwrap() };
// A flange that follows the rule saves neither key, and a design of format 23 opens as it was.
diff --git a/crates/doc/src/format/pending/sheet-flange-bend-positions.rs b/crates/doc/src/format/pending/sheet-flange-bend-positions.rs
new file mode 100644
index 0000000000..a728e5c2fe
--- /dev/null
+++ b/crates/doc/src/format/pending/sheet-flange-bend-positions.rs
@@ -0,0 +1,6 @@
+//! An edge flange feature's `position` can also be `material_outside` (the inner virtual sharp on
+//! the picked edge, so at 90° the flange's inner face is flush with the edge's face) or `tangent`
+//! (the bend's outer face tangent to the edge's face; below 90° the bend's end on that face),
+//! #5941. Older designs need no step: their
+//! positions (inside, outside, middle) are saved and built as before. The last release refuses a
+//! design that has them (it refuses the newer format number).
diff --git a/crates/doc/src/format/pending/sheet-flange-height-from.rs b/crates/doc/src/format/pending/sheet-flange-height-from.rs
new file mode 100644
index 0000000000..e3d8d9803e
--- /dev/null
+++ b/crates/doc/src/format/pending/sheet-flange-height-from.rs
@@ -0,0 +1,6 @@
+//! An edge flange feature can say where its heights are measured from (#5938): `height_from` is
+//! `inner` (the inner virtual sharp) or `tangent` (past 90° the line square to the flange
+//! touching the outside of the bend, up to 90° the outer virtual sharp). A feature measured from the outer
+//! virtual sharp, as every flange was before, saves no `height_from`, so older designs need no
+//! step and open and save as they were. The last release refuses a design that has it (it
+//! refuses the newer format number).
diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs
index 3724f307bd..ed8cf03a3f 100644
--- a/crates/doc/src/sheet.rs
+++ b/crates/doc/src/sheet.rs
@@ -549,13 +549,75 @@ pub struct SheetFlange {
pub tag: String,
}
-/// One edge flange to make: a pick on the sheet's edge, and that flange's height (to the outer
-/// face, from the virtual sharp) and angle (radians).
+/// One edge flange to make: a pick on the sheet's edge, that flange's height (measured as `from`
+/// says) and angle (radians).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EdgeFlange {
pub pick: Vec3,
pub height: f64,
pub angle: f64,
+ pub from: HeightFrom,
+}
+
+/// Where an edge flange's height is measured from (#5938). Every one measures along the flange,
+/// up to its far edge; they differ in where the measure starts, so in how much of the height is
+/// the bend rather than the leg (the flat panel past the bend). With bend angle θ, inner radius
+/// R and thickness T, the leg is the height less [`HeightFrom::before_leg`].
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum HeightFrom {
+ /// From the outer virtual sharp, where the lines of the base's and the flange's outer faces
+ /// meet, along the outer face: (R + T)·tan(θ/2) of the height is before the leg.
+ #[default]
+ Outer,
+ /// From the inner virtual sharp, where the lines of the two inner faces meet, along the inner
+ /// face: R·tan(θ/2) of the height is before the leg.
+ Inner,
+ /// For bends past 90°: from the line square to the flange that touches the outside of the
+ /// bend (at the point a quarter turn before the bend's end), R + T before the leg. Up to 90°
+ /// it is the outer virtual sharp, (R + T)·tan(θ/2); at 90° the two are the same line (the
+ /// base's outer face), so the height does not jump as the angle passes 90°.
+ Tangent,
+}
+
+impl HeightFrom {
+ pub const NAMES: [&'static str; 3] = ["outer", "inner", "tangent"];
+
+ pub fn parse(name: &str) -> Option<Self> {
+ match name.trim().to_ascii_lowercase().as_str() {
+ "outer" => Some(Self::Outer),
+ "inner" => Some(Self::Inner),
+ "tangent" => Some(Self::Tangent),
+ _ => None,
+ }
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Outer => "outer",
+ Self::Inner => "inner",
+ Self::Tangent => "tangent",
+ }
+ }
+
+ /// How much of the height lies before the leg starts, for a bend of `angle` (radians), inner
+ /// `radius` and `thickness`: the smallest height that fits (a flange with no leg).
+ pub fn before_leg(self, angle: f64, radius: f64, thickness: f64) -> f64 {
+ match self {
+ Self::Outer => (radius + thickness) * (angle / 2.0).tan(),
+ Self::Inner => radius * (angle / 2.0).tan(),
+ Self::Tangent if angle <= std::f64::consts::FRAC_PI_2 => (radius + thickness) * (angle / 2.0).tan(),
+ Self::Tangent => radius + thickness,
+ }
+ }
+
+ /// What the measure starts at, for messages.
+ fn datum(self) -> &'static str {
+ match self {
+ Self::Outer => "the outer sharp",
+ Self::Inner => "the inner sharp",
+ Self::Tangent => "the bend's tangent",
+ }
+ }
}
/// The most lines a path flange's path may have (each one flange and its bend).
@@ -2360,8 +2422,9 @@ impl SheetBody {
Ok(())
}
- /// Add an edge flange on the panel edge nearest `pick` (world): `height` to the outer face
- /// from the virtual sharp, `angle` (0…180°), inside / outside / middle bend position.
+ /// Add an edge flange on the panel edge nearest `pick` (world): `height` measured from the
+ /// outer virtual sharp ([`HeightFrom::Outer`]), `angle` (0…180°), inside / outside / middle /
+ /// material_outside / tangent bend position (see `add_flanges_each`).
pub fn add_flange(&mut self, pick: Vec3, height: f64, angle: f64, radius: f64, position: &str, flip: bool) -> Result<usize> {
self.add_flanges(&[pick], height, angle, radius, position, flip)?.into_iter().next().ok_or_else(|| DocError::Invalid("flange".into()))
}
@@ -2384,7 +2447,7 @@ impl SheetBody {
position: &str,
flip: bool,
) -> Result<(Vec<usize>, Vec<String>)> {
- let each: Vec<EdgeFlange> = picks.iter().map(|&pick| EdgeFlange { pick, height, angle }).collect();
+ let each: Vec<EdgeFlange> = picks.iter().map(|&pick| EdgeFlange { pick, height, angle, from: HeightFrom::Outer }).collect();
self.add_flanges_each(&each, radius, position, flip, ReliefOverride::default())
}
@@ -2475,7 +2538,7 @@ impl SheetBody {
None => (pick, top == (turn < 0.0)),
Some(&i) => (self.far_edge_pick(i).ok_or_else(|| DocError::Invalid("the flange has no far edge to bend again".into()))?, turn < 0.0),
};
- let each = [EdgeFlange { pick: at, height, angle: turn.abs() }];
+ let each = [EdgeFlange { pick: at, height, angle: turn.abs(), from: HeightFrom::Outer }];
let own = if k == 0 { relief } else { ReliefOverride::default() };
let (new, more) = self.add_flanges_each(&each, radius, "inside", flip, own).map_err(line)?;
made.extend(new);
@@ -2516,15 +2579,39 @@ impl SheetBody {
return Err(DocError::Invalid(format!("{}the flange angle must be between 0 and 180°", on(k))));
}
let sharp = (radius + self.t) * (e.angle / 2.0).tan();
+ // How far inside the picked edge the bend starts (the base is cut back that far), with
+ // bend angle θ, inner radius R and thickness T:
+ // - inside: (R + T)·tan(θ/2), the outer virtual sharp on the edge (at 90° the flange's
+ // outer face is flush with the edge's face);
+ // - outside: 0, the bend starts at the edge and lies wholly outside it (`sheet.flange`
+ // also takes `bend_outside` and saves it as `outside`);
+ // - middle: half of inside;
+ // - material_outside: R·tan(θ/2), the inner virtual sharp on the edge (at 90° the
+ // flange's inner face is flush with the edge's face, its material outside);
+ // - tangent: from 90° on R + T, the bend's outer face tangent to the edge's face (it
+ // touches that face a quarter turn into the bend and nothing of the bend passes it);
+ // below 90° the outer face never turns parallel to the edge's face, so the bend
+ // reaches furthest out at its end: (R + T)·sin θ puts that end on the edge's face
+ // (the leg leans on out past it). Both are R + T at 90°.
let setback = match position {
"inside" | "" => sharp,
"outside" => 0.0,
"middle" | "mid" => sharp / 2.0,
- other => return Err(DocError::Invalid(format!("unknown bend position `{other}` (inside, outside or middle)"))),
+ "material_outside" => radius * (e.angle / 2.0).tan(),
+ "tangent" if e.angle < std::f64::consts::FRAC_PI_2 => (radius + self.t) * e.angle.sin(),
+ "tangent" => radius + self.t,
+ other => {
+ return Err(DocError::Invalid(format!("unknown bend position `{other}` (inside, outside, middle, material_outside or tangent)")));
+ }
};
- let leg = e.height - sharp;
+ let least = e.from.before_leg(e.angle, radius, self.t);
+ let leg = e.height - least;
if !(leg >= -1e-9) {
- return Err(DocError::Invalid(format!("{}the flange height must be at least {sharp:.3} mm for this bend", on(k))));
+ let from = match e.from {
+ HeightFrom::Outer => String::new(),
+ other => format!(" from {}", other.datum()),
+ };
+ return Err(DocError::Invalid(format!("{}the flange height{from} must be at least {least:.3} mm for this bend", on(k))));
}
sizes.push((setback, leg));
}
@@ -5986,7 +6073,8 @@ mod tests {
Vec3::new(60.0 + u.x * 90.0, u.y * 90.0, 2.0),
Vec3::new(u.x * 45.0, u.y * 45.0, 2.0),
];
- let each: Vec<EdgeFlange> = (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians() }).collect();
+ let each: Vec<EdgeFlange> =
+ (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians(), from: HeightFrom::Outer }).collect();
flanges_each(rhombus(), rv, &each)
}
@@ -6016,7 +6104,7 @@ mod tests {
Vec3::new(l * 0.75, -l * u.y / 2.0, 2.0),
Vec3::new(l / 4.0, -l * u.y / 2.0, 2.0),
];
- let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians() };
+ let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians(), from: HeightFrom::Outer };
// The round relief reaches r from its corner and the two are 12 mm apart: it fits at both.
for shape in [ReliefShape::Round, ReliefShape::Rectangular] {
let what = format!("{shape:?} at two corners opposite each other");
@@ -6167,7 +6255,7 @@ mod tests {
let pts = [Vec2::new(0.0, 0.0), Vec2::new(9.0, 0.0), Vec2::new(9.0, 40.0), Vec2::new(-20.0, 20.0 * 3.0f64.sqrt())];
let base = || Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] };
let picks = [Vec3::new(-10.0, 17.32, 2.0), Vec3::new(4.5, 0.0, 2.0), Vec3::new(9.0, 20.0, 2.0)];
- let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians() };
+ let flange = |i: usize| EdgeFlange { pick: picks[i], height: 38.6, angle: 90f64.to_radians(), from: HeightFrom::Outer };
for shape in [ReliefShape::Round, ReliefShape::Rectangular] {
let what = format!("{shape:?} at both ends of a short edge");
let rv = RuleValues { corner_relief_shape: shape, corner_relief: 4.0, ..alu() };
@@ -6260,6 +6348,16 @@ mod tests {
holds_the_flat_material(&s, "a flange on a folded panel's side");
}
+ #[test]
+ fn a_bend_position_only_the_command_takes_as_another_name_is_refused_when_built() {
+ // `sheet.flange` saves `bend_outside` as `outside`; a design that names it itself is
+ // refused rather than built (or edited) as some other position.
+ let mut s = plate(200.0, 100.0);
+ let e = s.add_flange(Vec3::new(100.0, 0.0, 2.5), 40.0, std::f64::consts::FRAC_PI_2, 2.5, "bend_outside", false).unwrap_err().to_string();
+ assert!(e.contains("unknown bend position `bend_outside`"), "{e}");
+ assert!(s.flanges.is_empty());
+ }
+
#[test]
fn edge_flanges_across_an_existing_bend_close_their_corner() {
for position in ["inside", "outside", "middle"] {
@@ -6341,7 +6439,7 @@ mod tests {
let parent = s.flanges.get(wall).unwrap();
let point = parent.p + parent.d * parent.len + parent.n * (s.allowance(parent) + parent.leg * 0.5);
let side = apply_point(&s.world(Some(wall)), Vec3::new(point.x, point.y, s.t));
- let edges = [Vec3::new(120.0, 45.0, 2.0), side].map(|pick| EdgeFlange { pick, height: 20.0, angle });
+ let edges = [Vec3::new(120.0, 45.0, 2.0), side].map(|pick| EdgeFlange { pick, height: 20.0, angle, from: HeightFrom::Outer });
let (_, notes) = s.add_flanges_each(&edges, 1.0, "inside", false, ReliefOverride { shape: Some(shape), size: Some(4.0) }).unwrap();
assert!(notes.is_empty(), "{shape:?}: {notes:?}");
assert_eq!(s.holes.len(), 1);
@@ -7059,7 +7157,8 @@ mod tests {
let base = rect(Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 90.0), Vec2::new(0.0, 90.0));
let t = rv.thickness;
let picks = [Vec3::new(60.0, 0.0, t), Vec3::new(120.0, 45.0, t), Vec3::new(60.0, 90.0, t), Vec3::new(0.0, 45.0, t)];
- let each: Vec<EdgeFlange> = (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians() }).collect();
+ let each: Vec<EdgeFlange> =
+ (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians(), from: HeightFrom::Outer }).collect();
flanges_each(base, rv, &each)
}
@@ -7259,7 +7358,8 @@ mod tests {
let pts = [Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(100.0, 90.0), Vec2::new(20.0, 90.0)];
let picks = [Vec3::new(60.0, 0.0, 2.0), Vec3::new(110.0, 45.0, 2.0), Vec3::new(60.0, 90.0, 2.0), Vec3::new(10.0, 45.0, 2.0)];
let (angles, heights) = ([60.0f64, 105.0, 75.0, 120.0], [38.6, 30.0, 45.0, 25.0]);
- let each: Vec<EdgeFlange> = (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians() }).collect();
+ let each: Vec<EdgeFlange> =
+ (0..4).map(|i| EdgeFlange { pick: picks[i], height: heights[i], angle: angles[i].to_radians(), from: HeightFrom::Outer }).collect();
let (s, notes) = flanges_each(Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] }, &alu(), &each);
assert!(notes.is_empty(), "{notes:?}");
for i in 0..4 {
@@ -7283,7 +7383,7 @@ mod tests {
.iter()
.map(|&k| {
let m = (pts[k] + pts[(k + 1) % n]) * 0.5;
- EdgeFlange { pick: Vec3::new(m.x, m.y, rv.thickness), height, angle: deg.to_radians() }
+ EdgeFlange { pick: Vec3::new(m.x, m.y, rv.thickness), height, angle: deg.to_radians(), from: HeightFrom::Outer }
})
.collect();
let (s, notes) = flanges_each(Region2 { outer: Loop2::polygon(pts).ccw(), holes: vec![] }, rv, &each);
@@ -7602,8 +7702,9 @@ mod tests {
let rv = alu();
let (t, g) = (rv.thickness, rv.gap);
let (mut s, _) = tray(&rv, 90.0, 20.0);
- let each: Vec<EdgeFlange> =
- (0..4).map(|i| EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: [90f64, 70.0][i % 2].to_radians() }).collect();
+ let each: Vec<EdgeFlange> = (0..4)
+ .map(|i| EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: [90f64, 70.0][i % 2].to_radians(), from: HeightFrom::Outer })
+ .collect();
let (made, notes) = s.add_flanges_each(&each, 1.0, "inside", false, ReliefOverride::default()).unwrap();
assert!(notes.is_empty() && made == [4, 5, 6, 7], "{made:?} {notes:?}");
for (a, a_end, b, b_end) in TRAY_RETURNS {
@@ -7774,7 +7875,7 @@ mod tests {
let each: Vec<EdgeFlange> = (0..4)
.map(|i| {
let deg: f64 = if square { 90.0 } else { 180.0 - angles[i] };
- EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: deg.to_radians() }
+ EdgeFlange { pick: far_edge_pick(&s, i, true), height: 12.0, angle: deg.to_radians(), from: HeightFrom::Outer }
})
.collect();
let (_, notes) = s.add_flanges_each(&each, 1.0, "inside", false, ReliefOverride::default()).unwrap();
@@ -7914,8 +8015,8 @@ mod tests {
for b in SWEEP {
let what = format!("corner {alpha}°, flanges {a}° and {b}°");
let each = [
- EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians() },
- EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians() },
+ EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians(), from: HeightFrom::Outer },
+ EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians(), from: HeightFrom::Outer },
];
let (s, notes) = flanges_each(Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] }, &rv, &each);
assert!(notes.is_empty(), "{what}: {notes:?}");
@@ -8314,8 +8415,8 @@ mod tests {
for b in SWEEP {
let what = format!("corner {alpha}°, flanges {a}° and {b}°");
let each = [
- EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians() },
- EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians() },
+ EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians(), from: HeightFrom::Outer },
+ EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians(), from: HeightFrom::Outer },
];
let base = || Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] };
let (notch, _) = flanges_each(base(), &alu(), &each);
@@ -8482,8 +8583,8 @@ mod tests {
let u = Vec2::new(alpha.cos(), alpha.sin());
let pts = [Vec2::new(0.0, 0.0), Vec2::new(120.0, 0.0), Vec2::new(120.0, 0.0) + u * 90.0, u * 90.0];
let each = [
- EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians() },
- EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians() },
+ EdgeFlange { pick: Vec3::new(60.0, 0.0, 2.0), height: 38.6, angle: a.to_radians(), from: HeightFrom::Outer },
+ EdgeFlange { pick: Vec3::new(u.x * 45.0, u.y * 45.0, 2.0), height: 38.6, angle: b.to_radians(), from: HeightFrom::Outer },
];
let base = || Region2 { outer: Loop2::polygon(&pts).ccw(), holes: vec![] };
let (notch, none) = flanges_each(base(), &alu(), &each);
diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs
index b34b809dc5..9c563138da 100644
--- a/crates/engine/src/cmd/sheet.rs
+++ b/crates/engine/src/cmd/sheet.rs
@@ -18,8 +18,12 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sheet.flange", "Flange", flange).at("SHEET METAL", "CREATE").icon("flange").params(
"base: sketch + profiles? (rule?, flip?) | contour: sketch + curves (open chain of lines) + distance (rule?, flip?, reverse?) | \
edge: edges: [[x,y,z] on top/bottom edges, or {point: [x,y,z], angle?, height?} for an edge with its own angle and height] + \
- height (to the outer face), angle? (default 90 deg), radius? (default: rule), \
- position?: inside|outside|middle, flip?, body?, corner_relief_shape?: notch|round|rectangular|tear and corner_relief? (size across): \
+ height (along the flange, to its far edge), angle? (default 90 deg), radius? (default: rule), \
+ height_from?: outer|inner|tangent (where the height is measured from: the outer virtual sharp (default), \
+ the inner virtual sharp, or past 90 deg the line square to the flange touching the bend's outside (tangent; up to 90 deg the outer sharp)), \
+ position?: inside|outside|middle|material_outside|tangent (where the bend starts: the outer virtual sharp on the edge (default), \
+ the bend starting at the edge (bend_outside is the same), half way, the inner virtual sharp on the edge, \
+ or the bend's outer face tangent to the edge's face (below 90 deg the bend's end on that face)), flip?, body?, corner_relief_shape?: notch|round|rectangular|tear and corner_relief? (size across): \
the relief at the corners these flanges make (default: the rule's); \
then?: [{angle?, height, flip?}] further bends (at most 16), each a flange on the far edge of the one before, flip: true turns that bend the other way (edge only); \
type?: base|edge|contour (default from the inputs); name?, body_name? (the new body). \
@@ -269,10 +273,20 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(r) = &radius {
check_expr(s, r, Kind::Length, cmd, "radius")?;
}
- let position = str_(p, "position").unwrap_or("inside").to_ascii_lowercase();
- if !matches!(position.as_str(), "inside" | "outside" | "middle") {
- return Err(bad(cmd, "`position` must be inside, outside or middle"));
+ let mut position = str_(p, "position").unwrap_or("inside").to_ascii_lowercase();
+ if !matches!(position.as_str(), "inside" | "outside" | "bend_outside" | "middle" | "material_outside" | "tangent") {
+ return Err(bad(cmd, "`position` must be inside, outside, middle, material_outside or tangent"));
}
+ // The bend starting at the edge is `outside`, whichever name asked for it.
+ if position == "bend_outside" {
+ position = "outside".into();
+ }
+ // Where the heights are measured from; the outer sharp (the default) is saved as nothing.
+ let height_from = match p.get("height_from").filter(|v| !v.is_null()) {
+ Some(v) => v.as_str().and_then(sheet::HeightFrom::parse).ok_or_else(|| bad(cmd, "`height_from` must be outer, inner or tangent"))?,
+ None => sheet::HeightFrom::Outer,
+ };
+ let height_from = (height_from != sheet::HeightFrom::Outer).then(|| height_from.name().to_string());
if s.model.state().sheets.is_empty() {
return Err(no_sheet_body(cmd));
}
@@ -305,6 +319,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
body: body.clone().map(BodyName),
corner_relief_shape,
corner_relief,
+ height_from: height_from.clone(),
},
)?;
// Each further bend stands on the far edge of the flange before it.
@@ -324,6 +339,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
body: body.clone().map(BodyName),
corner_relief_shape: None,
corner_relief: None,
+ height_from: height_from.clone(),
},
)?;
}
diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs
index 1d3671d812..295d5040c9 100644
--- a/crates/engine/src/cmd/sheet_tests.rs
+++ b/crates/engine/src/cmd/sheet_tests.rs
@@ -4553,6 +4553,209 @@ fn a_flange_asked_for_0_8_mm_is_0_8_mm_or_refused_never_silently_2_5_mm() {
}
}
+/// A 100 x 60 base on XY under a rule 2 mm thick, R 2, K 0.4.
+fn r2_base(s: &mut Session) {
+ run(s, "sheet.manage_rules", json!({"name": "R2", "thickness": "2 mm", "k_factor": 0.4, "bend_radius": "2 mm", "active": true}));
+ base(s, 100.0, 60.0);
+}
+
+/// The top (z) of the sheet and its flat length across the flanged edge.
+fn top_and_flat(s: &mut Session) -> (f64, f64) {
+ let top = bbox(s)["max"][2].as_f64().unwrap_or(f64::NAN);
+ (top, flat(s)["flat_size_mm"][1].as_f64().unwrap_or(f64::NAN))
+}
+
+#[test]
+fn an_edge_flange_height_is_measured_from_the_outer_sharp_the_inner_sharp_or_the_bend_tangent() {
+ // T = 2, R = 2, K = 0.4, height 20 on the edge y = 0, inside position (setback (R + T)·tan(θ/2)).
+ // Before the leg: outer (R + T)·tan(θ/2), inner R·tan(θ/2), tangent the outer's up to 90° and
+ // R + T past it.
+ // The bend's axis is at z = T + R = 4; its far edge is the leg along the flange from the bend's
+ // end, so the top of the part is 4 − min((R + T)·cos θ, R·cos θ) + leg·sin θ, and the flat is
+ // 60 − setback + θ·(R + K·T) + leg.
+ let (t, r, k) = (2.0, 2.0, 0.4);
+ for deg in [90.0f64, 60.0, 120.0] {
+ let th = deg.to_radians();
+ let half = (th / 2.0).tan();
+ for (from, before) in [("outer", (r + t) * half), ("inner", r * half), ("tangent", if deg <= 90.0 { (r + t) * half } else { r + t })] {
+ let what = format!("{deg}° from {from}");
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg"), "height_from": from}));
+ let leg = 20.0 - before;
+ let top = r + t - ((r + t) * th.cos()).min(r * th.cos()) + leg * th.sin();
+ let length = 60.0 - (r + t) * half + th * (r + k * t) + leg;
+ let (got_top, got_flat) = top_and_flat(&mut s);
+ assert!((got_top - top).abs() < 1e-6, "{what}: top {got_top}, want {top}");
+ assert!((got_flat - length).abs() < 1e-6, "{what}: flat {got_flat}, want {length}");
+ }
+ }
+ // At 90°: legs 16, 18 and 16, so the far edge is at z = 20, 22 and 20.
+ let tops: Vec<f64> = ["outer", "inner", "tangent"]
+ .iter()
+ .map(|from| {
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "height_from": from}));
+ top_and_flat(&mut s).0
+ })
+ .collect();
+ for (got, want) in tops.iter().zip([20.0, 22.0, 20.0]) {
+ assert!((got - want).abs() < 1e-6, "{tops:?}");
+ }
+}
+
+#[test]
+fn an_edge_flange_measured_from_the_outer_sharp_saves_and_builds_as_before() {
+ let build = |extra: Option<&str>| {
+ let mut s = Session::default();
+ r2_base(&mut s);
+ let mut p = json!({"edges": [[50, 0, 2]], "height": 20, "angle": "75 deg"});
+ if let Some(from) = extra {
+ p["height_from"] = json!(from);
+ }
+ run(&mut s, "sheet.flange", p);
+ let kind = serde_json::to_value(s.doc.features.last().map(|f| f.kind.clone())).unwrap_or_default();
+ let (top, length) = top_and_flat(&mut s);
+ (kind, top, length, volume(&mut s))
+ };
+ let (plain, top, length, v) = build(None);
+ assert!(plain.get("height_from").is_none(), "{plain}");
+ let (outer, top_o, length_o, v_o) = build(Some("OUTER"));
+ assert_eq!(plain, outer);
+ assert_eq!((top, length, v), (top_o, length_o, v_o));
+ let (inner, ..) = build(Some("inner"));
+ assert_eq!(inner["height_from"], "inner", "{inner}");
+}
+
+#[test]
+fn an_edge_flange_too_short_for_its_height_datum_or_with_an_unknown_one_is_refused() {
+ let mut s = Session::default();
+ r2_base(&mut s);
+ let (features, v) = (s.doc.features.len(), volume(&mut s));
+ let err = |s: &mut Session, p: Value| match s.execute("sheet.flange", &p) {
+ Ok(v) => panic!("{p} was accepted: {v}"),
+ Err(e) => e.to_string(),
+ };
+ // From the inner sharp at 90° the bend takes R·tan 45° = 2; from the tangent past 90°, R + T = 4.
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 1.5, "height_from": "inner"}));
+ assert!(e.contains("from the inner sharp must be at least 2.000 mm"), "{e}");
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 3, "angle": "120 deg", "height_from": "tangent"}));
+ assert!(e.contains("from the bend's tangent must be at least 4.000 mm"), "{e}");
+ // From the outer sharp the message is the one it always was.
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 3.9, "height_from": "outer"}));
+ assert!(e.contains("height must be at least 4.000 mm"), "{e}");
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 20, "height_from": "middle"}));
+ assert!(e.contains("`height_from` must be outer, inner or tangent"), "{e}");
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 20, "height_from": 3}));
+ assert!(e.contains("`height_from`"), "{e}");
+ assert_eq!(s.doc.features.len(), features);
+ assert!(rel(volume(&mut s), v) < 1e-12);
+ // Up to 90° the tangent is the outer sharp: at 90° the bend takes R + T = 4, at 60° 4·tan 30°.
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 3.9, "height_from": "tangent"}));
+ assert!(e.contains("from the bend's tangent must be at least 4.000 mm"), "{e}");
+ let e = err(&mut s, json!({"edges": [[50, 0, 2]], "height": 2.3, "angle": "60 deg", "height_from": "tangent"}));
+ assert!(e.contains("from the bend's tangent must be at least 2.309 mm"), "{e}");
+ assert_eq!(s.doc.features.len(), features);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 4, "height_from": "tangent"}));
+ assert_eq!(s.doc.features.len(), features + 1);
+}
+
+#[test]
+fn an_edge_flange_measured_from_the_tangent_does_not_jump_as_its_angle_passes_90_degrees() {
+ // T = 2, R = 2, K = 0.4, height 20 from the tangent, inside position. Before the leg:
+ // (R + T)·tan(θ/2) up to 90° (the outer sharp), R + T past it; at 90° both are 4, so the leg,
+ // the top and the flat change smoothly through 90°.
+ let (t, r, k) = (2.0, 2.0, 0.4);
+ let build = |deg: f64| {
+ let th = deg.to_radians();
+ let half = (th / 2.0).tan();
+ let before = if deg <= 90.0 { (r + t) * half } else { r + t };
+ let leg = 20.0 - before;
+ let top = r + t - ((r + t) * th.cos()).min(r * th.cos()) + leg * th.sin();
+ let length = 60.0 - (r + t) * half + th * (r + k * t) + leg;
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg"), "height_from": "tangent"}));
+ let (got_top, got_flat) = top_and_flat(&mut s);
+ assert!((got_top - top).abs() < 1e-6, "{deg}°: top {got_top}, want {top}");
+ assert!((got_flat - length).abs() < 1e-6, "{deg}°: flat {got_flat}, want {length}");
+ (got_top, got_flat)
+ };
+ // 60°: leg 20 − 4·tan 30° = 17.691, as from the outer sharp; the inner face's end is highest
+ // at the bend, 4 − R·cos 60° = 3.
+ let (top60, _) = build(60.0);
+ let want = 4.0 - 2.0 * 0.5 + (20.0 - 4.0 * (30f64.to_radians()).tan()) * (60f64.to_radians()).sin();
+ assert!((top60 - want).abs() < 1e-6, "60°: top {top60}, want {want}");
+ // 90°: leg 16, top 20.
+ let (top90, flat90) = build(90.0);
+ assert!((top90 - 20.0).abs() < 1e-6, "90°: top {top90}");
+ // A thousandth of a degree either side moves the top and the flat by hundredths at most.
+ for deg in [90.0 - 1e-3, 90.0 + 1e-3] {
+ let (top, flat) = build(deg);
+ assert!((top - top90).abs() < 1e-2 && (flat - flat90).abs() < 1e-2, "{deg}°: top {top} flat {flat}, at 90° {top90} {flat90}");
+ }
+}
+
+#[test]
+fn edge_flange_material_outside_and_tangent_positions_start_the_bend_where_they_say() {
+ // T = 2, R = 2, K = 0.4, height 20 from the outer sharp on the edge y = 0. Setback (where the
+ // bend starts, inside the edge): material_outside R·tan(θ/2), tangent R + T, outside 0, and
+ // bend_outside the same as outside. The flange's outermost point (least y) is the setback less
+ // what reaches furthest out: R + T past 90° (the bend's outside a quarter turn in), at 90°
+ // the outer face, R + T. The flat is 60 − setback + θ·(R + K·T) + 20 − (R + T)·tan(θ/2).
+ let (t, r, k) = (2.0, 2.0, 0.4);
+ for deg in [90.0f64, 120.0] {
+ let th = deg.to_radians();
+ let half = (th / 2.0).tan();
+ for (position, setback) in [("material_outside", r * half), ("tangent", r + t), ("outside", 0.0), ("bend_outside", 0.0)] {
+ let what = format!("{deg}° {position}");
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg"), "position": position}));
+ let least_y = bbox(&mut s)["min"][1].as_f64().unwrap_or(f64::NAN);
+ assert!((least_y - (setback - (r + t))).abs() < 1e-6, "{what}: least y {least_y}");
+ let length = flat(&mut s)["flat_size_mm"][1].as_f64().unwrap_or(f64::NAN);
+ let want = 60.0 - setback + th * (r + k * t) + 20.0 - (r + t) * half;
+ assert!((length - want).abs() < 1e-6, "{what}: flat {length}, want {want}");
+ let saved = serde_json::to_value(s.doc.features.last().map(|f| f.kind.clone())).unwrap_or_default();
+ assert_eq!(saved["position"], if position == "bend_outside" { "outside" } else { position }, "{what}");
+ }
+ }
+ // Below 90° the tangent position puts the bend's end on the edge's face: at 60° the setback
+ // is (R + T)·sin 60° = 3.464, the leg 20 − (R + T)·tan 30° = 17.691 leans on out past the
+ // face, so the least y is −leg·cos 60° = −8.845. Through 90° the setback does not jump.
+ let th = 60f64.to_radians();
+ let (setback, leg) = ((r + t) * th.sin(), 20.0 - (r + t) * (th / 2.0).tan());
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": "60 deg", "position": "tangent"}));
+ let least_y = bbox(&mut s)["min"][1].as_f64().unwrap_or(f64::NAN);
+ assert!((least_y + leg * th.cos()).abs() < 1e-6, "60° tangent: least y {least_y}, want {}", -leg * th.cos());
+ let length = flat(&mut s)["flat_size_mm"][1].as_f64().unwrap_or(f64::NAN);
+ let want = 60.0 - setback + th * (r + k * t) + leg;
+ assert!((length - want).abs() < 1e-6, "60° tangent: flat {length}, want {want}");
+ let flat_at = |deg: f64| {
+ let mut s = Session::default();
+ r2_base(&mut s);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20, "angle": format!("{deg} deg"), "position": "tangent"}));
+ flat(&mut s)["flat_size_mm"][1].as_f64().unwrap_or(f64::NAN)
+ };
+ let (below, at, above) = (flat_at(90.0 - 1e-3), flat_at(90.0), flat_at(90.0 + 1e-3));
+ assert!((below - at).abs() < 1e-2 && (above - at).abs() < 1e-2, "flats {below} {at} {above}");
+ // The default is still inside, and an unknown position is refused without a feature.
+ let mut s = Session::default();
+ r2_base(&mut s);
+ let features = s.doc.features.len();
+ let e = s.execute("sheet.flange", &json!({"edges": [[50, 0, 2]], "height": 20, "position": "flush"})).unwrap_err().to_string();
+ assert!(e.contains("`position` must be inside, outside, middle, material_outside or tangent"), "{e}");
+ assert_eq!(s.doc.features.len(), features);
+ run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20}));
+ let saved = serde_json::to_value(s.doc.features.last().map(|f| f.kind.clone())).unwrap_or_default();
+ assert_eq!(saved["position"], "inside");
+ assert!((bbox(&mut s)["min"][1].as_f64().unwrap_or(f64::NAN)).abs() < 1e-6);
+}
+
/// A new fold still refuses a `fixed` point in a cut-out or past the outline, leaving the design
/// untouched (#263); a stored one that drifts off the sheet keeps its side with a warning (#370).
#[test]
diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs
index 3cd8f58ce7..82ee54e051 100644
--- a/crates/ui-egui/src/dialogs_sheet.rs
+++ b/crates/ui-egui/src/dialogs_sheet.rs
@@ -21,8 +21,11 @@ use crate::theme::Tokens;
const FOLD_POSITIONS: [&str; 4] = ["centerline", "start", "end", "mould"];
const FOLD_POSITION_LABELS: [&str; 4] = ["Centerline", "Start of Bend", "End of Bend", "Outside Mould Line"];
const FLANGE_TYPES: [&str; 3] = ["Base", "Edge", "Contour"];
-const POSITIONS: [&str; 3] = ["inside", "outside", "middle"];
-const POSITION_LABELS: [&str; 3] = ["Inside", "Outside", "Middle"];
+const POSITIONS: [&str; 5] = ["inside", "outside", "middle", "material_outside", "tangent"];
+const POSITION_LABELS: [&str; 5] = ["Inside", "Outside", "Middle", "Material Outside", "Tangent to Edge"];
+/// Where an edge flange's height is measured from (`height_from`; the first is the default).
+const HEIGHT_FROM: [&str; 3] = ["outer", "inner", "tangent"];
+const HEIGHT_FROM_LABELS: [&str; 3] = ["Outer Sharp", "Inner Sharp", "Tangent"];
/// Rule fields the manager edits (parameter name, label).
const RULE_FIELDS: [(&str, &str); 8] = [
("thickness", "Thickness"),
@@ -75,6 +78,8 @@ crate::dialog_descriptor::dialog_descriptors! {
angle: String,
radius: String,
position: usize,
+ /// Edge flanges: where the height is measured from (index into `HEIGHT_FROM`).
+ height_from: usize,
flip: bool,
distance: String,
reverse: bool,
@@ -157,6 +162,7 @@ fn new_flange(app: &SolveApp, ty: usize) -> Sm {
angle: "90 deg".into(),
radius: String::new(),
position: 0,
+ height_from: 0,
flip: false,
distance: crate::dialogs::length_default(&app.session, "20"),
reverse: false,
@@ -223,7 +229,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
let t = Tokens::get();
let mut enter = false;
match k {
- Sm::Flange { ty, height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, then } => {
+ Sm::Flange { ty, height, angle, radius, position, height_from, flip, distance, reverse, rule, own, relief, relief_size, then } => {
*ty = flange_type(inputs);
form_row(ui, "Type", |ui| {
ui.label(FLANGE_TYPES.get(*ty).copied().unwrap_or(""));
@@ -233,6 +239,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
enter |= expr_row(ui, "Height", height);
enter |= expr_row(ui, "Angle", angle);
choice_row(ui, "Bend Position", "sm_pos", position, &POSITION_LABELS);
+ choice_row(ui, "Height From", "sm_height_from", height_from, &HEIGHT_FROM_LABELS);
// Further bends: each a flange on the far edge of the one before it.
form_row(ui, "Further Bends", |ui| {
let add = crate::ui_kit::button(ui, "Add bend", crate::ui_kit::Button::Normal)
@@ -605,12 +612,15 @@ fn flange_edges(inputs: &[SelInput], own: &[(Vec3, String, String)]) -> Vec<Valu
pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map<String, Value>) -> Result<Vec<(String, Value)>, String> {
let s = &app.session;
let (cmd, mut p): (&str, Value) = match k {
- Sm::Flange { height, angle, radius, position, flip, distance, reverse, rule, own, relief, relief_size, then, .. } => {
+ Sm::Flange { height, angle, radius, position, height_from, flip, distance, reverse, rule, own, relief, relief_size, then, .. } => {
let mut p = match flange_type(inputs) {
1 => {
let mut p = json!({"type": "edge", "edges": flange_edges(inputs, own), "height": height, "angle": angle,
"position": POSITIONS.get(*position).copied().unwrap_or("inside")});
put(&mut p, &[("radius", radius)]);
+ if let Some(from) = HEIGHT_FROM.get(*height_from).filter(|_| *height_from > 0) {
+ p["height_from"] = json!(from);
+ }
if let Some(shape) = relief.checked_sub(1).and_then(|i| RELIEF_SHAPES.get(i)) {
p["corner_relief_shape"] = json!(shape);
}
@@ -776,7 +786,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
}
(f, curves.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect())
}
- FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief } => {
+ FeatureKind::SheetFlange { edges, height, angle, radius, position, flip, body, corner_relief_shape, corner_relief, height_from } => {
if let Some(b) = body {
extra.insert("body".into(), json!(b));
}
@@ -800,6 +810,10 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
angle: angle.to_string(),
radius: radius.as_deref().map(str::to_string).unwrap_or_default(),
position: POSITIONS.iter().position(|p| p == position).unwrap_or(0),
+ height_from: height_from
+ .as_deref()
+ .and_then(|name| HEIGHT_FROM.iter().position(|h| h.eq_ignore_ascii_case(name.trim())))
+ .unwrap_or(0),
flip: *flip,
distance: crate::dialogs::length_default(&app.session, "20"),
reverse: false,
diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs
index b5093713ce..33fdcba9c5 100644
--- a/crates/ui-egui/src/dialogs_sheet_tests.rs
+++ b/crates/ui-egui/src/dialogs_sheet_tests.rs
@@ -721,6 +721,92 @@ fn add_bend_and_remove_bend_buttons_work() {
assert_eq!(bends(&h).len(), 1, "the bin takes one bend out");
}
+/// The Flange dialog's Height From row: Outer Sharp (the default) asks for nothing, Inner Sharp
+/// reaches the feature, and Edit Feature shows it again.
+#[test]
+fn flange_dialog_measures_the_height_from_the_chosen_datum() {
+ for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] {
+ let mut h = crate::scenario::Harness::new();
+ h.call("ui.set", json!({"layout":mode}));
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap();
+ let edges: Vec<Sel> = edge_sel(&h.app.session, Vec3::new(50.0, 0.0, 2.5)).into_iter().collect();
+ assert_eq!(edges.len(), 1);
+ h.app.session.selection = edges;
+ h.app.start("sheet.flange");
+ h.frames(3);
+ let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) {
+ Some(Kind::Sheet(Sm::Flange { height_from, .. })) => Some(*height_from),
+ _ => None,
+ };
+ assert_eq!(shown(&h.app), Some(0));
+ let d = h.app.dialog.clone().unwrap();
+ let c = apply_commands(&h.app, &d).unwrap();
+ assert!(c[0].1.get("height_from").is_none(), "{}", c[0].1);
+ h.step(&json!({"click": {"handle": "dialog:Height From"}})).unwrap();
+ h.step(&json!({"click": {"handle": "dialog:Height From:Inner Sharp"}})).unwrap();
+ assert_eq!(shown(&h.app), Some(1));
+ let d = h.app.dialog.clone().unwrap();
+ let c = apply_commands(&h.app, &d).unwrap();
+ assert_eq!(c[0].1["height_from"], json!("inner"), "{}", c[0].1);
+ h.step(&json!({"widget": "OK"})).unwrap();
+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog);
+ let saved = |app: &SolveApp| match app.session.doc.features.last().map(|f| &f.kind) {
+ Some(FeatureKind::SheetFlange { height_from, .. }) => height_from.clone(),
+ _ => None,
+ };
+ assert_eq!(saved(&h.app).as_deref(), Some("inner"));
+ // Edit Feature shows Inner Sharp; Tangent then reaches the feature.
+ let id = h.app.session.doc.features.last().map(|f| f.id).unwrap();
+ let mut e = edit_dialog(&h.app, id, None).unwrap();
+ assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { height_from: 1, .. })));
+ let c = apply_commands(&h.app, &e).unwrap();
+ assert_eq!(c[0].1["params"]["height_from"], json!("inner"));
+ if let Kind::Sheet(Sm::Flange { height_from, .. }) = &mut e.kind {
+ *height_from = 2;
+ }
+ let commands = apply_commands(&h.app, &e).unwrap();
+ run_all(&mut h.app, commands);
+ assert_eq!(saved(&h.app).as_deref(), Some("tangent"));
+ }
+}
+
+/// The Flange dialog's Bend Position offers material outside and tangent, and Edit Feature shows them again.
+#[test]
+fn flange_dialog_offers_material_outside_and_tangent_bend_positions() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap();
+ h.app.session.selection = edge_sel(&h.app.session, Vec3::new(50.0, 0.0, 2.5)).into_iter().collect();
+ h.app.start("sheet.flange");
+ h.frames(3);
+ h.step(&json!({"click": {"handle": "dialog:Bend Position"}})).unwrap();
+ h.step(&json!({"click": {"handle": "dialog:Bend Position:Material Outside"}})).unwrap();
+ let d = h.app.dialog.clone().unwrap();
+ let c = apply_commands(&h.app, &d).unwrap();
+ assert_eq!(c[0].1["position"], json!("material_outside"), "{}", c[0].1);
+ h.step(&json!({"widget": "OK"})).unwrap();
+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog);
+ let id = h.app.session.doc.features.last().map(|f| f.id).unwrap();
+ let mut e = edit_dialog(&h.app, id, None).unwrap();
+ assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { position: 3, .. })));
+ if let Kind::Sheet(Sm::Flange { position, .. }) = &mut e.kind {
+ *position = 4;
+ }
+ let commands = apply_commands(&h.app, &e).unwrap();
+ assert_eq!(commands[0].1["params"]["position"], json!("tangent"));
+ run_all(&mut h.app, commands);
+ let saved = match h.app.session.doc.features.last().map(|f| &f.kind) {
+ Some(FeatureKind::SheetFlange { position, .. }) => position.clone(),
+ _ => String::new(),
+ };
+ assert_eq!(saved, "tangent");
+}
+
/// Convert takes a fixed face and, for a solid or shelled body, its bend edges; Edit Feature
/// brings both back.
#[test]
diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md
index c5e134b832..e0ba1e641c 100644
--- a/docs/book/src/guide/sheet-metal.md
+++ b/docs/book/src/guide/sheet-metal.md
@@ -24,6 +24,41 @@ flat pattern. Every copy takes further sheet metal features of its own. Mirrorin
`combine` joins the two halves into one solid, which has no single sheet model yet; mirroring
or patterning flange features themselves is not supported yet.
+An edge flange's `height` runs along the flange to its far edge. Where it is measured from is
+the feature's `height_from` (Height From in the Flange dialog): `outer` (the default, Outer
+Sharp) starts at the outer virtual sharp, where the lines of the base's and the flange's outer
+faces meet, so (R + T)·tan(θ/2) of it is bend before the flat leg starts (θ the bend angle, R
+the inner radius, T the thickness); `inner` (Inner Sharp) starts at the inner virtual sharp,
+R·tan(θ/2) before the leg; `tangent` is for bends past 90°, where the outer sharp runs far
+out: it starts at the line square to the flange that touches the outside of the bend, R + T
+before the leg. Up to 90° `tangent` is the outer sharp (at 90° the two are the same line, the
+base's outer face, so the leg does not jump as the angle passes 90°). A height shorter than
+what lies before the leg is refused with the smallest one that fits. With a 2 mm sheet and a
+2 mm radius, a 90° flange 20 high has a leg of 16 from the outer sharp or the tangent and 18
+from the inner sharp; at 120° it has a leg of 13.07 from the outer sharp, 16.54 from the inner
+sharp and 16 from the tangent.
+
+```json
+{"command":"sheet.flange","params":{"edges":[[50,0,2]],"height":20,"height_from":"inner"}}
+```
+
+Where an edge flange's bend starts is its `position` (Bend Position in the Flange dialog): how
+far inside the picked edge the base is cut back. `inside` (the default) puts the outer virtual
+sharp on the edge, (R + T)·tan(θ/2) inside it, so at 90° the flange's outer face is flush with
+the edge's face; `outside` (`sheet.flange` also takes `bend_outside` and saves it as `outside`) starts the bend at the edge, which
+leaves the base whole and the bend wholly outside; `middle` cuts back half of `inside`;
+`material_outside` puts the inner virtual sharp on the edge, R·tan(θ/2) inside it, so at 90°
+the flange's inner face is flush with the edge's face and its material is outside; `tangent`
+is for bends past 90°: it cuts back R + T, so the outside of the bend is tangent to the edge's
+face, touching it a quarter turn into the bend with nothing of the bend past it. At 90° that
+is `inside`. Below 90° the outside of the bend never turns parallel to the edge's face, so
+`tangent` cuts back (R + T)·sin θ instead: the bend's end is on the edge's face and the leg
+leans on out past it.
+
+```json
+{"command":"sheet.flange","params":{"edges":[[50,0,2]],"height":20,"angle":"120 deg","position":"tangent"}}
+```
+
An edge flange takes its setback off its own edge only. Where that edge ends at an inside
corner of the base (the base runs on past it, like the leg of an L), the rest of the base
stays, and the rule's **bend relief** (`relief_width` and `relief_depth`; Relief Width and