fix: midpoint tool rejects two lines (#3836)

This commit is contained in:
Mauznemo
2026-10-21 20:36:29 +00:00
committed by GitHub
parent 17ece2edc0
commit 84ec512d7a
8 changed files with 359 additions and 28 deletions
+52 -12
View File
@@ -156,7 +156,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SKETCH", "CONSTRAINTS")
.icon("c_midpoint")
.enabled(in_sketch)
.params("point, line"),
.params("point, line | a, b in pick order: a point and a line (either way round), or two lines whose midpoints meet (the first stays, the second moves)"),
CommandSpec::new("sketch.constraint.concentric", "Concentric", c_concentric)
.at("SKETCH", "CONSTRAINTS")
.icon("c_concentric")
@@ -1637,6 +1637,15 @@ pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option<f64> {
sk.constraints.iter().position(|c| c.id == id).and_then(|ci| solidcraft_sketch::constraint_residual(sk, ci))
}
/// The point already tied to the middle of line `l`, including one created by drawing.
/// Coincident coordinates alone are not enough: the Midpoint relationship must exist.
fn existing_midpoint(sk: &Sketch, l: usize) -> Option<usize> {
sk.constraints.iter().find_map(|c| match c.kind {
ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p),
_ => None,
})
}
/// Temporary pick intent. Saved sketches use ordinary points and constraints only.
#[derive(Clone, Copy, PartialEq, Eq)]
enum AlignmentTarget {
@@ -1645,19 +1654,13 @@ enum AlignmentTarget {
}
impl AlignmentTarget {
fn materialize(self, sk: &mut Sketch) -> Result<usize> {
fn materialize(self, sk: &mut Sketch, cmd: &str) -> Result<usize> {
match self {
Self::Point(p) => Ok(p),
Self::Midpoint(l) => {
// Reuse an existing associative midpoint, including one created by drawing.
// Coincident coordinates alone are insufficient: its relationship must exist.
if let Some(p) = sk.constraints.iter().find_map(|c| match c.kind {
ConstraintKind::Midpoint { p, l: line } if line == l && !c.driven => Some(p),
_ => None,
}) {
if let Some(p) = existing_midpoint(sk, l) {
return Ok(p);
}
let cmd = "sketch.constraint.horizontal_vertical";
let (a, b) = line_pts(sk, l).ok_or_else(|| bad(cmd, "a midpoint reference needs a line"))?;
let p = sk.add_point((a + b) * 0.5, None)?;
add_c(sk, ConstraintKind::Midpoint { p, l })?;
@@ -1693,8 +1696,8 @@ fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result<Value> {
if a == b {
return Err(bad(cmd, "alignment needs two distinct point references"));
}
let a = a.materialize(sk)?;
let b = b.materialize(sk)?;
let a = a.materialize(sk, cmd)?;
let b = b.materialize(sk, cmd)?;
if a == b {
return Err(bad(cmd, "alignment needs two distinct points"));
}
@@ -1826,9 +1829,46 @@ fn c_collinear(s: &mut Session, p: &Value) -> Result<Value> {
fn c_midpoint(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.constraint.midpoint";
constrain(s, p, cmd, |sk| {
Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? })
if p.get("a").is_none() && p.get("b").is_none() {
return Ok(ConstraintKind::Midpoint { p: point_ref(sk, p.get("point"), cmd, "point")?, l: curve_ref(sk, p.get("line"), cmd, "line")? });
}
// `a` and `b` in pick order: a point and a line either way round, or two lines.
let entity = |k: &str| -> Result<Ent> {
let r = p.get(k).and_then(Value::as_str).ok_or_else(|| bad(cmd, format!("`{k}` must be a point or line id")))?;
match sk.resolve_point(r) {
Some(i) => Ok(Ent::Point(i)),
None => sk.curve_index(r).map(Ent::Curve).ok_or_else(|| bad(cmd, format!("unknown sketch point or curve `{r}`"))),
}
};
let is_line = |sk: &Sketch, c: usize| matches!(sk.curves.get(c).map(|c| &c.kind), Some(CurveKind::Line { .. }));
match (entity("a")?, entity("b")?) {
(Ent::Point(q), Ent::Curve(l)) | (Ent::Curve(l), Ent::Point(q)) if is_line(sk, l) => Ok(ConstraintKind::Midpoint { p: q, l }),
// Two lines: their midpoints meet. One point sits at the middle of both, reusing
// a midpoint either line already has, so nothing new is saved in the design.
(Ent::Curve(a), Ent::Curve(b)) if is_line(sk, a) && is_line(sk, b) => {
if a == b {
return Err(bad(cmd, "pick two different lines"));
}
let (q, l) = match (existing_midpoint(sk, a), existing_midpoint(sk, b)) {
(Some(q), _) => (q, b),
(None, Some(q)) => (q, a),
(None, None) => (AlignmentTarget::Midpoint(a).materialize(sk, cmd)?, b),
};
if existing_midpoint_of(sk, q, l) {
return Err(bad(cmd, "these lines already share their midpoint"));
}
Ok(ConstraintKind::Midpoint { p: q, l })
}
_ => Err(bad(cmd, "MidPoint needs a point and a line, or two lines")),
}
})
}
/// Point `q` is already tied to the middle of line `l`.
fn existing_midpoint_of(sk: &Sketch, q: usize, l: usize) -> bool {
sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { p, l: line } if p == q && line == l) && !c.driven)
}
/// The centre of a symmetry about a point (#1075): `point`, or `line` naming a point rather than
/// a curve or a sketch axis (the origin picked as the third entity).
fn symmetry_center(sk: &Sketch, p: &Value, cmd: &str) -> Result<Option<usize>> {
@@ -632,3 +632,106 @@ fn midpoint_alignment_remaps_after_unrelated_geometry_is_deleted() {
run(&mut s, "sketch.delete", json!({"entities":[result["created"]["points"][0]]}));
assert!(sketch(&s).constraints.is_empty());
}
fn line_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (Vec2, Vec2) {
let solidcraft_sketch::CurveKind::Line { a, b } = sk.curves[sk.curve_index(id).unwrap()].kind else { panic!("expected line") };
(sk.point(a).unwrap(), sk.point(b).unwrap())
}
#[test]
fn midpoint_of_two_lines_centres_the_second_on_the_first() {
use solidcraft_sketch::ConstraintKind;
for reverse in [false, true] {
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false}));
run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false}));
let (first, second) = if reverse { ("l2", "l1") } else { ("l1", "l2") };
let stays = line_ends(&sketch(&s), first);
let length = {
let (a, b) = line_ends(&sketch(&s), second);
a.dist(b)
};
let before = s.doc.to_json();
let undo = s.undo.len();
let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":first,"b":second}));
assert_eq!(result["created"]["points"].as_array().unwrap().len(), 1);
assert_eq!(result["created"]["constraints"].as_array().unwrap().len(), 2);
assert_eq!(s.undo.len(), undo + 1);
let sk = sketch(&s);
assert_eq!(line_ends(&sk, first), stays, "the first pick stays put");
let (a, b) = line_ends(&sk, second);
assert!((a.dist(b) - length).abs() < 1e-6, "the second keeps its length");
assert!(line_midpoint(&sk, first).dist(line_midpoint(&sk, second)) < 1e-6);
assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2);
// Saved as ordinary points and constraints: it reopens and keeps holding.
let after = s.doc.to_json();
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.doc.to_json(), after);
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&after).unwrap());
reopened.active_sketch = s.active_sketch;
run(&mut reopened, "sketch.move_point", json!({"point":"l1.end","to":[80,15]}));
let sk = sketch(&reopened);
assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6);
}
}
#[test]
fn midpoint_takes_a_point_and_a_line_in_either_pick_order() {
for (a, b) in [("p", "l1"), ("l1", "p")] {
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,0],[40,0]],"infer":false,"connect":false}));
run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"}));
run(&mut s, "sketch.constraint.midpoint", json!({"a":a,"b":b}));
let sk = sketch(&s);
let p = sk.point(sk.resolve_point("p").unwrap()).unwrap();
assert!(p.dist(line_midpoint(&sk, "l1")) < 1e-6, "{a} then {b}");
}
}
#[test]
fn midpoint_of_two_lines_reuses_an_existing_midpoint() {
use solidcraft_sketch::ConstraintKind;
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false}));
run(&mut s, "sketch.line", json!({"points":[[5,-10],[25,-10]],"infer":false,"connect":false}));
// l3 starts at the midpoint of l2: that point is reused, not duplicated.
run(&mut s, "sketch.line", json!({"points":["mid:l2",[15,-30]],"infer":false,"connect":false}));
let count = sketch(&s).points.len();
let result = run(&mut s, "sketch.constraint.midpoint", json!({"a":"l1","b":"l2"}));
assert!(result["created"]["points"].as_array().unwrap().is_empty());
let sk = sketch(&s);
assert_eq!(sk.points.len(), count);
assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2);
assert!(line_midpoint(&sk, "l1").dist(line_midpoint(&sk, "l2")) < 1e-6);
// Applying it again finds nothing to add.
let before = s.doc.to_json();
assert!(s.execute("sketch.constraint.midpoint", &json!({"a":"l2","b":"l1"})).is_err());
assert_eq!(s.doc.to_json(), before);
}
#[test]
fn midpoint_rejects_wrong_picks_without_changing_the_sketch() {
let mut s = new_sketch();
run(&mut s, "sketch.line", json!({"points":[[0,0],[60,0]],"infer":false,"connect":false}));
run(&mut s, "sketch.circle.center", json!({"center":[40,50],"radius":3}));
run(&mut s, "sketch.point", json!({"point":[7,9],"id":"p"}));
for params in [
json!({"a":"l1","b":"l1"}),
json!({"a":"l1","b":"c1"}),
json!({"a":"c1","b":"l1"}),
json!({"a":"p","b":"origin"}),
json!({"a":"p","b":"c1"}),
json!({"a":"l1","b":"missing"}),
json!({"a":"l1"}),
json!({"a":12,"b":"l1"}),
] {
let before = s.doc.to_json();
let undo = s.undo.len();
assert!(s.execute("sketch.constraint.midpoint", &params).is_err(), "{params}");
assert_eq!(s.doc.to_json(), before, "{params}");
assert_eq!(s.undo.len(), undo, "{params}");
}
}