A line and a circle or arc can now be dimensioned to the circle's edge (ConstraintKind::LineCircleDistance, saved as line_circle_distance): the gap while the line misses the circle (0 is tangency), or how far the edge reaches past the line when it cuts through (stored as `inside`). Rebased onto main as one commit (the branch's own changes; its merges of main dropped). Conflicts resolved: the test mod lines in cmd/sketch.rs (both kept, sorted), and README.md, whose feature list main moved to docs/capabilities.md; the line-to-circle dimension is listed there now. Claude-Session: https://claude.ai/code/session_01QWhMwdqJYQKQq8RCLSL1LT Co-authored-by: jyviko <jyviko@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -229,6 +229,9 @@ completed drawings publish atomically. The browser still exports synchronously.
|
||||
Type a value and press Enter to commit one undo step; rejected values remain editable and
|
||||
cancellation leaves the sketch unchanged. Fit keeps geometry clear of the Sketch Palette
|
||||
and navigation controls, including enlarged displays and nested pending placements.
|
||||
- Sketch Dimension takes a line and a circle or arc (#1803): it measures from the line to the
|
||||
circle's edge (the gap, 0 when tangent, or how far the edge reaches past a line that cuts
|
||||
it), drives it like any other dimension and keeps the circle on its side of the line.
|
||||
- Sketch annotations, live drawing lengths and Measure use document units. Inches show
|
||||
three decimals and retain a meaningful fourth digit. Bare length dimension entry captures
|
||||
the current design unit; changing units leaves existing geometry and expressions intact.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
//! A sketch can hold a `line_circle_distance` dimension (#1803): the distance from a line `l` to
|
||||
//! the edge of a circle or arc `c`, saved with its `value` and, when the line cuts the circle,
|
||||
//! `inside` (the value is then how far the edge reaches past the line). Older designs need no
|
||||
//! transformation: they have no such dimension; 0.16.x (which reads up to 27) asks for an update
|
||||
//! instead of meeting a constraint type it doesn't know.
|
||||
@@ -111,7 +111,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())),
|
||||
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
|
||||
"entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
|
||||
"entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
|
||||
),
|
||||
CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)
|
||||
.at("SKETCH", "CONSTRAINTS")
|
||||
@@ -1976,6 +1976,7 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let is_line = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Line { .. }));
|
||||
let is_circle = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Circle { .. }));
|
||||
let is_round = |c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Arc { .. }));
|
||||
// The other reading of an angle between two lines (see below).
|
||||
let mut alt: Option<(ConstraintKind, f64)> = None;
|
||||
let (mut k, mut cur): (ConstraintKind, f64) = match (e0, e1) {
|
||||
@@ -2085,6 +2086,16 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A line and a circle or arc: the distance from the line to its edge (#1803).
|
||||
((None, Some(l)), Some((None, Some(c)))) | ((None, Some(c)), Some((None, Some(l)))) if is_line(l) && is_round(c) => {
|
||||
let (a, b) = line_pts(sk, l).unwrap_or_default();
|
||||
let (centre, r) = sk.center(c).zip(sk.radius(c)).ok_or_else(|| bad(cmd, "cannot dimension that curve"))?;
|
||||
let d = (b - a).normalized().map(|u| u.cross(centre - a).abs()).ok_or_else(|| bad(cmd, "that line has no length"))?;
|
||||
// A line that cuts the circle measures how far its edge reaches past the line.
|
||||
let inside = d < r;
|
||||
let gap = (d - r).abs();
|
||||
(ConstraintKind::LineCircleDistance { l, c, value: gap, inside }, gap)
|
||||
}
|
||||
_ => return Err(bad(cmd, "cannot dimension that combination of entities")),
|
||||
};
|
||||
let is_angle = k.is_angle();
|
||||
@@ -2598,6 +2609,9 @@ mod ids_tests;
|
||||
#[path = "sketch_infinite_tests.rs"]
|
||||
mod infinite_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_line_circle_tests.rs"]
|
||||
mod line_circle_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_point_expr_tests.rs"]
|
||||
mod point_expr_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -448,6 +448,7 @@ fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option<Vec2> {
|
||||
}
|
||||
Distance { p, q, .. } | DistanceX { p, q, .. } | DistanceY { p, q, .. } => Some((pt(p)? + pt(q)?) * 0.5),
|
||||
PointLineDistance { p, .. } | LinearDiameter { p, .. } => pt(p),
|
||||
LineCircleDistance { c, .. } => sk.center(c),
|
||||
Length { l, .. } | LineAngle { l, .. } => mid(l),
|
||||
Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } | ArcSweep { c, .. } => mid(c),
|
||||
SlotOverallLength { a, b, .. } => Some((sk.center(a)? + sk.center(b)?) * 0.5),
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Sketch Dimension from a line to the edge of a circle or arc (#1803): `sketch.dimension` with
|
||||
//! a line and a circle or arc measures the gap to the edge (or how far the edge reaches past a
|
||||
//! line that cuts it), drives it, follows its parameter, and survives undo and reopening.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec2;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn sketch(s: &Session) -> solidcraft_sketch::Sketch {
|
||||
s.model.state().sketch(s.active_sketch.unwrap()).unwrap().sketch.clone()
|
||||
}
|
||||
|
||||
fn point(s: &Session, id: &str) -> Vec2 {
|
||||
let sk = sketch(s);
|
||||
sk.resolve_point(id).and_then(|p| sk.point(p)).unwrap()
|
||||
}
|
||||
|
||||
/// A fixed line along x from (0, 0) to (40, 0) (`l1`) and a circle of diameter 10 at `centre`
|
||||
/// (`c1`).
|
||||
fn line_and_circle(centre: [f64; 2]) -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1"]}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": centre, "radius": 5}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["c1"], "type": "diameter", "value": 10}));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_and_a_circle_dimension_to_its_edge() {
|
||||
let mut s = line_and_circle([20.0, 15.0]);
|
||||
// Centre 15 above the line, radius 5: the gap to the edge is 10.
|
||||
let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"]}));
|
||||
assert_eq!(r["type"], "LinearDimension", "{r}");
|
||||
assert_eq!(r["measured"], 10.0, "{r}");
|
||||
let param = r["param"].as_str().unwrap().to_string();
|
||||
assert_eq!(r["expression"], "10 mm", "{r}");
|
||||
// The parameter drives the gap: 7 puts the centre 7 + 5 = 12 above the line.
|
||||
run(&mut s, "parameters.change", json!({"name": param, "expression": "7 mm"}));
|
||||
assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 12.0)) < 1e-7, "{:?}", point(&s, "c1.center"));
|
||||
// The circle and the line in the other order, with a value.
|
||||
let mut s = line_and_circle([20.0, 15.0]);
|
||||
let r = run(&mut s, "sketch.dimension", json!({"entities": ["c1", "l1"], "value": 3}));
|
||||
assert_eq!(r["measured"], 3.0, "{r}");
|
||||
assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 8.0)) < 1e-7, "{:?}", point(&s, "c1.center"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_cuts_the_circle_dimensions_how_far_the_edge_reaches_past_it() {
|
||||
// Centre 3 above the line, radius 5: the edge reaches 2 below the line.
|
||||
let mut s = line_and_circle([20.0, 3.0]);
|
||||
let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"]}));
|
||||
assert_eq!(r["measured"], 2.0, "{r}");
|
||||
let param = r["param"].as_str().unwrap().to_string();
|
||||
run(&mut s, "parameters.change", json!({"name": param, "expression": "4"}));
|
||||
// Reaching 4 past the line leaves the centre 1 above it; it never crosses the line.
|
||||
assert!(point(&s, "c1.center").dist(Vec2::new(20.0, 1.0)) < 1e-7, "{:?}", point(&s, "c1.center"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_dimensions_to_its_circle() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
|
||||
run(&mut s, "sketch.arc.center_point", json!({"center": [20, 20], "start": [26, 20], "end": [14, 20]}));
|
||||
let r = run(&mut s, "sketch.dimension", json!({"entities": ["a1", "l1"]}));
|
||||
assert_eq!(r["measured"], 14.0, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dimension_undoes_and_reopens() {
|
||||
let mut s = line_and_circle([20.0, 15.0]);
|
||||
let before = sketch(&s).constraints.len();
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"], "value": 6}));
|
||||
let saved = s.doc.to_json();
|
||||
assert!(saved.contains("\"line_circle_distance\""), "not saved");
|
||||
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
|
||||
run(&mut reopened, "sketch.edit", json!({"sketch": "Sketch1"}));
|
||||
assert!(point(&reopened, "c1.center").dist(Vec2::new(20.0, 11.0)) < 1e-7, "{:?}", point(&reopened, "c1.center"));
|
||||
let kinds = |s: &Session| sketch(s).constraints.iter().map(|c| c.kind.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(kinds(&reopened), kinds(&s));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(sketch(&s).constraints.len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_the_sketch_already_has_is_refused_or_driven() {
|
||||
// A tangent circle already has a gap of zero.
|
||||
let mut s = line_and_circle([20.0, 5.0]);
|
||||
run(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "c1"}));
|
||||
let err = s.execute("sketch.dimension", &json!({"entities": ["l1", "c1"]})).unwrap_err().to_string();
|
||||
assert!(err.contains("already determined"), "{err}");
|
||||
let r = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "c1"], "if_redundant": "driven"}));
|
||||
assert_eq!(r["driven"], true, "{r}");
|
||||
assert!(r["measured"].as_f64().unwrap().abs() < 1e-7, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_and_a_curve_that_is_not_round_is_still_refused() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
|
||||
run(&mut s, "sketch.ellipse", json!({"center": [20, 20], "major": [30, 20], "minor_radius": 4}));
|
||||
let err = s.execute("sketch.dimension", &json!({"entities": ["l1", "e1"]})).unwrap_err().to_string();
|
||||
assert!(err.contains("cannot dimension that combination"), "{err}");
|
||||
}
|
||||
@@ -92,6 +92,17 @@ pub fn dim_frame(sk: &Sketch, k: &ConstraintKind) -> Option<DimFrame> {
|
||||
let p0 = if matches!(k, LinearDiameter { .. }) { foot * 2.0 - q } else { foot };
|
||||
DimFrame::Linear { p0, p1: q, dir: unit(q - foot, d.perp()) }
|
||||
}
|
||||
LineCircleDistance { l, c, .. } => {
|
||||
// From the line to the circle's edge point nearest it (beyond it when the line cuts
|
||||
// the circle), along the line's normal.
|
||||
let (a, b) = line_ends(sk, l)?;
|
||||
let (centre, r) = (sk.center(c)?, sk.radius(c)?);
|
||||
let d = unit(b - a, Vec2::X);
|
||||
let normal = unit(centre - (a + d * (centre - a).dot(d)), d.perp());
|
||||
let p1 = centre - normal * r;
|
||||
let p0 = a + d * (p1 - a).dot(d);
|
||||
DimFrame::Linear { p0, p1, dir: unit(p1 - p0, normal) }
|
||||
}
|
||||
Radius { c, .. } | Diameter { c, .. } => {
|
||||
let radius = match sk.curves.get(c)?.kind {
|
||||
CurveKind::Ellipse { r, .. } => r,
|
||||
@@ -187,6 +198,7 @@ pub fn dim_reach(sk: &Sketch, k: &ConstraintKind) -> [Option<(Vec2, Vec2)>; 2] {
|
||||
let (p, l, to_line) = match *k {
|
||||
PointLineDistance { p, l, .. } => (p, l, true),
|
||||
LinearDiameter { p, l, .. } => (p, l, false),
|
||||
LineCircleDistance { l, .. } => return [line_ends(sk, l), None],
|
||||
_ => return [None, None],
|
||||
};
|
||||
let Some((a, b)) = line_ends(sk, l) else { return [None, None] };
|
||||
|
||||
@@ -83,6 +83,8 @@ mod font_tests;
|
||||
#[cfg(test)]
|
||||
mod least_motion_tests;
|
||||
#[cfg(test)]
|
||||
mod line_circle_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod thin_tests;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! The distance from a line to the edge of a circle or arc (#1803): solved numerically and by
|
||||
//! construction, measured, kept on its side of the line through edits, and refused on other
|
||||
//! kinds of curve.
|
||||
|
||||
use solidcraft_geom::Vec2;
|
||||
|
||||
use crate::tests::v;
|
||||
use crate::*;
|
||||
|
||||
/// A fixed line along x from (0, 0) to (40, 0) and a circle of radius `r` at `centre` (its
|
||||
/// centre free, its radius set by a dimension). The line, the circle and the centre point.
|
||||
fn line_and_circle(centre: Vec2, r: f64) -> (Sketch, usize, usize, usize) {
|
||||
let mut sk = Sketch::new();
|
||||
let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap();
|
||||
let (a, b) = sk.curves[l].kind.ends().unwrap();
|
||||
for p in [a, b] {
|
||||
sk.add_constraint(ConstraintKind::Fix { p }, None).unwrap();
|
||||
}
|
||||
let c = sk.add_circle(centre, r, None, None).unwrap();
|
||||
let CurveKind::Circle { c: ci, .. } = sk.curves[c].kind else { panic!("not a circle") };
|
||||
sk.add_constraint(ConstraintKind::Radius { c, value: r }, None).unwrap();
|
||||
(sk, l, c, ci)
|
||||
}
|
||||
|
||||
fn kind_at(sk: &Sketch, k: usize) -> ConstraintKind {
|
||||
sk.constraints[k].kind.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_to_circle_distance_places_the_circle_its_gap_from_the_line() {
|
||||
let (mut sk, l, c, ci) = line_and_circle(v(20.0, 15.0), 5.0);
|
||||
let k = sk.constraints.len();
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 10.0, inside: false }, None).unwrap();
|
||||
// As drawn the gap is 15 − 5 = 10: the sketch already holds it.
|
||||
assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 10.0).abs() < 1e-9);
|
||||
assert!(solve(&mut sk).ok());
|
||||
// A gap of 7 puts the centre 7 + 5 = 12 from the line, on the side it was drawn on.
|
||||
sk.constraints[k].kind.set_value(7.0);
|
||||
let rep = solve(&mut sk);
|
||||
assert!(rep.ok(), "{rep:?}");
|
||||
let centre = sk.points[ci].pos;
|
||||
assert!((centre.y - 12.0).abs() < 1e-7, "{centre:?}");
|
||||
assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 7.0).abs() < 1e-7);
|
||||
// Tangent: a gap of zero.
|
||||
sk.constraints[k].kind.set_value(0.0);
|
||||
assert!(solve(&mut sk).ok());
|
||||
assert!((sk.points[ci].pos.y - 5.0).abs() < 1e-7, "{:?}", sk.points[ci].pos);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_below_the_line_stays_below_it() {
|
||||
let (mut sk, l, c, ci) = line_and_circle(v(20.0, -15.0), 5.0);
|
||||
let k = sk.constraints.len();
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 10.0, inside: false }, None).unwrap();
|
||||
assert!(solve(&mut sk).ok());
|
||||
sk.constraints[k].kind.set_value(3.0);
|
||||
assert!(solve(&mut sk).ok());
|
||||
assert!((sk.points[ci].pos.y + 8.0).abs() < 1e-7, "{:?}", sk.points[ci].pos);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_cuts_the_circle_measures_how_far_its_edge_reaches_past_it() {
|
||||
// Centre 3 above the line, radius 5: the edge reaches 5 − 3 = 2 below the line.
|
||||
let (mut sk, l, c, ci) = line_and_circle(v(20.0, 3.0), 5.0);
|
||||
let k = sk.constraints.len();
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: true }, None).unwrap();
|
||||
assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 2.0).abs() < 1e-9);
|
||||
assert!(solve(&mut sk).ok());
|
||||
// Reaching 4 past the line leaves the centre 5 − 4 = 1 above it.
|
||||
sk.constraints[k].kind.set_value(4.0);
|
||||
let rep = solve(&mut sk);
|
||||
assert!(rep.ok(), "{rep:?}");
|
||||
assert!((sk.points[ci].pos.y - 1.0).abs() < 1e-7, "{:?}", sk.points[ci].pos);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_is_measured_to_its_circle() {
|
||||
let mut sk = Sketch::new();
|
||||
let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap();
|
||||
let a = sk.add_arc(v(20.0, 20.0), v(26.0, 20.0), v(14.0, 20.0), [None; 3], None).unwrap();
|
||||
let k = sk.constraints.len();
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c: a, value: 14.0, inside: false }, None).unwrap();
|
||||
// Centre 20 above the line, radius 6.
|
||||
assert!((solver::measure_dimension(&sk, &kind_at(&sk, k)).unwrap() - 14.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dimension_needs_a_line_and_a_circle_or_arc() {
|
||||
let mut sk = Sketch::new();
|
||||
let l = sk.add_line(v(0.0, 0.0), v(40.0, 0.0), None, None, None).unwrap();
|
||||
let m = sk.add_line(v(0.0, 10.0), v(40.0, 10.0), None, None, None).unwrap();
|
||||
let c = sk.add_circle(v(20.0, 20.0), 5.0, None, None).unwrap();
|
||||
for (l, c) in [(m, l), (c, c), (c, l)] {
|
||||
assert!(sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 1.0, inside: false }, None).is_err(), "{l} {c}");
|
||||
}
|
||||
for value in [-1.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value, inside: false }, None).is_err(), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dimension_survives_a_round_trip_and_a_renumbering() {
|
||||
let (mut sk, l, c, _) = line_and_circle(v(20.0, 3.0), 5.0);
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: true }, None).unwrap();
|
||||
let json = serde_json::to_value(&sk).unwrap();
|
||||
let saved = json["constraints"].as_array().unwrap().last().unwrap().clone();
|
||||
assert_eq!(saved["type"], "line_circle_distance", "{saved}");
|
||||
assert_eq!(saved["inside"], true, "{saved}");
|
||||
let back: Sketch = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back.constraints, sk.constraints);
|
||||
// `inside` is left out when false.
|
||||
let outside = ConstraintKind::LineCircleDistance { l, c, value: 2.0, inside: false };
|
||||
assert!(serde_json::to_value(&outside).unwrap().get("inside").is_none());
|
||||
let mut k = outside;
|
||||
assert!(k.remap(&|p| Some(p), &|i| Some(i + 10)));
|
||||
assert_eq!(k.indices(), (vec![], vec![l + 10, c + 10]));
|
||||
assert!(!k.remap(&|p| Some(p), &|_| None));
|
||||
}
|
||||
|
||||
/// With the centre's x set too, the seed places the centre exactly (its offset line from the
|
||||
/// dimension crossing the line of its x), before the numerical solver runs.
|
||||
#[test]
|
||||
fn the_seed_places_the_centre_by_construction() {
|
||||
for (drawn, inside, value, want) in [(v(20.0, 15.0), false, 7.0, v(20.0, 12.0)), (v(20.0, 3.0), true, 4.0, v(20.0, 1.0))] {
|
||||
let (mut sk, l, c, ci) = line_and_circle(drawn, 5.0);
|
||||
let (a, _) = sk.curves[l].kind.ends().unwrap();
|
||||
sk.add_constraint(ConstraintKind::DistanceX { p: a, q: ci, value: 20.0 }, None).unwrap();
|
||||
sk.add_constraint(ConstraintKind::LineCircleDistance { l, c, value, inside }, None).unwrap();
|
||||
let out = crate::tests::seed_of(&sk);
|
||||
assert!(out.placed_by[ci].is_some_and(crate::construct::Placement::anchors), "{out:?}");
|
||||
assert!(out.pos[ci].unwrap().dist(want) < 1e-9, "{out:?}");
|
||||
let rep = solve(&mut sk);
|
||||
assert!(rep.ok() && rep.dof == 0, "{rep:?}");
|
||||
assert!(sk.points[ci].pos.dist(want) < 1e-9, "{:?}", sk.points[ci].pos);
|
||||
}
|
||||
}
|
||||
@@ -887,6 +887,14 @@ pub(crate) fn read(sk: &Sketch, before: &dyn Fn(usize) -> Option<Vec2>, on_curve
|
||||
ties.push(Tie::Offset { p, l, len: Len::Value(d) });
|
||||
}
|
||||
}
|
||||
// The centre lies radius ± the gap from the line, on its side in the reference.
|
||||
LineCircleDistance { l, c, value, inside } if line(l).is_some() => {
|
||||
if let (Some(rd), Some(r)) = (round(c), r_of(c))
|
||||
&& let Some(d) = dim(if inside { r - value } else { r + value })
|
||||
{
|
||||
ties.push(Tie::Offset { p: rd.c, l, len: Len::Value(d) });
|
||||
}
|
||||
}
|
||||
Tangent { a, b } => {
|
||||
let (l, curve) = if line(a).is_some() { (a, b) } else { (b, a) };
|
||||
if line(l).is_some()
|
||||
|
||||
@@ -303,6 +303,17 @@ pub enum ConstraintKind {
|
||||
l: usize,
|
||||
value: f64,
|
||||
},
|
||||
/// Distance from line `l` to the edge of circle or arc `c`, along the line's normal: the
|
||||
/// gap `|distance from the centre to the line| − radius` while the line misses the circle,
|
||||
/// or, `inside`, how far the edge reaches past the line, `radius − |distance|`, while the
|
||||
/// line cuts it. Zero is tangency either way. An arc is measured to its whole circle.
|
||||
LineCircleDistance {
|
||||
l: usize,
|
||||
c: usize,
|
||||
value: f64,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
inside: bool,
|
||||
},
|
||||
Length {
|
||||
l: usize,
|
||||
value: f64,
|
||||
@@ -380,6 +391,7 @@ impl ConstraintKind {
|
||||
| DistanceX { value, .. }
|
||||
| DistanceY { value, .. }
|
||||
| PointLineDistance { value, .. }
|
||||
| LineCircleDistance { value, .. }
|
||||
| Length { value, .. }
|
||||
| LineAngle { value, .. }
|
||||
| ArcSweep { value, .. }
|
||||
@@ -400,6 +412,7 @@ impl ConstraintKind {
|
||||
| DistanceX { value, .. }
|
||||
| DistanceY { value, .. }
|
||||
| PointLineDistance { value, .. }
|
||||
| LineCircleDistance { value, .. }
|
||||
| Length { value, .. }
|
||||
| LineAngle { value, .. }
|
||||
| ArcSweep { value, .. }
|
||||
@@ -433,7 +446,9 @@ impl ConstraintKind {
|
||||
Midpoint { .. } => "MidPoint",
|
||||
Symmetric { .. } => "Symmetry",
|
||||
Fix { .. } => "Fix",
|
||||
Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | Length { .. } => "LinearDimension",
|
||||
Distance { .. } | DistanceX { .. } | DistanceY { .. } | PointLineDistance { .. } | LineCircleDistance { .. } | Length { .. } => {
|
||||
"LinearDimension"
|
||||
}
|
||||
Radius { .. } => "RadialDimension",
|
||||
Diameter { .. } => "DiameterDimension",
|
||||
Angle { .. } | LineAngle { .. } | ArcSweep { .. } => "AngularDimension",
|
||||
@@ -466,6 +481,7 @@ impl ConstraintKind {
|
||||
}
|
||||
Angle { a, b, .. } | SlotOverallLength { a, b, .. } => (vec![], vec![a, b]),
|
||||
Midpoint { p, l } | PointLineDistance { p, l, .. } => (vec![p], vec![l]),
|
||||
LineCircleDistance { l, c, .. } => (vec![], vec![l, c]),
|
||||
Symmetric { p, q, l } => (vec![p, q], vec![l]),
|
||||
Fix { p } => (vec![p], vec![]),
|
||||
Smooth { a, b } => (vec![], vec![a, b]),
|
||||
@@ -529,6 +545,10 @@ impl ConstraintKind {
|
||||
fp(p);
|
||||
fc(l);
|
||||
}
|
||||
LineCircleDistance { l, c, .. } => {
|
||||
fc(l);
|
||||
fc(c);
|
||||
}
|
||||
Symmetric { p, q, l } => {
|
||||
fp(p);
|
||||
fp(q);
|
||||
@@ -969,6 +989,10 @@ impl Sketch {
|
||||
return Err(SketchError::Invalid("overall slot length must exceed its width".into()));
|
||||
}
|
||||
}
|
||||
LineCircleDistance { l, c, .. } => {
|
||||
need_line(l)?;
|
||||
need_round(c)?;
|
||||
}
|
||||
Tangent { a, b } => {
|
||||
let free = |i: usize| self.curves.get(i).is_some_and(|c| c.kind.is_freeform());
|
||||
if !(is_round(a) || is_round(b) || free(a) || free(b)) {
|
||||
|
||||
@@ -347,6 +347,14 @@ impl State<'_> {
|
||||
let sweep = ((self.p(b) - self.p(cp)).angle() - (self.p(a) - self.p(cp)).angle()).rem_euclid(std::f64::consts::TAU);
|
||||
if curve.reversed { -sweep } else { sweep }
|
||||
}
|
||||
/// What a line-to-circle distance measures: the gap from line `l` to the edge of circle or
|
||||
/// arc `c`, or (`inside`) how far the edge reaches past the line.
|
||||
fn line_circle_gap(&self, l: usize, c: usize, inside: bool) -> f64 {
|
||||
let (a, b) = self.line(l);
|
||||
let (cc, r) = self.round(c);
|
||||
let d = line_dist(cc, a, b).abs();
|
||||
if inside { r - d } else { d - r }
|
||||
}
|
||||
fn slot_length(&self, a: usize, b: usize) -> f64 {
|
||||
let (ca, ra) = self.round(a);
|
||||
let (cb, rb) = self.round(b);
|
||||
@@ -547,6 +555,7 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
|
||||
let (a, b) = s.line(l);
|
||||
out.push(line_dist(s.p(p), a, b).abs() - value);
|
||||
}
|
||||
LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value),
|
||||
Length { l, value } => {
|
||||
let (a, b) = s.line(l);
|
||||
out.push(a.dist(b) - value);
|
||||
@@ -609,6 +618,7 @@ fn measure(s: &State, k: &ConstraintKind) -> Option<f64> {
|
||||
let (a, b) = s.line(l);
|
||||
line_dist(s.p(p), a, b).abs()
|
||||
}
|
||||
LineCircleDistance { l, c, inside, .. } => s.line_circle_gap(l, c, inside),
|
||||
Length { l, .. } => {
|
||||
let (a, b) = s.line(l);
|
||||
a.dist(b)
|
||||
@@ -814,6 +824,7 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec<Ref> {
|
||||
| DistanceY { p, q, .. } => vec![P(p), P(q)],
|
||||
PointOnCurve { p, c } => vec![P(p), C(c)],
|
||||
Midpoint { p, l } | PointLineDistance { p, l, .. } | LinearDiameter { p, l, .. } => vec![P(p), L(l)],
|
||||
LineCircleDistance { l, c, .. } => vec![L(l), R(c)],
|
||||
Horizontal { l } | Vertical { l } | Length { l, .. } | LineAngle { l, .. } => vec![L(l)],
|
||||
// Another kind reads a constant value, whatever its points: as good as any.
|
||||
ArcSweep { c, .. } | Radius { c, .. } | Diameter { c, .. } | ArcLength { c, .. } => vec![C(c)],
|
||||
@@ -1579,7 +1590,8 @@ enum Orient {
|
||||
SideX(usize, usize, f64),
|
||||
/// The same along y (`DistanceY`).
|
||||
SideY(usize, usize, f64),
|
||||
/// Which side of line `l` the point `p` is on (`PointLineDistance`, `LinearDiameter`).
|
||||
/// Which side of line `l` the point `p` is on (`PointLineDistance`, `LinearDiameter`, a
|
||||
/// circle's centre for `LineCircleDistance`).
|
||||
OfLine(usize, usize, f64),
|
||||
}
|
||||
|
||||
@@ -1748,6 +1760,12 @@ fn orients(s: &State, sub: &[(Block, Vec<usize>)]) -> Vec<(Orient, Vec<usize>)>
|
||||
ConstraintKind::DistanceY { p, q, value } if free(p) || free(q) => out.push((Orient::SideY(p, q, value), vec![*ci])),
|
||||
ConstraintKind::PointLineDistance { p, l, value } => out.push((Orient::OfLine(p, l, value), vec![*ci])),
|
||||
ConstraintKind::LinearDiameter { p, l, value } => out.push((Orient::OfLine(p, l, value / 2.0), vec![*ci])),
|
||||
// The circle stays on its side of the line: the distance is unsigned.
|
||||
ConstraintKind::LineCircleDistance { l, c, value, .. } => {
|
||||
if let Some(CurveKind::Circle { c: centre, .. } | CurveKind::Arc { c: centre, .. }) = s.sk.curves.get(c).map(|x| &x.kind) {
|
||||
out.push((Orient::OfLine(*centre, l, value + s.round(c).1), vec![*ci]));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[
|
||||
{"call": "engine.execute", "params": {"command": "sketch.create", "params": {"plane": "XY"}}},
|
||||
{"call": "engine.execute", "params": {"command": "sketch.line", "params": {"points": [[0, 0], [40, 0]]}}},
|
||||
{"call": "engine.execute", "params": {"command": "sketch.constraint.fix", "params": {"entities": ["l1"]}}},
|
||||
{"call": "engine.execute", "params": {"command": "sketch.circle.center", "params": {"center": [20, 15], "radius": 5}}},
|
||||
{"call": "engine.execute", "params": {"command": "sketch.dimension", "params": {"entities": ["c1"], "type": "diameter", "value": 10, "text_at": [30, 22]}}},
|
||||
{"call": "ui.view", "params": {"view": "top"}},
|
||||
{"call": "ui.view", "params": {"view": "fit"}},
|
||||
{"start": "sketch.dimension"},
|
||||
{"click": {"sketch": [8, 0]}},
|
||||
{"click": {"sketch": [20, 10]}},
|
||||
{"text": "7"},
|
||||
{"key": "Enter"},
|
||||
{"key": "Escape"},
|
||||
{"expect": {"errors": 0}},
|
||||
{"expect": {"param": {"d2": 7}}},
|
||||
{"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 1], "value": 12}}},
|
||||
{"expect": {"query": {"command": "sketch.inspect", "path": ["curves", 1, "center_at", 0], "value": 20}}}
|
||||
]
|
||||
@@ -177,7 +177,8 @@ or vertical alignment from their current positions. Esc cancels a pending first
|
||||
The solver is SolidCraft's own (damped Gauss–Newton with degree-of-freedom analysis). Constraints:
|
||||
coincident, horizontal/vertical, parallel, perpendicular, tangent, equal, concentric, collinear,
|
||||
midpoint, symmetry, fix, curvature (G2) and polygon. **Sketch Dimension** (D) adds linear,
|
||||
aligned, horizontal, vertical, radius, diameter and angle dimensions. Each is a parameter
|
||||
aligned, horizontal, vertical, point-to-line, line-to-circle, radius, diameter and angle
|
||||
dimensions. Each is a parameter
|
||||
(`d1`, `d2`, …), so it can hold an expression.
|
||||
|
||||
Press D, click what you want to measure and type the value: as soon as the click settles the
|
||||
@@ -197,6 +198,13 @@ Between two points, or on a line, that don't line up with an axis, where you pla
|
||||
dimension picks what it measures: across from them, the distance between them; above or below
|
||||
them, the horizontal distance; beside them, the vertical distance.
|
||||
|
||||
A line and a circle or arc (click the line, then the circle's edge, or the other way round)
|
||||
measure from the line to the circle's edge, square to the line: the gap between them, 0 when
|
||||
the circle touches the line. When the line cuts through the circle, the dimension measures how
|
||||
far the edge reaches past the line instead. An arc is measured to the circle it lies on. For
|
||||
the distance to the centre, click the centre point instead of the edge. In scripts:
|
||||
`{"command": "sketch.dimension", "params": {"entities": ["l1", "c1"], "value": 5}}`.
|
||||
|
||||
A dimension the sketch can't take, because the geometry is already fixed by other constraints
|
||||
and dimensions, is added as a driven (reference) dimension instead: it is shown in
|
||||
parentheses, measures the sketch, and has no value to edit.
|
||||
|
||||
@@ -31,7 +31,7 @@ and help is welcome: see [CONTRIBUTING.md](../CONTRIBUTING.md).
|
||||
and the rank of its Jacobian gives the remaining degrees of freedom. Constraints: coincident,
|
||||
point on curve, horizontal/vertical, parallel, perpendicular, tangent, curvature (G2), equal,
|
||||
concentric, collinear, midpoint, symmetry, fix; linear, aligned, horizontal, vertical,
|
||||
point-to-line, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven
|
||||
point-to-line, line-to-circle, radius, diameter, angle, arc sweep, arc length and slot length dimensions driven
|
||||
by parameters. Over-constraining edits are rejected; fully constrained geometry turns black.
|
||||
Dragging solves the sketch every frame and rebuilds the model once, when the drag ends.
|
||||
Select a line or its two endpoints, type its dimension and press Enter to commit one undo
|
||||
|
||||
@@ -47,8 +47,11 @@ These are the shapes of the commands a part build needs, so an agent rarely has
|
||||
{"command":"sketch.dimension","params":{"entities":["origin","c1.center"],"type":"horizontal","value":"w/2 - wall - 6"}}
|
||||
{"command":"sketch.dimension","params":{"entities":["c1"],"type":"diameter","value":"6"}}
|
||||
{"command":"sketch.dimension","params":{"entities":["l1"],"value":"w"}}
|
||||
{"command":"sketch.dimension","params":{"entities":["l1","c1"],"value":"2"}}
|
||||
```
|
||||
|
||||
A line with a circle or arc measures from the line to its edge (0 is tangent); give the centre point (`c1.center`) for the distance to the centre.
|
||||
|
||||
Distances are unsigned. Draw the geometry on the correct side first, and the dimension keeps it there.
|
||||
|
||||
`sketch.draw.dimensioned` creates a shape and its dimensions in one undo step. The dimension roles depend on the creator:
|
||||
|
||||
Reference in New Issue
Block a user