Allow sketch Mirror to use origin axes (#4193) (#4207)

* claim: #4193

* Sketch Mirror: an origin axis can be the mirror line (#4193)

Mirror accepted only a straight curve of the sketch. It now also takes an
origin axis that lies in the sketch plane ({axis: X|Y|Z}), projected into
the sketch as a fixed linked line, so the copies stay symmetric to it and
follow the source when it moves.

* Sketch Mirror: use current sketch store (#4193)
This commit is contained in:
raykholo
2026-10-29 05:08:00 +00:00
committed by GitHub
parent fed7ea0c88
commit afe7dcd4e1
6 changed files with 159 additions and 12 deletions
+18 -5
View File
@@ -8,7 +8,7 @@ use solidcraft_doc::ProfileSel;
use solidcraft_geom::Vec2;
use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, intersections, intersections_within};
use super::sketch::{add_c, edit, ids_of, solve_current};
use super::sketch::{add_c, edit, ids_of, line_or_axis_ref, solve_current};
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec2_list};
@@ -97,7 +97,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SKETCH", "PATTERN")
.icon("sketch_mirror")
.enabled(in_sketch)
.params(concat!("entities: [curve/point ids], line: mirror line id (symmetry constraints are added)", created_doc!())),
.params(concat!("entities: [curve/point ids], line: straight curve id, x / y for a sketch axis, or {axis: X|Y|Z} for an origin axis in the sketch plane (symmetry constraints are added)", created_doc!())),
CommandSpec::new("sketch.pattern.circular", "Circular Pattern", pattern_circular)
.at("SKETCH", "PATTERN")
.icon("sketch_circ_pattern")
@@ -2630,11 +2630,24 @@ fn copy_through(
fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.mirror";
let origin_axis =
p.get("line").filter(|line| line.is_object()).map(|line| super::sketch_project::origin_axis_line(s, p, line, cmd)).transpose()?;
let (out, info) = edit(s, p, cmd, false, |sk, _| {
let (cs, ps) = entities(sk, p, cmd)?;
let lid = str_(p, "line").ok_or_else(|| bad(cmd, "`line` must be the mirror line"))?;
let l = sk.curve_index(lid).ok_or_else(|| bad(cmd, format!("unknown curve `{lid}`")))?;
let Some(Shape::Line { a, b }) = sk.shape(l) else { return Err(bad(cmd, "the mirror must be a line")) };
let l = if let Some((source, geom)) = origin_axis {
let link =
sk.links.iter().find(|link| link.kind == solidcraft_sketch::LinkKind::Project && link.source == source).map(|link| link.id.clone());
let link = match link {
Some(link) => link,
None => sk.add_link(solidcraft_sketch::LinkKind::Project, source, &geom)?,
};
sk.link_curves(&link).first().copied().ok_or_else(|| bad(cmd, "the origin axis does not resolve to a straight line"))?
} else {
line_or_axis_ref(sk, p.get("line"), cmd, "line")?
};
let Some(Shape::Line { a, b }) = sk.shape(l) else {
return Err(bad(cmd, "the mirror must be a straight curve of this sketch or an origin axis in its plane"));
};
let u = (b - a).normalized().ok_or_else(|| bad(cmd, "degenerate mirror line"))?;
let refl = move |q: Vec2| {
let foot = a + u * (q - a).dot(u);
@@ -3184,3 +3184,57 @@ fn extend_two_collinear_lines_are_refused_as_collinear() {
let e = s.execute("sketch.extend", &json!({"curves": [a, c]})).unwrap_err().to_string();
assert!(e.contains("collinear"), "{e}");
}
#[test]
fn mirror_origin_axes_keep_symmetry_and_fully_constrained_sources_driving_copies() {
for axis in ["x", "y"] {
let mut s = new_sketch();
run(&mut s, "parameters.add", json!({"name":"width","expression":"10 mm"}));
run(&mut s, "sketch.line", json!({"points":[["width","3 mm"],["width + 5 mm","8 mm"]],"ids":["source"]}));
let before = run(&mut s, "sketch.inspect", json!({}))["dof"].clone();
assert_eq!(before, 0);
let out = run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":axis}));
assert_eq!(out["sketch"]["dof"], before);
let copy = out["curves"][0].as_str().unwrap();
for width in [10, 20] {
if width == 20 {
run(&mut s, "parameters.change", json!({"name":"width","expression":"20 mm"}));
}
let sk = sketch(&s);
let l = sk.sketch_axis_curve(axis).unwrap();
assert!(sk.is_linked_curve(l) && sk.curves[l].construction);
assert_eq!(sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Symmetric { l: line, .. } if line == l)).count(), 2);
for (source_end, copy_end, x, y) in [("start", "end", width, 3), ("end", "start", width + 5, 8)] {
let source = sk.point(sk.resolve_point(&format!("source.{source_end}")).unwrap()).unwrap();
assert!(source.dist(Vec2::new(x as f64, y as f64)) < 1e-6);
let expected = if axis == "y" { Vec2::new(-source.x, source.y) } else { Vec2::new(source.x, -source.y) };
let actual = sk.point(sk.resolve_point(&format!("{copy}.{copy_end}")).unwrap()).unwrap();
assert!(actual.dist(expected) < 1e-6, "{axis}: {actual:?} != {expected:?}");
}
assert_eq!(run(&mut s, "sketch.inspect", json!({}))["dof"], before);
}
}
}
#[test]
fn mirror_origin_axis_in_rotated_plane_reuses_projection_and_rejects_invalid_lines() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane":{"origin":[0,5,0],"x_dir":[1,1,0],"y_dir":[-1,1,0]}}));
run(&mut s, "sketch.line", json!({"points":[[10,3],[15,8]],"ids":["source"]}));
let out = run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":{"axis":"Y"}}));
let sk = sketch(&s);
let copy = out["curves"][0].as_str().unwrap();
for (source_end, copy_end) in [("start", "end"), ("end", "start")] {
let source = sk.point(sk.resolve_point(&format!("source.{source_end}")).unwrap()).unwrap();
let copy = sk.point(sk.resolve_point(&format!("{copy}.{copy_end}")).unwrap()).unwrap();
assert!(copy.dist(Vec2::new(source.y, source.x)) < 1e-6, "{source:?}: {copy:?}");
}
run(&mut s, "sketch.mirror", json!({"entities":["source"],"line":{"axis":"Y"}}));
assert_eq!(sketch(&s).links.len(), 1);
run(&mut s, "sketch.circle.center", json!({"center":[20,10],"radius":2,"id":"circle"}));
let before = s.doc.to_json();
for line in [json!({"axis":"Z"}), json!({"axis":"bad"}), json!({"plane":"XY"}), json!("circle"), json!("missing")] {
assert!(s.execute("sketch.mirror", &json!({"entities":["source"],"line":line})).is_err(), "{line}");
assert_eq!(s.doc.to_json(), before);
}
}
+23
View File
@@ -231,6 +231,29 @@ pub(super) mod refresh_count {
}
}
/// Resolve an origin axis as a mirror line, keeping its projection linked and fixed.
pub(super) fn origin_axis_line(s: &Session, p: &Value, line: &Value, cmd: &str) -> Result<(LinkSource, Vec<solidcraft_sketch::LinkGeom>)> {
let id = sketch_store::target(s, p, cmd)?;
let doc = placed_candidate(s, &s.doc);
let st = s.model.state_before(id);
let st = state_for_sketch(s, &doc, id, &st)?;
let plane = sketch_plane(&doc, id, &st)?;
let src = source(s, line, cmd)?;
let LinkSource::Axis { name } = &src else { return Err(bad(cmd, "the mirror line must be a straight sketch curve or an origin axis")) };
let dir = match name.as_str() {
"X" => Vec3::X,
"Y" => Vec3::Y,
"Z" => Vec3::Z,
_ => return Err(bad(cmd, "the origin axis must be X, Y or Z")),
};
if plane.normal().dot(dir).abs() > 1e-9 || plane.normal().dot(plane.origin).abs() > 1e-6 {
return Err(bad(cmd, "the origin axis must lie in the sketch plane"));
}
let (vals, _) = doc.param_values();
let r = resolve(&doc, &vals, &st, &plane, LinkKind::Project, &src)?;
Ok((r.source, r.geom))
}
/// Add a link for `src` to sketch `id` in `doc` (not stored in the session). Returns the link id.
pub(super) fn add_link(s: &Session, doc: &Document, id: u64, sk: &mut Sketch, kind: LinkKind, src: LinkSource) -> Result<String> {
add_link_unless_present(s, doc, id, sk, kind, src, false).map(|l| l.unwrap_or_default())