SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sheet metal: a fold crosses slanted or curved edges of any panel (#10621) (#10922)
alfonsotames9e5e143ac3b0
diff --git a/ROADMAP.md b/ROADMAP.mdindex f6726e48f2..0ee1e258ee 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -662,7 +662,9 @@ completed drawings publish atomically. The browser still exports synchronously.pieces survive unfold/refold as one logical sheet group, including split flanged sheets.Cut-outs made in the flat pattern cross bends at any angle or curved: their edges fold tohelices and curves on the bend, their walls square to the sheet. Free-form bases use bounded- sampling.+ sampling. A fold crosses the sheet's own outer edges the same way, slanted or on any curve,+ with the outline exact in the flat pattern and its DXF, and flanges and other folds still go+ on the panels.Parallel prismatic partial-depth cuts retain pocket side and depth through transfer andunfold/refold, with separate pocket contours in preview and DXF. Planar Intersect preservesexact holes and retained islands, including the union of multiple selected profiles, anddiff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rsindex 269e24419e..4d27268e69 100644--- a/crates/doc/src/sheet.rs+++ b/crates/doc/src/sheet.rs@@ -529,6 +529,10 @@ pub struct SheetFlange {/// (flat coordinates, counter-clockwise).#[serde(default, skip_serializing_if = "Option::is_none")]pub exact: Option<Loop2>,+ /// A fold's bend zone as drawn, when a curved edge of the sheet crosses it (flat coordinates,+ /// counter-clockwise): `zone` is this instead of straight ends.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub zone_shape: Option<Loop2>,/// Which feature made it: `F<feature>.<k>` (persistent edge names).#[serde(default, skip_serializing_if = "String::is_empty")]pub tag: String,@@ -834,6 +838,205 @@ fn rect(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Region2 {Region2 { outer: lp, holes: Vec::new() }}+/// How a fold's bend runs along its line `d`: where its start line starts and ends, how far its far+/// edge runs on past those ends, and which ends are cut askew (`SheetFlange::ext`, `tear`).+type FoldEnds = (f64, f64, (f64, f64), (bool, bool));++/// The ends of a fold's zone (`strip`, between the lines at `s0` and `s0 + ba` along `n`) when+/// straight edges of the sheet slant across it, so that it folds as a bend with torn ends. Every+/// corner must lie on one of the two lines: a curved edge has corners in between, and an S of the+/// same area as a straight end would pass on area alone.+fn slanted_zone(strip: &[Vec2], n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option<FoldEnds> {+ let on_line = |q: &Vec2, s: f64| (q.dot(n) - s).abs() <= ZONE_SQUARE_TOL;+ if !strip.iter().all(|q| on_line(q, s0) || on_line(q, s0 + ba)) {+ return None;+ }+ let span = |s: f64| {+ let mut along = strip.iter().filter(|q| on_line(q, s)).map(|q| q.dot(d));+ let first = along.next()?;+ Some(along.fold((first, first), |(lo, hi), u| (lo.min(u), hi.max(u))))+ };+ let ((a0, a1), (e0, e1)) = (span(s0)?, span(s0 + ba)?);+ let (start, far) = (a1 - a0, e1 - e0);+ let trapezoid = (start + far) / 2.0 * ba;+ if start <= ZONE_SQUARE_TOL+ || far <= ZONE_SQUARE_TOL+ || (trapezoid - signed_area(strip).abs()).abs() > 1e-6 * start.max(far).max(1.0) * ba.max(1.0)+ {+ return None;+ }+ let end = |on: f64| if on.abs() > ZONE_SQUARE_TOL { (on, true) } else { (0.0, false) };+ let ((on0, torn0), (on1, torn1)) = (end(a0 - e0), end(e1 - a1));+ Some((a0, a1, (on0, on1), (torn0, torn1)))+}++/// A turn sharper than this (its sine) between two edges of an outline is a corner. Smooth curves+/// and their chords turn less: a chord at the sheet's 0.001 mm tolerance turns about 5° on a 1 mm+/// radius.+const CORNER_TURN: f64 = 0.17;++/// Where two edges of an outline meet at a corner.+fn outline_corners(outline: &Loop2) -> Vec<Vec2> {+ let segs = &outline.segs;+ let mut corners = Vec::new();+ for (i, next) in segs.iter().enumerate() {+ let Some(prev) = segs.get((i + segs.len() - 1) % segs.len()) else { continue };+ let (t0, t1) = (prev.end_tangent(), next.start_tangent());+ if t0.cross(t1).abs() > CORNER_TURN || t0.dot(t1) < 0.0 {+ corners.push(next.start());+ }+ }+ corners+}++/// `seg` in pieces, cut where it crosses the line `level` along `n`, into `out`. A curve that only+/// touches the line stays whole.+fn cut_at_level(seg: &Seg2, n: Vec2, level: f64, out: &mut Vec<Seg2>) {+ const SAMPLES: usize = 64;+ const MAX_CROSSINGS: usize = 16;+ const ON_LINE: f64 = 1e-9;+ let off = |s: &Seg2, t: f64| s.point_at(t).dot(n) - level;+ let mut rest = *seg;+ for _ in 0..MAX_CROSSINGS {+ // The first change of side, skipping samples on the line itself.+ let (mut last, mut crossing) = (None::<(f64, f64)>, None);+ for k in 0..=SAMPLES {+ let t = k as f64 / SAMPLES as f64;+ let v = off(&rest, t);+ if v.abs() <= ON_LINE {+ continue;+ }+ match last {+ Some((was, before)) if before * v < 0.0 => {+ crossing = Some((was, t, before));+ break;+ }+ _ => last = Some((t, v)),+ }+ }+ let Some((mut lo, mut hi, before)) = crossing else { break };+ // On the distance itself: the cut lands on the line, and what's left starts on it.+ for _ in 0..60 {+ let mid = (lo + hi) / 2.0;+ if off(&rest, mid) * before > 0.0 {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ let (first, second) = rest.split_at((lo + hi) / 2.0);+ out.push(first);+ rest = second;+ }+ out.push(rest);+}++/// A panel's outline cut exactly across a fold whose zone a curved edge crosses, each piece+/// keeping its exact curves.+#[derive(Clone, Debug, PartialEq)]+struct CurvedFold {+ fixed: Loop2,+ zone: Loop2,+ moving: Loop2,+ ends: FoldEnds,+}++/// `outline` cut into the side short of the zone between the lines at `s0` and `s0 + ba` along `n`,+/// the zone, and the side past it. It must run from one side through the zone to the other and+/// back through the zone, once: a notch, several tabs on the line or a zone that reaches the+/// outline's tip is `None`. Both of the zone's ends count as torn: their edges aren't square across.+fn curved_fold(outline: &Loop2, n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option<CurvedFold> {+ const ON_LINE: f64 = 1e-6;+ if outline.segs.len() > MAX_FLAT_POINTS {+ return None;+ }+ let outline = outline.ccw();+ let mut pieces = Vec::new();+ for seg in &outline.segs {+ let mut near = Vec::new();+ cut_at_level(seg, n, s0, &mut near);+ for piece in &near {+ cut_at_level(piece, n, s0 + ba, &mut pieces);+ }+ }+ // The band each piece lies in: 0 short of the zone, 1 in it, 2 past it. A piece along either+ // line is an edge square across the bend, not one crossing it.+ let mut bands = Vec::with_capacity(pieces.len());+ for piece in &pieces {+ let v = piece.mid().dot(n);+ if !v.is_finite() || (v - s0).abs() <= ON_LINE || (v - s0 - ba).abs() <= ON_LINE {+ return None;+ }+ bands.push(if v < s0 {+ 0+ } else if v > s0 + ba {+ 2+ } else {+ 1+ });+ }+ // Round the outline from where it enters the side short of the zone.+ let count = pieces.len();+ let first = (0..count).find(|&i| bands.get(i) == Some(&0) && bands.get((i + count - 1) % count) != Some(&0))?;+ let mut runs: Vec<(i32, Vec<Seg2>)> = Vec::new();+ for k in 0..count {+ let i = (first + k) % count;+ let (band, piece) = (*bands.get(i)?, *pieces.get(i)?);+ match runs.last_mut() {+ Some((b, run)) if *b == band => run.push(piece),+ _ => runs.push((band, vec![piece])),+ }+ }+ let [(0, near), (1, there), (2, far), (1, back)] = runs.as_slice() else { return None };+ let ends_of = |run: &[Seg2]| Some((run.first()?.start(), run.last()?.end()));+ let ((near0, near1), (there0, there1), (far0, far1), (back0, back1)) = (ends_of(near)?, ends_of(there)?, ends_of(far)?, ends_of(back)?);+ let on = |q: Vec2, s: f64| (q.dot(n) - s).abs() <= ON_LINE;+ if !(on(near0, s0) && on(near1, s0) && on(far0, s0 + ba) && on(far1, s0 + ba)) {+ return None;+ }+ let closed = |run: &[Seg2], to: Vec2, from: Vec2| {+ let mut segs = run.to_vec();+ segs.push(Seg2::Line { a: to, b: from });+ segs+ };+ let mut zone = closed(there, there1, back0);+ zone.extend_from_slice(back);+ zone.push(Seg2::Line { a: back1, b: there0 });+ let span = |p: Vec2, q: Vec2| (p.dot(d).min(q.dot(d)), p.dot(d).max(q.dot(d)));+ let ((a0, a1), (e0, e1)) = (span(near0, near1), span(far0, far1));+ if a1 - a0 <= ON_LINE || e1 - e0 <= ON_LINE {+ return None;+ }+ Some(CurvedFold {+ fixed: Loop2 { segs: closed(near, near1, near0) },+ zone: Loop2 { segs: zone },+ moving: Loop2 { segs: closed(far, far1, far0) },+ ends: (a0, a1, (a0 - e0, e1 - a1), (true, true)),+ })+}++/// Two counter-clockwise loops joined along a straight edge they share, running opposite ways:+/// every curve of both exactly as it was, which the planar booleans wouldn't hand back.+fn join_along_seam(a: &Loop2, b: &Loop2) -> Option<Loop2> {+ const SAME: f64 = 1e-6;+ if a.segs.len().saturating_mul(b.segs.len()) > MAX_FLAT_POINTS {+ return None;+ }+ for (i, ea) in a.segs.iter().enumerate() {+ let Seg2::Line { a: p, b: q } = *ea else { continue };+ for (j, eb) in b.segs.iter().enumerate() {+ let Seg2::Line { a: r, b: s } = *eb else { continue };+ if p.dist(s) <= SAME && q.dist(r) <= SAME {+ let mut segs = Vec::with_capacity(a.segs.len() + b.segs.len());+ segs.extend(a.segs.iter().skip(i + 1).chain(a.segs.iter().take(i)).cloned());+ segs.extend(b.segs.iter().skip(j + 1).chain(b.segs.iter().take(j)).cloned());+ return Some(Loop2 { segs });+ }+ }+ }+ None+}+/// Round to a 1e-9 mm grid (keeps trimmed edges exactly where the kernel expects them).fn snap(v: Vec2) -> Vec2 {let r = |x: f64| (x * 1e9).round() / 1e9;@@ -1091,6 +1294,9 @@ impl SheetBody {/// Flat region of a flange's bend zone: square across the bend at both ends, but at a torn/// end its far edge ends where the panel's does.pub fn zone(&self, f: &SheetFlange) -> Region2 {+ if let Some(lp) = &f.zone_shape {+ return Region2 { outer: lp.ccw(), holes: Vec::new() };+ }let ba = self.allowance(f);let (u0, u1) = self.zone_span(f);let (a, b) = (f.p + f.d * u0, f.p + f.d * u1);@@ -1107,6 +1313,32 @@ impl SheetBody {(if f.tear.0 { -f.ext.0 } else { u0 }, if f.tear.1 { f.len + f.ext.1 } else { u1 })}+ /// How far a bend's zone reaches along the bend from `p`: a torn end runs askew, and a curved+ /// edge may bulge past both of its ends.+ pub(crate) fn zone_reach(&self, f: &SheetFlange) -> (f64, f64) {+ if let Some(lp) = &f.zone_shape {+ return lp.polyline(1e-3).iter().map(|q| (*q - f.p).dot(f.d)).fold((f64::MAX, f64::MIN), |(lo, hi), u| (lo.min(u), hi.max(u)));+ }+ let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f));+ (u0.min(e0), u1.max(e1))+ }++ /// Where a bend's centre line starts and ends, along the bend from `p`: between the middles+ /// of the bend's two ends (a torn end is askew), or where a curved edge crosses it.+ fn centre_line(&self, f: &SheetFlange) -> (f64, f64) {+ if let Some(lp) = &f.zone_shape {+ let mut at = Vec::new();+ for e in &lp.segs {+ line_hits(f.p + f.n * (self.allowance(f) / 2.0), f.d, e, &mut at);+ }+ if let (Some(lo), Some(hi)) = (at.iter().copied().reduce(f64::min), at.iter().copied().reduce(f64::max)) {+ return (lo, hi);+ }+ }+ let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f));+ ((u0 + e0) / 2.0, (u1 + e1) / 2.0)+ }+/// Folded (in the flat frame, as `fold`), the point of a bend's end (the one at `p`, or the/// other one when `at_end`) at the turn `phi` of the bend and the height `z` in the sheet. A/// torn end runs evenly along the bend while the bend turns, from its start line's end to@@ -1145,7 +1377,9 @@ impl SheetBody {if let Some(shape) = &f.shape&& let Some((lo, hi)) = edge_span(shape, f.p + f.n * self.allowance(f)){- return (span.0.max(lo), span.1.min(hi));+ // A torn end runs askew to where the panel's end starts, so the panel's root doesn't+ // limit the bend there.+ return (if f.tear.0 { span.0 } else { span.0.max(lo) }, if f.tear.1 { span.1 } else { span.1.min(hi) });}span}@@ -1929,6 +2163,60 @@ impl SheetBody {Ok(regions)}+ /// The sheet's panels and bend zones. Where a free-form edge crosses a fold, the zone and the+ /// panels either side are already joined along their seams, so the edge stays the curve it+ /// was drawn as: merged by the planar booleans it would come back as fitted arcs. A seam+ /// another feature changed is left to them.+ fn flat_pieces(&self) -> Result<Vec<Region2>> {+ let mut owners: Vec<Option<usize>> = Vec::new();+ let mut slots: Vec<Option<Region2>> = Vec::new();+ for (pi, r) in self.panels() {+ owners.push(pi);+ slots.push(Some(planar_region(&r)?));+ }+ let panel_slot = |pi: Option<usize>| owners.iter().position(|o| *o == pi);+ let panels = slots.len();+ for f in &self.flanges {+ slots.push(Some(planar_region(&self.zone(f))?));+ }+ // Which slot now holds each: joined pieces live in the one they joined.+ let mut held_by: Vec<usize> = (0..slots.len()).collect();+ let free_form = |slots: &[Option<Region2>], at: usize| slots.get(at).and_then(Option::as_ref).is_some_and(|r| !r.outer.is_line_arc());+ for (i, f) in self.flanges.iter().enumerate() {+ // A fold's pieces share whole seams; an edge flange's bend needn't span its edge.+ if f.shape.is_none() {+ continue;+ }+ let zone = panels + i;+ let sides = [panel_slot(f.parent), panel_slot(Some(i))];+ if !free_form(&slots, zone) && !sides.iter().flatten().any(|&p| free_form(&slots, held_by.get(p).copied().unwrap_or(p))) {+ continue;+ }+ for side in sides.into_iter().flatten() {+ let at = |held_by: &[usize], k: usize| held_by.get(k).copied().unwrap_or(k);+ let (a, b) = (at(&held_by, zone), at(&held_by, side));+ if a == b {+ continue;+ }+ let (Some(Some(ra)), Some(Some(rb))) = (slots.get(a), slots.get(b)) else { continue };+ let Some(joined) = join_along_seam(&ra.outer, &rb.outer) else { continue };+ let holes = ra.holes.iter().chain(&rb.holes).cloned().collect();+ if let Some(slot) = slots.get_mut(a) {+ *slot = Some(Region2 { outer: joined, holes });+ }+ if let Some(slot) = slots.get_mut(b) {+ *slot = None;+ }+ for k in &mut held_by {+ if *k == b {+ *k = a;+ }+ }+ }+ }+ Ok(slots.into_iter().flatten().collect())+ }+pub(crate) fn flat_material(&self) -> Result<Vec<Region2>> {let mut work = FlatWork::new();// Merge structural pieces before cutting: clipping each panel first introduces@@ -1942,16 +2230,12 @@ impl SheetBody {}let mut regions = Vec::new();let mut panel_points = 0usize;- for (_, r) in self.panels() {- let r = planar_region(&r)?;+ for r in self.flat_pieces()? {panel_points = panel_points.saturating_add(region_complexity(std::slice::from_ref(&r))?.1);if panel_points > MAX_FLAT_POINTS {return Err(flat_budget_error());}regions.push(r);- }- for f in &self.flanges {- regions.push(planar_region(&self.zone(f))?);region_complexity(®ions)?;}let regions = material_union(regions, &mut work)?;@@ -2083,9 +2367,7 @@ impl SheetBody {let mut out = Vec::new();for (i, f) in self.flanges.iter().enumerate() {let ba = self.allowance(f);- // The centre line runs between the middles of the bend's two ends (a torn end is askew).- let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f));- let (u0, u1) = ((u0 + e0) / 2.0, (u1 + e1) / 2.0);+ let (u0, u1) = self.centre_line(f);let a = f.p + f.n * (ba / 2.0) + f.d * u0;for (s0, s1) in clear_of(a, f.d, u1 - u0, &cuts) {out.push(BendInfo {@@ -2435,10 +2717,8 @@ impl SheetBody {return Err(DocError::Invalid("not supported yet: a partial side-edge flange beside a cut-out".into()));}let clipped = if side || original.shape.is_some() || original.exact.is_some() {+ // A panel with curves gives way to its 0.001 mm chords here.let region = self.panel(original);- if !region.outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. })) {- return Err(DocError::Invalid("not supported yet: a flange setback on a curved flange panel".into()));- }let points = clip(®ion.outer.ccw().polyline(1e-3), a + inward * by, inward);if points.len() < 3 {return Err(DocError::Invalid("the flange's setback removes the whole panel".into()));@@ -2774,6 +3054,7 @@ impl SheetBody {leg: leg.max(0.0),shape: None,exact: None,+ zone_shape: None,tag: String::new(),ext: (0.0, 0.0),slope: (0.0, 0.0),@@ -3672,6 +3953,7 @@ impl SheetBody {tear: (false, false),shape: None,exact: None,+ zone_shape: None,tag: String::new(),});Ok(self.flanges.len() - 1)@@ -3685,7 +3967,8 @@ impl SheetBody {/// flat). On the base the side holding `fixed` (default: the larger side) stays put; on a/// flange the side toward its own bend does. `flip` folds the other way. A `fixed` point that/// touches no material still picks the side it lies on, and sets `warning` (see- /// [`FOLD_FIXED_OFF_SHEET`]).+ /// [`FOLD_FIXED_OFF_SHEET`]). The outline may cross the zone on straight slanted edges or on+ /// any curve; a sharp corner in the zone is refused, by name.#[allow(clippy::too_many_arguments)]pub fn add_fold(&mut self,@@ -3740,11 +4023,12 @@ impl SheetBody {let pts = dedup(&r.outer.ccw().polyline(1e-3));let (a2, b2) = (Vec2::new(fa.x, fa.y), Vec2::new(fb.x, fb.y));if pts.contains((a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) {- found = Some((pi, inv, a2, b2, pts));+ found = Some((pi, inv, a2, b2, pts, r.outer));break;}}- let (panel, inv, a2, b2, pts) = found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?;+ let (panel, inv, a2, b2, pts, outline) =+ found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?;let d = (b2 - a2).normalized().ok_or_else(|| DocError::Invalid("the fold line has no length".into()))?;let mut n = Vec2::new(-d.y, d.x);let l0 = a2.dot(n);@@ -3797,6 +4081,7 @@ impl SheetBody {tear: (false, false),shape: None,exact: None,+ zone_shape: None,tag: String::new(),};let ba = self.allowance(&probe);@@ -3827,26 +4112,46 @@ impl SheetBody {let angle = if flip { -angle } else { angle };return self.fold_tabs(panel, &pts, (n, d), (s0, ba), span, (angle, radius), &strips);}- // The bend zone must be a rectangle across the panel (a slanted or curved edge would- // run across the bend as a helix, which the sheet's faces can't carry yet).+ // The bend zone is a rectangle across the panel, or straight edges of the sheet slant+ // across it, or curved ones do. Those ends fold to helices and curves, as torn ends and+ // cut-outs across a bend do.let us: Vec<f64> = strip.iter().map(|q| q.dot(d)).collect();let (u0, u1) = (us.iter().cloned().fold(f64::MAX, f64::min), us.iter().cloned().fold(f64::MIN, f64::max));+ let mut ends: FoldEnds = (u0, u1, (0.0, 0.0), (false, false));+ let mut zone_shape = None;+ // An outline with curves is cut exactly, wherever the curves are, so they stay as drawn in+ // the flat pattern; a cut that doesn't come out whole falls back on the chords.+ let cut = if outline.segs.iter().all(|e| matches!(e, Seg2::Line { .. })) { None } else { curved_fold(&outline, n, d, s0, ba) };if ((u1 - u0) * ba - signed_area(&strip).abs()).abs() > 1e-6 * (u1 - u0).max(1.0) * ba.max(1.0) {- // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name- // it and how far the line has to move to clear it.- let corners: Vec<(Vec2, f64)> = pts.iter().map(|q| (*q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect();- if let Some(&(c, _)) = corners.first() {- let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s));- let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s));- let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t));- return Err(DocError::Invalid(format!(- "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \- move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays",- w.x, w.y, w.z- )));+ if let Some(slanted) = slanted_zone(&strip, n, d, s0, ba) {+ ends = slanted;+ } else {+ // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name+ // it and how far the line has to move to clear it.+ let corners: Vec<(Vec2, f64)> =+ outline_corners(&outline).into_iter().map(|q| (q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect();+ if let Some(&(c, _)) = corners.first() {+ let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s));+ let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s));+ let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t));+ return Err(DocError::Invalid(format!(+ "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \+ move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays",+ w.x, w.y, w.z+ )));+ }+ let Some(curved) = &cut else {+ return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into()));+ };+ ends = curved.ends;+ zone_shape = Some(curved.zone.clone());}- return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into()));}+ let (u0, u1, ext, tear) = ends;+ let (fixed_exact, moving_exact) = match cut {+ Some(cut) => (Some(cut.fixed), Some(cut.moving)),+ None => (None, None),+ };let up = !flip;let leg = moving.iter().map(|q| q.dot(n) - s0 - ba).fold(0.0, f64::max);let p0 = n * s0 + d * u0;@@ -3857,11 +4162,14 @@ impl SheetBody {v.into_iter().map(snap).collect::<Vec<_>>()};match panel {- None => self.base = Region2 { outer: Loop2::polygon(&fixed_part).ccw(), holes: self.base.holes.clone() },+ None => {+ self.base =+ Region2 { outer: fixed_exact.clone().unwrap_or_else(|| Loop2::polygon(&fixed_part)).ccw(), holes: self.base.holes.clone() }+ }Some(j) => {if let Some(f) = self.flanges.get_mut(j) {f.shape = Some(ccw(fixed_part.clone()));- f.exact = None;+ f.exact = fixed_exact;}}}@@ -3874,11 +4182,12 @@ impl SheetBody {angle: if up { angle } else { -angle },radius,leg,- ext: (0.0, 0.0),+ ext,slope: (0.0, 0.0),- tear: (false, false),+ tear,shape: Some(ccw(moving)),- exact: None,+ exact: moving_exact,+ zone_shape,tag: String::new(),});let i = self.flanges.len() - 1;@@ -4023,6 +4332,7 @@ impl SheetBody {tear: (false, false),shape: Some(ccw(moving)),exact: None,+ zone_shape: None,tag: String::new(),});}@@ -4779,6 +5089,9 @@ impl SheetBody {if let Some(exact) = &mut f.exact {*exact = flip_x_loop(exact);}+ if let Some(zone) = &mut f.zone_shape {+ *zone = flip_x_loop(zone);+ }}for r in self.holes.iter_mut().chain(self.labels.iter_mut()).chain(self.pockets.iter_mut().map(|p| &mut p.region)) {*r = flip_x_region(r);@@ -4923,6 +5236,7 @@ pub fn contour_flange(body: &str, rule: &str, rv: &RuleValues, plane: &Plane, pttear: (false, false),shape: None,exact: None,+ zone_shape: None,tag: String::new(),};let ba = sheet.allowance(&f);@@ -5599,6 +5913,145 @@ mod tests {}}+ /// Any closed curve the sheet's outlines can hold: a circle, conics, cubics, and a mix.+ fn curved_outlines() -> Vec<(&'static str, Loop2)> {+ let w = std::f64::consts::FRAC_1_SQRT_2;+ let v = |x: f64, y: f64| Vec2::new(x, y);+ let conic = |a: Vec2, apex: Vec2, b: Vec2| Seg2::Conic { a, apex, b, w };+ let ellipse = vec![+ conic(v(80.0, 0.0), v(80.0, 40.0), v(0.0, 40.0)),+ conic(v(0.0, 40.0), v(-80.0, 40.0), v(-80.0, 0.0)),+ conic(v(-80.0, 0.0), v(-80.0, -40.0), v(0.0, -40.0)),+ conic(v(0.0, -40.0), v(80.0, -40.0), v(80.0, 0.0)),+ ];+ let cubic = |p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2| Seg2::Cubic { p0, p1, p2, p3 };+ // An uneven blob: its sides aren't symmetric about the fold or each other.+ let spline = vec![+ cubic(v(70.0, -5.0), v(75.0, 30.0), v(30.0, 55.0), v(0.0, 40.0)),+ cubic(v(0.0, 40.0), v(-30.0, 25.0), v(-90.0, 45.0), v(-85.0, 0.0)),+ cubic(v(-85.0, 0.0), v(-80.0, -45.0), v(-20.0, -60.0), v(0.0, -35.0)),+ cubic(v(0.0, -35.0), v(20.0, -10.0), v(65.0, -40.0), v(70.0, -5.0)),+ ];+ // A D: a straight side the fold runs across, and an arc it also crosses.+ let d_shape = vec![+ Seg2::Line { a: v(-50.0, -50.0), b: v(0.0, -50.0) },+ Seg2::Arc { center: v(0.0, 0.0), radius: 50.0, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI },+ Seg2::Line { a: v(0.0, 50.0), b: v(-50.0, 50.0) },+ Seg2::Line { a: v(-50.0, 50.0), b: v(-50.0, -50.0) },+ ];+ vec![+ ("circle", Loop2::circle(v(0.0, 0.0), 50.0)),+ ("ellipse", Loop2 { segs: ellipse }),+ ("spline", Loop2 { segs: spline }),+ ("D", Loop2 { segs: d_shape }),+ ]+ }++ #[test]+ fn a_curved_outline_is_cut_exactly_across_a_fold_whatever_the_curve() {+ let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0));+ for (name, lp) in curved_outlines() {+ for (s0, ba) in [(-2.8, 5.6), (-30.0, 12.0), (10.0, 1.5)] {+ let cut = curved_fold(&lp, n, d, s0, ba).unwrap_or_else(|| panic!("{name} at {s0}"));+ // The pieces are the outline: nothing lost, nothing doubled, and all closed.+ let area = |l: &Loop2| l.signed_area();+ let sum = area(&cut.fixed) + area(&cut.zone) + area(&cut.moving);+ assert!((sum - lp.signed_area().abs()).abs() < 1e-6, "{name} at {s0}: {sum} vs {}", lp.signed_area());+ for piece in [&cut.fixed, &cut.zone, &cut.moving] {+ assert!(piece.is_closed(1e-9) && piece.is_ccw(), "{name} at {s0}: {piece:?}");+ }+ // Each lies wholly in its band, on the outline's own curves: sampled densely.+ let band = |l: &Loop2, lo: f64, hi: f64| l.polyline(1e-3).iter().all(|q| q.dot(n) >= lo - 1e-6 && q.dot(n) <= hi + 1e-6);+ assert!(band(&cut.fixed, f64::MIN, s0) && band(&cut.zone, s0, s0 + ba) && band(&cut.moving, s0 + ba, f64::MAX), "{name} at {s0}");+ // A curve is cut, not replaced by chords: the same kind of segment comes back.+ let curves = |l: &Loop2| l.segs.iter().filter(|e| !matches!(e, Seg2::Line { .. })).count();+ assert!(curves(&cut.fixed) + curves(&cut.zone) + curves(&cut.moving) >= curves(&lp), "{name} at {s0}");+ assert!(cut.ends.3 == (true, true), "{name}: both ends are torn");+ }+ }+ }++ /// What keeps a flat pattern true: unrolling a bend keeps lengths on its neutral surface, so+ /// a curved edge is as long folded as in the flat there, and only there.+ #[test]+ fn a_curved_edge_keeps_its_length_on_the_neutral_surface() {+ for (name, lp) in curved_outlines() {+ let mut s = plate(10.0, 10.0);+ s.base = Region2 { outer: lp, holes: Vec::new() };+ let t = s.t;+ let mut warning = None;+ let (a, b) = (Vec3::new(5.0, -200.0, t), Vec3::new(5.0, 200.0, t));+ let i =+ s.add_fold(a, b, std::f64::consts::FRAC_PI_2, 3.0, "centerline", false, None, &mut warning).unwrap_or_else(|e| panic!("{name}: {e}"));+ let zone = s.flanges[i].zone_shape.clone().unwrap_or_else(|| panic!("{name}: no exact zone"));+ let neutral = t - s.k * t;+ let mut edges = 0;+ for e in zone.segs.iter().filter(|e| !matches!(zone_edge_kind(&s.flanges[i], e), ZoneEdge::Along)) {+ edges += 1;+ const N: usize = 400;+ let at = |k: usize| e.point_at(k as f64 / N as f64);+ let flat: f64 = (0..N).map(|k| at(k).dist(at(k + 1))).sum();+ let folded = |z: f64| -> f64 { (0..N).map(|k| s.map3(Piece::Zone(i), at(k), z).dist(s.map3(Piece::Zone(i), at(k + 1), z))).sum() };+ assert!((folded(neutral) - flat).abs() < 1e-3, "{name}: {} folded vs {flat} flat", folded(neutral));+ // The test can tell: on the inside of the bend the edge is shorter.+ assert!(flat - folded(t) > 0.05, "{name}: {} on the inside vs {flat} flat", folded(t));+ }+ assert!(edges >= 2, "{name}: {zone:?}");+ }+ }++ #[test]+ fn a_fold_across_an_outline_that_doesnt_pass_through_once_is_refused() {+ let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0));+ let v = |x: f64, y: f64| Vec2::new(x, y);+ let circle = Loop2::circle(v(0.0, 0.0), 50.0);+ // The zone reaches the tip: nothing lies past it, or short of it.+ assert!(curved_fold(&circle, n, d, 49.0, 5.0).is_none());+ assert!(curved_fold(&circle, n, d, -54.0, 5.0).is_none());+ // Wholly off the sheet.+ assert!(curved_fold(&circle, n, d, 60.0, 5.0).is_none());+ // Two tabs on the line: the outline crosses the zone four times.+ let tabs = Loop2::polygon(&[+ v(-10.0, -30.0),+ v(10.0, -30.0),+ v(10.0, -5.0),+ v(-10.0, -5.0),+ v(-10.0, 5.0),+ v(10.0, 5.0),+ v(10.0, 30.0),+ v(-10.0, 30.0),+ v(-20.0, 30.0),+ v(-20.0, -30.0),+ ]);+ assert!(curved_fold(&tabs, n, d, -2.0, 4.0).is_none());+ // An edge square across the bend, along the zone's line.+ let along = Loop2::polygon(&[v(-10.0, -10.0), v(2.0, -10.0), v(2.0, 10.0), v(-10.0, 10.0)]);+ assert!(curved_fold(&along, n, d, -2.0, 4.0).is_none());+ // Numbers that aren't.+ assert!(curved_fold(&circle, n, d, f64::NAN, 5.0).is_none());+ assert!(curved_fold(&Loop2 { segs: Vec::new() }, n, d, 0.0, 5.0).is_none());+ }++ #[test]+ fn a_fold_zone_with_straight_ends_is_told_from_a_curved_or_cornered_one() {+ let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0));+ let zone = |pts: &[(f64, f64)]| slanted_zone(&pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect::<Vec<_>>(), n, d, 0.0, 4.0);+ // Narrowing, widening, leaning one way, and square at one end.+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (-1.0, -1.0), (true, true))));+ assert_eq!(zone(&[(0.0, 1.0), (4.0, 0.0), (4.0, 10.0), (0.0, 9.0)]), Some((1.0, 9.0, (1.0, 1.0), (true, true))));+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 2.0), (4.0, 12.0), (0.0, 10.0)]), Some((0.0, 10.0, (-2.0, 2.0), (true, true))));+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (0.0, -1.0), (false, true))));+ // An S across the zone encloses what the straight end would: its corners give it away.+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (2.0, 10.0), (2.0, 9.0), (0.0, 10.0)]), None);+ // A curved end, as a polyline.+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (3.0, 9.8), (1.0, 9.8), (0.0, 9.0)]), None);+ // Nothing to bend across: the zone comes to a point on either line, or isn't there.+ assert_eq!(zone(&[(0.0, 0.0), (4.0, 5.0), (0.0, 10.0)]), None);+ assert_eq!(zone(&[(0.0, 5.0), (4.0, 0.0), (4.0, 10.0)]), None);+ assert_eq!(zone(&[]), None);+ assert_eq!(zone(&[(f64::NAN, 0.0), (4.0, 0.0), (4.0, 10.0), (0.0, 10.0)]), None);+ }+#[test]fn a_slanted_flat_edge_folds_to_its_exact_helix() {// A 72° flange, inside: the bend's axis runs along x through y = setback, z = T + R,diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rsindex ef9fd60ecd..f818aa521c 100644--- a/crates/doc/src/sheet_convert.rs+++ b/crates/doc/src/sheet_convert.rs@@ -1011,6 +1011,7 @@ pub fn convert_body(slope: (0.0, 0.0),shape: None,exact: None,+ zone_shape: None,tag: String::new(),tear: (false, false),});diff --git a/crates/doc/src/sheet_face_names.rs b/crates/doc/src/sheet_face_names.rsindex 3e37736f5f..f2e4917e9a 100644--- a/crates/doc/src/sheet_face_names.rs+++ b/crates/doc/src/sheet_face_names.rs@@ -68,8 +68,8 @@ impl SheetBody {let Some(inverse) = mat_inverse(&world) else { continue };let q = apply_point(&inverse, p) - o;let u = q.dot(d);- let (u0, u1) = self.zone_span(f);- if u < u0 - tol || u > u1 + tol {+ let (lo, hi) = self.zone_reach(f);+ if u < lo - tol || u > hi + tol {continue;}let radial = q - d * u;diff --git a/crates/engine/src/cmd/sheet_dxf_tests.rs b/crates/engine/src/cmd/sheet_dxf_tests.rsindex 8a99ce6eb1..26a7360542 100644--- a/crates/engine/src/cmd/sheet_dxf_tests.rs+++ b/crates/engine/src/cmd/sheet_dxf_tests.rs@@ -614,3 +614,59 @@ fn bend_lines_can_be_left_out_and_everything_put_on_layer_0() {assert!(s.execute("sheet.export_dxf", &bad).is_err(), "{bad}");}}++/// The DXF of a sheet folded across a curved outer outline has the curve as drawn, not arcs fitted+/// to it, and no seams where the fold cut it: the blank, with its bend line where the bend is.+#[test]+fn a_curved_outline_folded_across_stays_its_curve_in_the_dxf() {+ let blanks: [(&str, &str, Value, &str); 3] = [+ ("circle", "sketch.circle.center", json!({"center": [0, 0], "radius": 50}), "CIRCLE"),+ ("ellipse", "sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40}), "ELLIPSE"),+ (+ "spline",+ "sketch.spline.fit_point",+ json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}),+ "SPLINE",+ ),+ ];+ for (name, id, p, kind) in blanks {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"}));+ run(&mut s, id, p);+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "sheet.flange", json!({"sketch": "Blank"}));+ let flat_loops = loops(&s);+ let area: f64 = flat_loops.iter().map(|l| l.signed_area().abs()).sum();+ run(&mut s, "sheet.fold", json!({"points": [[10, -200, 2.5], [10, 200, 2.5]]}));+ let dxf = export(&mut s, json!({}));+ let es = entities(&dxf);+ assert!(count(&es, kind) >= 1, "{name}: no {kind}: {:?}", es.iter().map(|e| e.0.as_str()).collect::<Vec<_>>());+ if kind != "CIRCLE" {+ assert_eq!(count(&es, "ARC"), 0, "{name}: curves came back as fitted arcs");+ }+ // The only straight line is the bend line, across the sheet on the zone's centre line.+ let lines: Vec<&Entity> = es.iter().filter(|e| e.0 == "LINE").collect();+ assert_eq!(lines.len(), 1, "{name}: seams left in the outline");+ let (a, b) = (point(lines[0], 10), point(lines[0], 11));+ assert!((a.x - 10.0).abs() < 1e-6 && (b.x - 10.0).abs() < 1e-6, "{name}: bend line {a:?} to {b:?}");+ // The blank is the blank: as much of it as was drawn, exactly.+ let after: f64 = loops(&s).iter().map(|l| l.signed_area().abs()).sum();+ assert!((after - area).abs() < 1e-6 * area, "{name}: {after} vs {area}");+ }+}++/// A fold across the straight part of a curved outline keeps the curve as drawn as well: an arc+/// stays one arc, not the 0.001 mm chords a fold used to leave.+#[test]+fn a_curve_away_from_a_fold_stays_its_curve_in_the_dxf() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]}));+ run(&mut s, "sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "sheet.flange", json!({"sketch": "Blank"}));+ run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2.5], [-20, 200, 2.5]]}));+ let es = entities(&export(&mut s, json!({})));+ assert_eq!(count(&es, "ARC"), 1, "{:?}", es.iter().map(|e| e.0.as_str()).collect::<Vec<_>>());+ assert!(count(&es, "LINE") < 12, "the arc went to chords: {} lines", count(&es, "LINE"));+}diff --git a/crates/engine/src/cmd/sheet_face_names_tests.rs b/crates/engine/src/cmd/sheet_face_names_tests.rsindex 6c5d656f3e..87491f601f 100644--- a/crates/engine/src/cmd/sheet_face_names_tests.rs+++ b/crates/engine/src/cmd/sheet_face_names_tests.rs@@ -112,3 +112,23 @@ fn a_flanges_sheet_names_hold_when_another_flange_goes() {assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), None, &gone).is_err());assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), Some("Body2"), &right).is_err());}++/// A fold at 45° across a strip, with a bend zone wide for the strip: about a third of the bend's+/// faces lies beyond the ends of its start line, along the bend, and they still take its names.+#[test]+fn a_bend_askew_across_a_sheet_keeps_its_names() {+ let mut s = Session::default();+ run(&mut s, "sheet.manage_rules", json!({"name": "R10", "thickness": "1 mm", "bend_radius": "10 mm", "active": true}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Strip"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [200, 20]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "sheet.flange", json!({"sketch": "Strip"}));+ run(&mut s, "sheet.fold", json!({"points": [[90, -5, 1], [115, 20, 1]], "fixed": [10, 10, 1]}));+ let fold = s.doc.features.last().map_or(0, |f| f.id);+ let all = faces(&mut s);+ for (side, radius) in [("inner", 10.0), ("outer", 11.0)] {+ let name = format!("sheet:Body1:F{fold}.0:bend.{side}");+ let f = named(&all, &name);+ assert!(f.len() == 1 && f[0].2.is_some_and(|r| (r - radius).abs() < 1e-6), "{name}: {all:?}");+ }+}diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rsindex b3afc4a233..7980e7df71 100644--- a/crates/engine/src/cmd/sheet_tests.rs+++ b/crates/engine/src/cmd/sheet_tests.rs@@ -3094,6 +3094,397 @@ fn fold_at_a_tab_root_names_the_real_cause() {run(&mut ok, "sheet.fold", json!({"points": [[40, 51, 0.8], [60, 51, 0.8]], "fixed": [50, 25, 0.8]}));}+/// The sheet of the folds across slanted edges below: 2 mm thick, R 1, K 0.4.+fn t2_blank(s: &mut Session, outline: Value) {+ run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": "0.4", "active": true}));+ run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"}));+ run(s, "sketch.line", json!({"points": outline, "closed": true}));+ run(s, "sketch.finish", json!({}));+ run(s, "sheet.flange", json!({"sketch": "Blank"}));+}++/// 160 long, 50 wide at x = 0 and 100 wide at x = 160: 12000 mm², and 75 wide at its midline.+fn t2_trapezoid(s: &mut Session) {+ t2_blank(s, json!([[0, -25], [160, -50], [160, 50], [0, 25]]));+}++/// A point on `t2_trapezoid`'s lower slanted side, on the sheet's top.+fn t2_slant(x: f64) -> [f64; 3] {+ [x, -25.0 - 25.0 * x / 160.0, 2.0]+}++/// What the T2 sheet's flat pattern says it weighs. A bend of turn θ takes θ·(R + K·T) of the flat+/// and has θ·T·(R + T/2) of section, so it adds θ·T²·(½ − K) per mm across it; ruled ends keep the+/// zone's mean width at its centre line's length, however askew they are.+fn t2_volume_from_flat(f: &Value) -> f64 {+ let area = |loops: &Value| -> f64 {+ let ring = |l: &Value| {+ let p: Vec<(f64, f64)> =+ l.as_array().into_iter().flatten().map(|q| (q[0].as_f64().unwrap_or(f64::NAN), q[1].as_f64().unwrap_or(f64::NAN))).collect();+ (0..p.len()).map(|i| p[i].0 * p[(i + 1) % p.len()].1 - p[(i + 1) % p.len()].0 * p[i].1).sum::<f64>().abs() / 2.0+ };+ loops.as_array().into_iter().flatten().map(ring).sum()+ };+ let bends: f64 = f["bends"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|b| b["angle_deg"].as_f64().unwrap_or(f64::NAN).to_radians() * 0.4 * b["length"].as_f64().unwrap_or(f64::NAN))+ .sum();+ (area(&f["outline"]) - area(&f["cutouts"])) * 2.0 + bends+}++/// The midline of a trapezoid crosses its slanted sides: the bend zone isn't square across, and+/// the sheet keeps its real outline (#10621).+#[test]+fn a_fold_across_slanted_edges_keeps_the_sheets_outline() {+ let zone = FRAC_PI_2 * 1.8;+ let flat_volume = 12000.0 * 2.0;+ let want = flat_volume + 75.0 * FRAC_PI_2 * 0.4;+ // Both legs are as long, R + T + 80 - BA / 2 high when folded.+ let (wide, narrow) = ([80.0 + zone / 2.0 - 3.0, 160.0], [0.0, 80.0 - zone / 2.0 + 3.0]);+ for (name, fixed, x) in+ [("no side named: the larger stays", None, wide), ("the wide end", Some([150, 0, 0]), wide), ("the narrow end", Some([10, 0, 0]), narrow)]+ {+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ let mut fold = json!({"points": [[80, -60, 2], [80, 60, 2]]});+ if let Some(p) = fixed {+ fold["fixed"] = json!(p);+ }+ run(&mut s, "sheet.fold", fold);+ let v = volume(&mut s);+ assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}");+ let b = bbox(&mut s);+ let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN);+ assert!((at(&b["min"][0]) - x[0]).abs() < 1e-6 && (at(&b["max"][0]) - x[1]).abs() < 1e-6, "{name}: {b}");+ assert!((at(&b["max"][2]) - (3.0 + 80.0 - zone / 2.0)).abs() < 1e-6, "{name}: {b}");+ let f = flat(&mut s);+ assert!((at(&f["flat_size_mm"][0]) - 160.0).abs() < 1e-6 && (at(&f["flat_size_mm"][1]) - 100.0).abs() < 1e-6, "{name}: {f}");+ assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: the outline is the sheet's, not a trimmed rectangle: {f}");+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}");+ assert!((at(&f["bends"][0]["length"]) - 75.0).abs() < 1e-6 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}");+ assert!(rel(t2_volume_from_flat(&f), want) < 1e-9, "{name}: {f}");+ // Flat again it weighs the sheet it was, and it folds back the same.+ run(&mut s, "sheet.unfold", json!({}));+ let unfolded = volume(&mut s);+ assert!(rel(unfolded, flat_volume) < 1e-9, "{name}: unfolded {unfolded}");+ run(&mut s, "sheet.refold", json!({}));+ let refolded = volume(&mut s);+ assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}");+ }+}++/// A fold across slanted edges leaves panels with their real outlines, so flanges and other folds+/// go on it as on any fold, before or after it.+#[test]+fn flanges_and_folds_go_on_a_sheet_folded_across_slanted_edges() {+ let mid = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]});+ let wide = json!({"edges": [[160, 0, 2]], "height": 20});+ let slanted = json!({"edges": [t2_slant(120.0)], "height": 20});+ let flange = "sheet.flange";+ let fold = "sheet.fold";+ let cases: [(&str, Vec<(&str, &Value)>); 3] = [+ ("flange on the wide end after", vec![(fold, &mid), (flange, &wide)]),+ ("flange on the wide end before", vec![(flange, &wide), (fold, &mid)]),+ ("flange on the slanted side after", vec![(fold, &mid), (flange, &slanted)]),+ ];+ let mut volumes = Vec::new();+ for (name, steps) in cases {+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ for (id, p) in steps {+ run(&mut s, id, p.clone());+ }+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: {f}");+ assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "{name}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));+ volumes.push(v);+ }+ // A flange beside the fold: the order doesn't matter.+ assert!(rel(volumes[0], volumes[1]) < 1e-6, "{volumes:?}");++ // A flange along the whole slanted side has its bend where the fold would cross: refused,+ // for that reason, as on a rectangle.+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ run(&mut s, flange, slanted.clone());+ match s.execute(fold, &mid) {+ Ok(v) => panic!("the fold goes through the flange's bend: {v}"),+ Err(e) => assert!(e.to_string().contains("a fold through a flange's bend"), "{e}"),+ }++ // A second fold, 87.5 wide at x = 120 and square to the first, or askew across the same sides.+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ run(&mut s, fold, mid.clone());+ run(&mut s, fold, json!({"points": [[120, -60, 2], [120, 60, 2]], "fixed": [150, 0, 0]}));+ let want = 24000.0 + (75.0 + 87.5) * FRAC_PI_2 * 0.4;+ let v = volume(&mut s);+ assert!(rel(v, want) < 1e-5, "volume {v} vs {want}");+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ run(&mut s, fold, mid.clone());+ run(&mut s, fold, json!({"points": [[100, 60, 2], [140, -60, 2]], "fixed": [155, 0, 0]}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}");+ assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));++ // Askew on the blank itself.+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ run(&mut s, fold, json!({"points": [[60, 60, 2], [100, -60, 2]], "fixed": [155, 0, 0]}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));+}++/// Walls leaning at 70° close the trapezoid's corner on a slanted line, so a fold across the wide+/// end's wall crosses a slanted edge of a flange: the wall widens evenly up to its top, and the+/// bend with it (#10621).+#[test]+fn a_fold_across_a_flanges_slanted_end_folds() {+ let lean = 70f64.to_radians();+ let walls = json!({"edges": [[160, 0, 2], t2_slant(120.0)], "height": 40, "angle": "70 deg"});+ // The wall's outer face, from where the wall alone reaches: its top's outer corner is the+ // farthest out, its inner corner the highest.+ let mut one = Session::default();+ t2_trapezoid(&mut one);+ run(&mut one, "sheet.flange", json!({"edges": [[160, 0, 2]], "height": 40, "angle": "70 deg"}));+ let b = bbox(&mut one);+ let (x_out, z_in) = (b["max"][0].as_f64().unwrap_or(f64::NAN), b["max"][2].as_f64().unwrap_or(f64::NAN));+ let z_out = z_in - 2.0 * lean.cos();+ let mut lengths = Vec::new();+ for z in [14.0, 22.0, 30.0] {+ let mut s = Session::default();+ t2_trapezoid(&mut s);+ run(&mut s, "sheet.flange", walls.clone());+ let x = x_out - (z_out - z) / lean.tan();+ run(&mut s, "sheet.fold", json!({"points": [[x, -90.0, z], [x, 90.0, z]], "angle": "30 deg"}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(3), "z {z}: {f}");+ assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "z {z}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));+ lengths.push(f["bends"][2]["length"].as_f64().unwrap_or(f64::NAN));+ }+ let (rise, more) = (lengths[1] - lengths[0], lengths[2] - lengths[1]);+ assert!(rise > 1e-3 && (rise - more).abs() < 1e-6, "{lengths:?}");+}++/// A blank whose outer outline is curved: `draw` makes it in a sketch, on the T2 sheet.+fn t2_curved_blank(s: &mut Session, draw: &[(&str, Value)], k: &str) {+ run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": k, "active": true}));+ run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"}));+ for (id, p) in draw {+ run(s, id, p.clone());+ }+ run(s, "sketch.finish", json!({}));+ run(s, "sheet.flange", json!({"sketch": "Blank"}));+}++/// A circle or an ellipse as the sheet's outer outline, folded at `x` off its centre. The bend+/// adds θ·T²·(½ − K) per mm of the zone's mean width, which is the material in the zone over BA:+/// for semi-axes a (across the fold) and b, the chord (b / a)·2√(a² − s²) over the zone. The bend+/// allowance sets how high the part that folds stands, so K shows there: compensation.+#[test]+fn a_fold_across_a_round_outer_outline_is_compensated() {+ let circle = ("sketch.circle.center", json!({"center": [0, 0], "radius": 50}));+ let ellipse = ("sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40}));+ for (name, draw, a, b) in [("circle", circle, 50.0_f64, 50.0_f64), ("ellipse", ellipse, 80.0_f64, 40.0_f64)] {+ for (x, k) in [(10.0_f64, 0.4_f64), (-20.0, 0.3), (10.0, 0.5)] {+ let zone = FRAC_PI_2 * (1.0 + k * 2.0);+ let integral = |s: f64| s * (a * a - s * s).sqrt() + a * a * (s / a).asin();+ let in_zone = (b / a) * (integral(x + zone / 2.0) - integral(x - zone / 2.0));+ let want = PI * a * b * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone;+ let mut s = Session::default();+ t2_curved_blank(&mut s, std::slice::from_ref(&draw), &k.to_string());+ run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-(a - 1.0) * x.signum(), 0, 2]}));+ let name = format!("{name} at x = {x}, K {k}");+ // The volume measure works on facets: a flat ellipse reads about 1e-4 low on its own.+ let v = volume(&mut s);+ assert!(rel(v, want) < 3e-4, "{name}: volume {v} vs {want}");+ // The part past the bend stands R + T + its flat length past the zone.+ let leg = a - x.abs() - zone / 2.0;+ let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN);+ assert!((high - (3.0 + leg)).abs() < 1e-3, "{name}: {high} high vs {}", 3.0 + leg);+ // The flat pattern is the blank as drawn, the bend line on the zone's centre line.+ let f = flat(&mut s);+ let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN);+ // (The size is measured on 0.001 mm chords, so up to that short on each side.)+ assert!((at(&f["flat_size_mm"][0]) - 2.0 * a).abs() < 2.5e-3 && (at(&f["flat_size_mm"][1]) - 2.0 * b).abs() < 2.5e-3, "{name}: {f}");+ let chord = 2.0 * b * (1.0 - (x / a).powi(2)).sqrt();+ assert!((at(&f["bends"][0]["length"]) - chord).abs() < 1e-3 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}");+ assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: {f}");+ run(&mut s, "sheet.unfold", json!({}));+ let unfolded = volume(&mut s);+ assert!(rel(unfolded, PI * a * b * 2.0) < 3e-4, "{name}: unfolded {unfolded}");+ run(&mut s, "sheet.refold", json!({}));+ let refolded = volume(&mut s);+ assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}");+ }+ }+}++/// Any curve, not only conics: a closed spline, an open spline closed by a line, an arc with lines,+/// each folded where its curves cross the zone, then folded again.+#[test]+fn a_fold_crosses_any_curve_of_the_outer_outline() {+ let spline = vec![(+ "sketch.spline.fit_point",+ json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}),+ )];+ let open = vec![+ ("sketch.spline.fit_point", json!({"points": [[-60, 0], [-30, 45], [10, 30], [60, 50]]})),+ ("sketch.line", json!({"points": [[60, 50], [60, -30], [-60, -30], [-60, 0]]})),+ ];+ let d_shape = vec![+ ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})),+ ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})),+ ];+ for (name, draw, line_at) in [("closed spline", spline, 5.0), ("open spline and lines", open, 7.0), ("arc and lines", d_shape, 20.0)] {+ let mut s = Session::default();+ t2_curved_blank(&mut s, &draw, "0.4");+ let flat_volume = volume(&mut s);+ run(&mut s, "sheet.fold", json!({"points": [[line_at, -200, 2], [line_at, 200, 2]]}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}");+ // The bend adds what it adds to the flat sheet, here on a centre line that varies little.+ let gain = v - flat_volume;+ let want = f["bends"][0]["length"].as_f64().unwrap_or(f64::NAN) * FRAC_PI_2 * 0.4;+ assert!((gain - want).abs() < 0.03 * want + 1.5, "{name}: gained {gain} vs {want}");+ // Flat again it weighs what it did, and it folds back the same.+ run(&mut s, "sheet.unfold", json!({}));+ let unfolded = volume(&mut s);+ assert!(rel(unfolded, flat_volume) < 3e-4, "{name}: unfolded {unfolded} vs {flat_volume}");+ run(&mut s, "sheet.refold", json!({}));+ let refolded = volume(&mut s);+ assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}");+ // A second fold across the part that stayed, where the curves cross it too.+ run(&mut s, "sheet.fold", json!({"points": [[line_at - 30.0, -200, 2], [line_at - 30.0, 200, 2]], "fixed": [line_at - 50.0, 0, 2]}));+ let f = flat(&mut s);+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: second fold: {f}");+ }+}++/// A curved outline with a hole across the zone: the bend adds what the material in the zone+/// holds, between the outline's chord and the hole's.+#[test]+fn a_cut_out_crosses_a_fold_across_a_round_outer_outline() {+ let (r, hole, x, k) = (50.0_f64, 15.0_f64, 10.0_f64, 0.4_f64);+ let zone = FRAC_PI_2 * (1.0 + k * 2.0);+ let integral = |a: f64, s: f64| {+ let s = s.clamp(-a, a);+ s * (a * a - s * s).sqrt() + a * a * (s / a).asin()+ };+ let in_zone = integral(r, x + zone / 2.0) - integral(r, x - zone / 2.0) - (integral(hole, zone / 2.0) - integral(hole, -zone / 2.0));+ let want = PI * (r * r - hole * hole) * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone;+ let mut s = Session::default();+ t2_curved_blank(&mut s, &[("sketch.circle.center", json!({"center": [0, 0], "radius": r}))], "0.4");+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"}));+ run(&mut s, "sketch.circle.center", json!({"center": [x, 0], "radius": hole}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]}));+ run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-49, 0, 2]}));+ let v = volume(&mut s);+ assert!(rel(v, want) < 3e-4, "volume {v} vs {want}");+ let f = flat(&mut s);+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "the hole parts the bend line: {f}");+}++/// Curves away from the zone stay curves too, and a flange still goes on either side of a fold+/// across the straight part of a curved outline (the side with the arc gives way to chords).+#[test]+fn flanges_go_on_a_curved_outline_folded_across_its_straight_part() {+ let d_shape = vec![+ ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})),+ ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})),+ ];+ let fold = json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [-50, 0, 2]});+ // The side that stays is square; the arc goes up with the side that folds.+ let mut s = Session::default();+ t2_curved_blank(&mut s, &d_shape, "0.4");+ run(&mut s, "sheet.fold", fold.clone());+ run(&mut s, "sheet.flange", json!({"edges": [[-60, 0, 2]], "height": 20}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}");+ assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));+ // The side with the arc stays; the flange goes on the square side that folded.+ let mut s = Session::default();+ t2_curved_blank(&mut s, &d_shape, "0.4");+ run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]}));+ let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN);+ run(&mut s, "sheet.flange", json!({"edges": [[-20.0 + FRAC_PI_2 * 0.9 - 3.0, 0, high]], "height": 20}));+ let (v, f) = (volume(&mut s), flat(&mut s));+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}");+ assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f));+}++/// A sharp corner in the zone stays refused, by name: the material beside it wouldn't hang from+/// anything. A fold clear of it, on the same outline, folds. Where the lines run smoothly into the+/// arc is no corner.+#[test]+fn a_corner_of_a_curved_outline_in_the_zone_is_named() {+ let stepped = vec![+ ("sketch.line", json!({"points": [[0, 50], [-20, 50], [-20, 30], [-60, 30], [-60, -30], [-20, -30], [-20, -50], [0, -50]]})),+ ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})),+ ];+ let mut s = Session::default();+ t2_curved_blank(&mut s, &stepped, "0.4");+ match s.execute("sheet.fold", &json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]})) {+ Ok(v) => panic!("the zone holds the corners at x = -20: {v}"),+ Err(e) => assert!(e.to_string().contains("corner of the sheet's outline"), "{e}"),+ }+ run(&mut s, "sheet.fold", json!({"points": [[0, -200, 2], [0, 200, 2]], "fixed": [40, 0, 2]}));+}++/// A circle or an ellipse cut out across a fold that crosses slanted edges, before the fold or in+/// the flat after it: the outline's edges and the cut-out's both cross the bend.+#[test]+fn round_cut_outs_cross_a_fold_across_slanted_edges() {+ let zone = FRAC_PI_2 * 1.8;+ let fold = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]});+ let cut = |s: &mut Session, draw: &(&str, Value)| {+ run(s, "sketch.create", json!({"plane": "XY", "name": "Hole"}));+ run(s, draw.0, draw.1.clone());+ run(s, "sketch.finish", json!({}));+ run(s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]}));+ };+ let circle = ("sketch.circle.center", json!({"center": [80, 0], "radius": 15}));+ let ellipse = ("sketch.ellipse", json!({"center": [80, 0], "major": [100, 0], "minor_radius": 10}));+ for (name, draw, a, b) in [("circle", circle, 15.0_f64, 15.0_f64), ("ellipse", ellipse, 20.0_f64, 10.0_f64)] {+ // What it takes out of the zone: its chord (b / a)·2√(a² − s²) across s in ±BA / 2.+ let h = zone / 2.0;+ let in_zone = 2.0 * (b / a) * (h * (a * a - h * h).sqrt() + a * a * (h / a).asin());+ let flat_volume = (12000.0 - PI * a * b) * 2.0;+ let want = flat_volume + (75.0 - in_zone / zone) * FRAC_PI_2 * 0.4;++ let mut before = Session::default();+ t2_trapezoid(&mut before);+ cut(&mut before, &draw);+ run(&mut before, "sheet.fold", fold.clone());+ let v = volume(&mut before);+ assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}");+ // One cut-out, and the centre line in two pieces either side of it.+ let f = flat(&mut before);+ assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(1), "{name}: {f}");+ let bends = f["bends"].as_array().cloned().unwrap_or_default();+ let length: f64 = bends.iter().map(|b| b["length"].as_f64().unwrap_or(f64::NAN)).sum();+ assert!(bends.len() == 2 && (length - (75.0 - 2.0 * b)).abs() < 1e-3, "{name}: {f}");+ run(&mut before, "sheet.unfold", json!({}));+ // A round hole's volume is measured on its facets: 0.235 mm³ over for this circle, as on+ // a plain rectangle.+ let unfolded = volume(&mut before);+ assert!(rel(unfolded, flat_volume) < 2e-5, "{name}: unfolded {unfolded} vs {flat_volume}");++ let mut after = Session::default();+ t2_trapezoid(&mut after);+ run(&mut after, "sheet.fold", fold.clone());+ run(&mut after, "sheet.unfold", json!({}));+ cut(&mut after, &draw);+ run(&mut after, "sheet.refold", json!({}));+ let refolded = volume(&mut after);+ assert!(rel(refolded, want) < 1e-5, "{name}: refolded {refolded} vs {want}");+ }+}+/// #296: two bends meeting at an open corner relief touch only along an edge, so the folded/// material the machining guard checks must not be sewn into one solid.#[test]