Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Polygon: By side shows the Length and Sides boxes (#11271) (#11287)

thocsmithaae4282f1e56
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 463f3c1e1d..4de7bb9e7f 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -66,7 +66,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension")
.enabled(in_sketch)
- .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names) (optional with as_drawn or locate), as_drawn?: bool (also dimension every other role of the shape at its size as drawn; a radius or diameter given takes the place of the other, a circle otherwise takes its diameter, and a size the sketch already determines, such as the angle of a line inferred horizontal, is left out), locate?: bool (then place the shape from the sketch origin until nothing of it is left free: horizontal and vertical distances from the origin to its points, centres first, each kept only where it removes freedom, so a shape anchored to the origin or to placed geometry gets none; a point on an axis goes onto that axis instead of a 0 distance; the reply's located lists them); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),
+ .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names) (optional with as_drawn or locate), as_drawn?: bool (also dimension every other role of the shape at its size as drawn; a radius or diameter given takes the place of the other, as an edge polygon's side length does its radius, a circle otherwise takes its diameter, and a size the sketch already determines, such as the angle of a line inferred horizontal, is left out), locate?: bool (then place the shape from the sketch origin until nothing of it is left free: horizontal and vertical distances from the origin to its points, centres first, each kept only where it removes freedom, so a shape anchored to the origin or to placed geometry gets none; a point on an axis goes onto that axis instead of a 0 distance; the reply's located lists them); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),
CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", rect_two_point)
.at("SKETCH", "CREATE")
.icon("rect")
diff --git a/crates/engine/src/cmd/sketch_dimensioned.rs b/crates/engine/src/cmd/sketch_dimensioned.rs
index 1ecd6806cd..08c8403b02 100644
--- a/crates/engine/src/cmd/sketch_dimensioned.rs
+++ b/crates/engine/src/cmd/sketch_dimensioned.rs
@@ -35,13 +35,16 @@ pub fn dimension_roles(creator: &str) -> Option<&'static [&'static str]> {
"sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point" => &["length", "width"],
"sketch.slot.arc_center" => &["radius", "sweep", "width"],
"sketch.slot.arc_three_point" => &["width"],
- "sketch.polygon.inscribed" | "sketch.polygon.circumscribed" | "sketch.polygon.edge" => &["radius"],
+ "sketch.polygon.inscribed" | "sketch.polygon.circumscribed" => &["radius"],
+ // A polygon drawn by a side can be sized by that side instead (#11271).
+ "sketch.polygon.edge" => &["radius", "length"],
_ => return None,
})
}
-/// Roles that measure the same size two ways: a shape takes one of each pair.
-const ALTERNATIVES: &[[&str; 2]] = &[["radius", "diameter"]];
+/// Roles that measure the same size two ways: a shape takes one of each pair. Only the edge
+/// polygon has both a radius and a length.
+const ALTERNATIVES: &[[&str; 2]] = &[["radius", "diameter"], ["radius", "length"]];
/// The roles to place: the given ones, then (`as_drawn`) each other role of `roles` that is not
/// an alternative of one already placed. None stands for the size as drawn.
@@ -74,8 +77,8 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {
if dimensions.len() > roles.len() || dimensions.keys().any(|key| !roles.contains(&key.as_str())) {
return Err(bad(cmd, "unsupported dimension role for this creator"));
}
- if dimensions.contains_key("radius") && dimensions.contains_key("diameter") {
- return Err(bad(cmd, "choose radius or diameter, not both"));
+ if let Some([a, b]) = ALTERNATIVES.iter().find(|pair| pair.iter().all(|role| dimensions.contains_key(*role))) {
+ return Err(bad(cmd, format!("choose {a} or {b}, not both")));
}
let mut overall_length = None;
let mut slot_width = None;
@@ -163,6 +166,8 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {
let centre = out.get("centre_arc").filter(|v| v.is_string()).cloned().ok_or_else(|| bad(cmd, "slot centre arc missing"))?;
(vec![centre], role)
}
+ // The first side runs from `p0` to `p1`; the others are equal to it.
+ ("sketch.polygon.edge", "length") => (vec![curve(0)?], "length"),
(c, "radius") if c.starts_with("sketch.polygon.") => {
let support =
out.get("support_circle").filter(|v| v.is_string()).cloned().ok_or_else(|| bad(cmd, "polygon support circle missing"))?;
diff --git a/crates/engine/src/cmd/sketch_dimensioned_tests.rs b/crates/engine/src/cmd/sketch_dimensioned_tests.rs
index 93a7805e27..724047e805 100644
--- a/crates/engine/src/cmd/sketch_dimensioned_tests.rs
+++ b/crates/engine/src/cmd/sketch_dimensioned_tests.rs
@@ -153,6 +153,43 @@ fn slots_and_polygon_keep_permanent_typed_dimensions() {
assert_eq!(result["errors"], json!([]));
close(measure(&s, |k| matches!(k, ConstraintKind::Radius { .. })), 15.0);
}
+ // A polygon drawn by a side takes that side's length in place of its radius (#11271), and
+ // every side follows it.
+ let mut s = session();
+ let undo = s.undo.len();
+ let out = draw(&mut s, "sketch.polygon.edge", json!({"p0":[0,0],"p1":[10,0],"sides":5,"connect":false}), json!({"length":"12 mm"}));
+ assert_eq!(s.undo.len(), undo + 1);
+ let length = out["dimensions"]["length"]["param"].as_str().unwrap();
+ let result = run(&mut s, "parameters.change", json!({"name":length,"expression":20}));
+ assert_eq!(result["errors"], json!([]));
+ let sk = sketch(&s);
+ let sides: Vec<f64> = sk
+ .curves
+ .iter()
+ .filter(|c| !c.construction)
+ .filter_map(|c| match c.kind {
+ solidcraft_sketch::CurveKind::Line { a, b } => Some(sk.points[a].pos.dist(sk.points[b].pos)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(sides.len(), 5);
+ sides.iter().for_each(|l| close(*l, 20.0));
+ // As drawn, a typed length leaves out the radius; both given are refused.
+ let mut s = session();
+ let out = run(
+ &mut s,
+ "sketch.draw.dimensioned",
+ json!({"command":"sketch.polygon.edge","params":{"p0":[0,0],"p1":[10,0],"sides":5},"dimensions":{"length":10},"as_drawn":true}),
+ );
+ assert!(out["dimensions"].get("radius").is_none(), "{out}");
+ let error = s
+ .execute(
+ "sketch.draw.dimensioned",
+ &json!({"command":"sketch.polygon.edge","params":{"p0":[0,0],"p1":[10,0]},"dimensions":{"length":10,"radius":9}}),
+ )
+ .expect_err("both sizes")
+ .to_string();
+ assert!(error.contains("choose radius or length, not both"), "{error}");
}
#[test]
diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs
index c601321f37..859bcbc9ea 100644
--- a/crates/ui-egui/src/sketch_dims.rs
+++ b/crates/ui-egui/src/sketch_dims.rs
@@ -64,6 +64,8 @@ pub fn boxes_for(cmd: &str, n: usize) -> Vec<DimBox> {
("sketch.arc.center_point" | "sketch.slot.arc_center", 1) => vec![b("Radius", Length)],
("sketch.arc.center_point" | "sketch.slot.arc_center", 2) => vec![b("Sweep", Angle)],
("sketch.polygon.inscribed" | "sketch.polygon.circumscribed", 1) => vec![b("Radius", Length), b("Sides", Unitless)],
+ // By side: the side from the first click to the second (#11271).
+ ("sketch.polygon.edge", 1) => vec![b("Length", Length), b("Sides", Unitless)],
("sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point", 1) => vec![b("Length", Length)],
("sketch.conic", 2) => vec![b("Rho", Unitless)],
("sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point", 2)
@@ -148,6 +150,7 @@ pub fn effective(app: &SolveApp, t: &Tool, h: Vec2) -> Vec2 {
c + Vec2::from_angle(a0 + sweep) * r
}
("sketch.polygon.inscribed" | "sketch.polygon.circumscribed", 1) => a + dir_or_x(h - a) * lk("Radius").unwrap_or((h - a).len()),
+ ("sketch.polygon.edge", 1) => a + dir_or_x(h - a) * lk("Length").unwrap_or((h - a).len()),
("sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point", 2) => match lk("Width") {
Some(w) => {
let c0 = t.pts.first().map(|p| p.0).unwrap_or(a);
@@ -338,7 +341,8 @@ fn live(app: &SolveApp, t: &Tool, e: Vec2, px: f64) -> Vec<(f64, Vec2)> {
("sketch.circle.two_tangent", 2) => {
vec![(crate::sketch_tools::two_tangent_default_radius(app, t), (first + a) * 0.5 + dir_or_x(a - first).perp() * off)]
}
- ("sketch.arc.center_point" | "sketch.slot.arc_center", 1) | ("sketch.polygon.inscribed" | "sketch.polygon.circumscribed", 1) => {
+ ("sketch.arc.center_point" | "sketch.slot.arc_center", 1)
+ | ("sketch.polygon.inscribed" | "sketch.polygon.circumscribed" | "sketch.polygon.edge", 1) => {
vec![((e - a).len(), (a + e) * 0.5), (6.0, a + (e - a) * 0.5 + (e - a).perp() * 0.3)]
}
("sketch.arc.center_point" | "sketch.slot.arc_center", 2) => {
@@ -614,7 +618,7 @@ fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option
// Polygon values used to sit inside the radius, so both boxes covered a small polygon
// and each other. Place them together outside its projected outline, in screen space:
// their separation must not shrink with the shape or a tilted sketch plane.
- let polygon_positions = if matches!(t.cmd, "sketch.polygon.inscribed" | "sketch.polygon.circumscribed") {
+ let polygon_positions = if matches!(t.cmd, "sketch.polygon.inscribed" | "sketch.polygon.circumscribed" | "sketch.polygon.edge") {
let corners = crate::tools::polygon_outline(t, e, locked(app, t, "Sides").unwrap_or(6.0))
.unwrap_or_else(|| t.pts.iter().map(|p| p.0).chain(std::iter::once(e)).collect());
let points: Vec<_> = corners.iter().filter_map(|p| proj.to_screen(plane.to_world(*p))).collect();
diff --git a/crates/ui-egui/src/sketch_typed_intent_tests.rs b/crates/ui-egui/src/sketch_typed_intent_tests.rs
index f4f4de8eb3..93a2256e53 100644
--- a/crates/ui-egui/src/sketch_typed_intent_tests.rs
+++ b/crates/ui-egui/src/sketch_typed_intent_tests.rs
@@ -197,6 +197,40 @@ fn polygon_radius_is_persistent_and_fractional_sides_are_rejected() {
assert_eq!(sketch.curves.iter().filter(|c| !c.construction).count(), 5);
}
+/// "By side" offers the side length and the number of sides, as the other polygon modes do
+/// (#11271): the typed length becomes a dimension of the first side.
+#[test]
+fn edge_polygon_takes_a_typed_side_length_and_side_count() {
+ let mut h = start("sketch.polygon.edge");
+ let labels: Vec<_> = h.app.tool.as_ref().unwrap().dims.iter().map(|d| d.label).collect();
+ assert_eq!(labels, ["Length", "Sides"]);
+ type_value(&mut h, "12");
+ h.step(&json!({"key":"Tab"})).unwrap();
+ type_value(&mut h, "5");
+ let undo = h.app.session.undo.len();
+ enter(&mut h);
+ assert_eq!(h.app.session.undo.len(), undo + 1);
+ assert!(constraints(&h).iter().any(|c| matches!(c, ConstraintKind::Length { value, .. } if (*value - 12.0).abs() < 1e-7)));
+ // The design's own state: this sketch is in no component, so it matches the world view.
+ let state = h.app.session.model.state();
+ let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
+ let sides: Vec<f64> = sketch
+ .curves
+ .iter()
+ .filter(|c| !c.construction)
+ .filter_map(|c| match c.kind {
+ CurveKind::Line { a, b } => Some(sketch.points[a].pos.dist(sketch.points[b].pos)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(sides.len(), 5);
+ assert!(sides.iter().all(|l| (l - 12.0).abs() < 1e-6), "{sides:?}");
+ // The first side runs from the first click towards the cursor.
+ let CurveKind::Line { a, b } = sketch.curves[0].kind else { panic!("expected the first side") };
+ assert!(sketch.points[a].pos.dist(solidcore_record::Vec2::new(0.0, 0.0)) < 1e-6);
+ assert!(sketch.points[b].pos.dist(solidcore_record::Vec2::new(12.0, 0.0)) < 1e-6);
+}
+
#[test]
fn line_angle_survives_drag_and_one_undo_removes_geometry_and_dimensions() {
let mut h = start("sketch.line");
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index 3ec9983334..7f697be06e 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -166,7 +166,9 @@ zero-based index. For example:
Polygon tools show their edge outline while positioning the second point, so the orientation
can be checked before placement. Inscribed and circumscribed polygons retain their support
-circle and update the outline when the inline **Sides** value changes.
+circle and update the outline when the inline **Sides** value changes. A polygon drawn **By side**
+has a **Length** box for the side from the first click and the same **Sides** box; a typed length
+becomes a dimension of that side, and the other sides stay equal to it.
**Text** is set in the built-in font (Liberation Sans) unless it is given another: `sketch.text` and
`sketch.edit_text` take a `font`, the family or full name of an installed font ("DejaVu Sans") or the path