Offset free-form curves and mixed chains: trim folds, round corners (#2149, #2676, #2761, #3159, #3828) (#4156)

* Offset of free-form curves: trim folds, round chain corners

Offsetting a spline by more than its tightest bend failed with "offset spline
has no interior certificate correspondence": the plain offset folds over itself
there and a single linked spline cannot follow it. A chain of Bézier curves (any
imported SVG outline) was refused outright.

Such an offset is now the parallel boundary: the plain offset of every piece,
joined round each corner by an arc about it, trimmed where it folds or crosses
itself (a sharp corner is left), each kept run fitted with an open spline and
certified to the offset tolerance, and the whole proven free of crossings. Tiny
kinks are joined directly; zero-length Bézier handles (infinite curvature at
the end) are replaced by their chord within a quarter of the tolerance. A
single curve whose plain offset is smooth still gets the linked offset; the
trimmed or chained result is ordinary curves, not linked to the source, so the
command adds no distance parameter for it.

* Offset chains mixing lines or arcs with free-form curves

A chain offset read every curve with Sketch::exact_segs, which only covers free-form
curves, so a chain with straight or circular pieces (a text glyph, an SVG path with
L commands) failed with "offset source changed shape". Read them with exact_pieces,
which gives lines and arcs from their analytic form; the trimming already handles
those pieces.
This commit is contained in:
Alexander Puzynia authored and GitHub committed 2026-10-24 21:27:31 +00:00
1 parent 7e24f0e35a
commit 37b7b0bd3e
5 files changed
+1516 -13

No files matched your search

+60 -12
View File
@@ -1810,6 +1810,11 @@ struct Side {
constraints: Vec<String>,
association: Option<String>,
param: Option<String>,
/// Set when the offset is not linked to its source: a free-form curve whose plain offset
/// folds over a tight bend or crosses itself (trimmed), or a chain of curves that
/// includes free-form ones. Its curves then have no association and no distance to
/// drive, and this names the source curves they were made from.
unlinked_sources: Option<Vec<String>>,
}
/// The signed distances an offset runs at. One side is the distance as given. `symmetric` is the
@@ -1846,7 +1851,14 @@ fn offset_side(sk: &mut Sketch, cmd: &str, order: &[(usize, bool)], sources: &[(
cons.push(add_c(sk, ConstraintKind::Parallel { a, b })?);
}
}
return Ok(Side { distance: d, curves: created.curves, constraints: cons, association: Some(created.association), param: None });
return Ok(Side {
distance: d,
curves: created.curves,
constraints: cons,
association: Some(created.association),
param: None,
unlinked_sources: None,
});
}
let pieces: Vec<Piece> =
order.iter().map(|(c, f)| offset_piece(sk, *c, *f, d)).collect::<Option<_>>().ok_or_else(|| bad(cmd, "the offset collapses an arc"))?;
@@ -1942,7 +1954,7 @@ fn offset_side(sk: &mut Sketch, cmd: &str, order: &[(usize, bool)], sources: &[(
sk.offsets.push(solidcraft_sketch::OffsetChain { sources: sources.to_vec(), outputs: outputs.clone(), distance: d, closed, topology: None });
sk.refresh_offsets()?;
}
Ok(Side { distance: d, curves: outputs, constraints: cons, association: None, param: None })
Ok(Side { distance: d, curves: outputs, constraints: cons, association: None, param: None, unlinked_sources: None })
}
/// Numbers remain millimetres for programmatic callers; expressions use design units.
@@ -2015,7 +2027,7 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha
closed: true,
topology: None,
});
sides.push(Side { distance: r - nr, curves: outputs, constraints: Vec::new(), association: None, param: None });
sides.push(Side { distance: r - nr, curves: outputs, constraints: Vec::new(), association: None, param: None, unlinked_sources: None });
}
return Ok(sides);
}
@@ -2043,16 +2055,41 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha
};
let runs = offset_runs(d, symmetric, distance2);
if order.iter().any(|(i, _)| sk.shape(*i).is_none()) {
// A smooth free-form entity is offset from exact pieces. Junctions that
// would require trimming/intersecting independent normal offsets are
// refused rather than joined by a guessed average point.
if order.len() != 1 {
return Err(bad(cmd, "offset smooth free-form curves individually; mixed chain junctions are ambiguous"));
}
let (source, forward) = *order.first().ok_or_else(|| bad(cmd, "no curves"))?;
// A smooth free-form entity is offset from exact pieces. One curve gets a linked
// offset where its plain offset is smooth and simple; otherwise (a fold or a
// crossing to trim, or a chain with corners) the offset is the trimmed parallel
// boundary, rounded at outer corners, and not linked to its source.
let source_ids = order
.iter()
.map(|(i, _)| sk.curves.get(*i).map(|c| c.id.clone()).ok_or_else(|| bad(cmd, "offset source vanished")))
.collect::<Result<Vec<_>>>()?;
let unlinked = |sk: &Sketch, dd: f64, curves: &[usize]| Side {
distance: dd,
curves: ids_of(sk, curves),
constraints: Vec::new(),
association: None,
param: None,
unlinked_sources: Some(source_ids.clone()),
};
for dd in runs {
let output = sk.add_freeform_offset(source, forward, dd)?;
sides.push(Side { distance: dd, curves: ids_of(sk, &[output]), constraints: Vec::new(), association: None, param: None });
let side = match order.as_slice() {
[(source, forward)] => match sk.offset_freeform(*source, *forward, dd)? {
solidcraft_sketch::FreeformOffsetOutput::Linked(output) => Side {
distance: dd,
curves: ids_of(sk, &[output]),
constraints: Vec::new(),
association: None,
param: None,
unlinked_sources: None,
},
solidcraft_sketch::FreeformOffsetOutput::Unlinked(curves) => unlinked(sk, dd, &curves),
},
_ => {
let curves = sk.offset_freeform_chain(&order, dd)?;
unlinked(sk, dd, &curves)
}
};
sides.push(side);
}
return Ok(sides);
}
@@ -2109,6 +2146,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
let eligible = sk.curves.iter().map(|c| c.id.clone()).collect::<std::collections::HashSet<_>>();
let param = doc.new_model_param(&expression, "mm");
let param2 = expression2.as_ref().map(|e| doc.new_model_param(e, "mm"));
let made: Vec<String> = std::iter::once(param.clone()).chain(param2.clone()).collect();
let mut pending = ids.clone();
let mut sides = Vec::new();
while !pending.is_empty() {
@@ -2120,6 +2158,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
.find(|o| o.owns_output(output))
.map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>())
.or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()]))
.or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone()))
.ok_or_else(|| bad(cmd, "offset association is missing"))?;
// An offset of infinite lines is infinite lines too (#1359).
let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite));
@@ -2134,6 +2173,10 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
}
}
for (index, side) in group.iter_mut().enumerate() {
// A trimmed offset is not linked to its source: it has no distance to drive.
if side.unlinked_sources.is_some() {
continue;
}
let name = if index == 1 { param2.as_ref().unwrap_or(&param) } else { &param };
let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?;
side.constraints.push(sk.add_constraint(
@@ -2149,6 +2192,11 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
}
sides.extend(group);
}
// Parameters made for distances that only trimmed (unlinked) offsets used drive nothing.
let used = |name: &String| sides.iter().any(|side: &Side| side.param.as_ref() == Some(name));
let param = used(&param).then_some(param);
let param2 = param2.filter(|name| used(name));
doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name));
Ok((sides, param, param2))
})?;
let curves: Vec<&String> = sides.iter().flat_map(|side| side.curves.iter()).collect();
@@ -2174,3 +2174,160 @@ fn trim_cuts_a_line_at_its_tangent_point_on_a_circle() {
assert_eq!(sketch(&s).curves.len(), 3, "{name}: the circle and both lines stay");
}
}
/// A point midway between an offset output and its source, inside the wall they bound.
fn inside_offset_wall(s: &Session, output: &str) -> Vec2 {
let sk = sketch(s);
let index = sk.curve_index(output).unwrap();
let q = sk.exact_pieces(index)[0].point_at(0.5);
let source: Vec<_> = (0..sk.curves.len()).filter(|i| *i < index && !sk.freeform_offsets.iter().any(|o| o.output == sk.curves[*i].id)).collect();
let p = source
.iter()
.flat_map(|i| sk.exact_pieces(*i))
.flat_map(|seg| (0..=2000).map(move |k| seg.point_at(k as f64 / 2000.0)))
.min_by(|a, b| a.dist(q).total_cmp(&b.dist(q)))
.unwrap();
p.lerp(q, 0.5)
}
#[test]
fn freeform_offsets_trim_folds_and_round_chain_corners_into_an_extrudable_wall() {
// A cookie-cutter outline whose notch near (4.2, 36) bends with a radius of about
// 0.3 mm: 1.26 mm outwards its plain offset folds over itself there. The offset is
// trimmed to the parallel boundary (open splines meeting at a corner), unlinked.
let cookie = json!([
[0, 0],
[-1.6, 12.8],
[-7.4, 23.4],
[-4.8, 26.6],
[-8.6, 39],
[2.8, 41.6],
[4.2, 36],
[11.8, 43.2],
[17.2, 43.2],
[37.2, 24.6],
[38.6, 23],
[35.8, 16.4],
[35.8, 0],
[24.2, 0],
[9.6, 0]
]);
let mut s = new_sketch();
run(&mut s, "sketch.spline.fit_point", json!({"points": cookie, "periodic": true}));
let (before, params) = (s.doc.to_json(), s.doc.params.len());
let out = run(&mut s, "sketch.offset", json!({"curves": ["s1"], "distance": 1.26}));
let curves = ids(&out["curves"]);
assert!(!curves.is_empty(), "{out}");
assert_eq!(out["param"], Value::Null, "a trimmed offset has no distance to drive: {out}");
assert_eq!(out["sketch"]["dof"], 30, "the offset adds no freedom (only the source's fit points move): {out}");
assert_eq!(s.doc.params.len(), params, "no orphan distance parameter");
let sk = sketch(&s);
assert!(sk.freeform_offsets.is_empty() && !sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. })));
// The source and its offset bound the inner region and the wall around it.
let areas = profiles(&s);
assert_eq!(areas.len(), 2, "{areas:?}");
let wall = inside_offset_wall(&s, &curves[0]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), before);
run(&mut s, "edit.redo", json!({}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "profiles": [{"point": [wall.x, wall.y]}]}));
let volume = body_volumes(&mut s);
assert_eq!(volume.len(), 1);
assert!((volume[0] - 10.0 * areas[0]).abs() < 0.01 * volume[0], "{volume:?} for a wall of {} mm²", areas[0]);
// An outline the way drawing programs save it: cubic Bézier curves with two corners,
// a joint kinked by a few thousandths of a degree, and a zero-length handle. Each
// side is the parallel boundary, rounded at outer corners and trimmed at inner ones.
let svg = r#"<svg width="60mm" height="60mm" viewBox="-15 -15 60 60"><path d="M0,0 C10,-5 20,-5 30,0 C35,10 35,20 30,30 C25.0002,40 10,40 5,35 C4,31 8,20 8,20 C0,15 -5,5 0,0 Z"/></svg>"#;
for distance in [1.26, -1.26] {
let mut s = new_sketch();
run(&mut s, "sketch.insert_svg", json!({"text": svg}));
let sources = sketch(&s).curves.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
assert_eq!(sources.len(), 5);
// Picking every curve of the chain makes one offset, not one per curve.
let out = run(&mut s, "sketch.offset", json!({"curves": sources, "distance": distance}));
let curves = ids(&out["curves"]);
let sk = sketch(&s);
assert!(
curves.iter().any(|c| matches!(sk.curves[sk.curve_index(c).unwrap()].kind, CurveKind::Arc { .. })),
"an outer corner is rounded: {out}"
);
assert_eq!(sk.curves.len(), 5 + curves.len());
let source: Vec<_> = (0..5).flat_map(|i| sk.exact_pieces(i)).collect();
for c in &curves {
for seg in sk.exact_pieces(sk.curve_index(c).unwrap()) {
for k in 0..=8 {
let p = seg.point_at(k as f64 / 8.0);
let d = source.iter().flat_map(|s| (0..=2000).map(move |j| s.point_at(j as f64 / 2000.0).dist(p))).fold(f64::INFINITY, f64::min);
assert!((d - 1.26).abs() < solidcraft_sketch::OFFSET_TOLERANCE, "distance {d} at {p:?}");
}
}
}
let areas = profiles(&s);
assert_eq!(areas.len(), 2, "{areas:?}");
let wall = inside_offset_wall(&s, &curves[0]);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "profiles": [{"point": [wall.x, wall.y]}]}));
let volume = body_volumes(&mut s);
let ring = areas.iter().copied().fold(f64::INFINITY, f64::min).min((areas[1] - areas[0]).abs());
assert_eq!(volume.len(), 1);
assert!(volume[0] > 0.0 && (volume[0] - 10.0 * ring).abs() < 0.02 * volume[0], "{volume:?} against {areas:?}");
}
}
#[test]
fn freeform_chain_offsets_take_the_straight_pieces_of_the_chain_along() {
// Outlines mix straight pieces with free-form ones: an SVG path with `L` commands, a
// text glyph (lines and conics). Picking one curve offsets the whole chain, lines too.
let distance = 1.26;
let certified = |s: &Session, curves: &[String]| {
let sk = sketch(s);
let offsets: Vec<usize> = curves.iter().map(|c| sk.curve_index(c).unwrap()).collect();
let source: Vec<_> = (0..sk.curves.len()).filter(|i| !offsets.contains(i)).flat_map(|i| sk.exact_pieces(i)).collect();
for &c in &offsets {
for seg in sk.exact_pieces(c) {
for k in 0..=8 {
let p = seg.point_at(k as f64 / 8.0);
let d = source.iter().flat_map(|s| (0..=2000).map(move |j| s.point_at(j as f64 / 2000.0).dist(p))).fold(f64::INFINITY, f64::min);
assert!((d - distance).abs() < solidcraft_sketch::OFFSET_TOLERANCE, "distance {d} at {p:?}");
}
}
}
};
let svg = r#"<svg width="60mm" height="60mm" viewBox="-15 -15 60 60"><path d="M0,0 L30,0 C35,10 35,20 30,30 L0,30 Z"/></svg>"#;
for d in [distance, -distance] {
let mut s = new_sketch();
run(&mut s, "sketch.insert_svg", json!({"text": svg}));
let sk = sketch(&s);
let kinds = sk.curves.iter().map(|c| matches!(c.kind, CurveKind::Line { .. })).collect::<Vec<_>>();
assert_eq!(kinds, [true, false, true, true], "lines and one Bézier curve");
let line = sk.curves[0].id.clone();
let out = run(&mut s, "sketch.offset", json!({"curves": [line], "distance": d}));
let curves = ids(&out["curves"]);
assert!(!curves.is_empty(), "{out}");
assert_eq!(sketch(&s).curves.len(), 4 + curves.len());
certified(&s, &curves);
let areas = profiles(&s);
assert_eq!(areas.len(), 2, "{areas:?}");
let wall = inside_offset_wall(&s, &curves[0]);
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 10, "profiles": [{"point": [wall.x, wall.y]}]}));
assert_eq!(body_volumes(&mut s).len(), 1);
}
// The letter D: a straight stem and conic bowls, outside and inside.
let mut s = new_sketch();
run(&mut s, "sketch.text", json!({"text": "D", "at": [0, 0], "height": 30}));
let sk = sketch(&s);
assert!(
sk.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { .. }))
&& sk.curves.iter().any(|c| sk.shape(sk.curve_index(&c.id).unwrap()).is_none())
);
let line = sk.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone();
let out = run(&mut s, "sketch.offset", json!({"curves": [line], "distance": distance}));
let curves = ids(&out["curves"]);
assert!(!curves.is_empty(), "{out}");
certified(&s, &curves);
}
+3
View File
@@ -8,6 +8,9 @@ use crate::{CurveKind, Sketch, SketchError, fit_beziers_mode};
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Seg2, Vec2};
mod trim;
pub use trim::FreeformOffsetOutput;
pub const OFFSET_TOLERANCE: f64 = 0.002;
const MAX_PIECES: usize = 256;
const MAX_ASSOCIATIONS: usize = 128;
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -49,7 +49,7 @@ pub use decompose::Budget;
pub use dims::{DimFrame, DimLayout, chain_centres, default_text, dim_frame, dim_layout, dim_layout_reaching, dim_reach, encode_text};
pub use ends::{END_TOL, EndReport, EndTouch, UntiedEnd, loose_ends};
pub use fonts::{DEFAULT_FONT_FAMILY, FontData, families_in, find_style_in, font_data, font_data_styled, installed_families, set_font_file_check};
pub use freeform_offset::{FreeformOffset, OFFSET_TOLERANCE};
pub use freeform_offset::{FreeformOffset, FreeformOffsetOutput, OFFSET_TOLERANCE};
pub use link::{Link, LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES, SKETCH_AXIS_HALF, TextExprs, sketch_axis_geom};
pub use model::{
Constraint, ConstraintKind, Curve, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, PointExprs, SPoint, Sketch, SketchError,