Skip to content

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

Coil: a section from a sketch profile (#4236) (#4239)

TheMiddleCompanyae0b1edeac99
diff --git a/crates/doc/src/coil_tests.rs b/crates/doc/src/coil_tests.rs
new file mode 100644
index 0000000000..bbcaa09772
--- /dev/null
+++ b/crates/doc/src/coil_tests.rs
@@ -0,0 +1,56 @@
+use serde_json::{Value, json};
+
+use crate::FeatureKind;
+
+fn kind(v: Value) -> FeatureKind {
+ serde_json::from_value(v).unwrap()
+}
+
+#[test]
+fn an_old_coil_saves_unchanged() {
+ let old = json!({
+ "type": "coil",
+ "base": [0.0, 0.0, 0.0],
+ "axis": [0.0, 0.0, 1.0],
+ "diameter": "40",
+ "pitch": "8",
+ "turns": "4",
+ "section_size": "3",
+ "section": "circular",
+ "operation": "new_body"
+ });
+ assert_eq!(serde_json::to_value(kind(old.clone())).unwrap(), old);
+}
+
+#[test]
+fn a_coil_from_a_sketch_saves_its_sketch_and_profiles() {
+ let v = json!({
+ "type": "coil",
+ "base": [0.0, 0.0, 0.0],
+ "axis": [0.0, 0.0, 1.0],
+ "sketch": 7,
+ "profiles": {"type": "indices", "indices": [0]},
+ "pitch": "8",
+ "turns": "4",
+ "section": "circular",
+ "operation": "new_body"
+ });
+ assert_eq!(serde_json::to_value(kind(v.clone())).unwrap(), v);
+}
+
+#[test]
+fn all_profiles_are_omitted() {
+ let v = json!({
+ "type": "coil",
+ "base": [0.0, 0.0, 0.0],
+ "axis": [0.0, 0.0, 1.0],
+ "sketch": 7,
+ "pitch": "8",
+ "turns": "4",
+ "section": "circular",
+ "operation": "new_body"
+ });
+ let saved = serde_json::to_value(kind(v.clone())).unwrap();
+ assert_eq!(saved, v);
+ assert!(saved.get("profiles").is_none());
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index c9cf07cb04..d118cc9de6 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -1005,14 +1005,23 @@ pub enum FeatureKind {
base: PointExpr,
#[serde(default = "z_axis")]
axis: Dir,
+ /// The sketch whose plane and profile the coil sweeps. Its absence means the primitive
+ /// circular or square section below.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ sketch: Option<SketchId>,
+ #[serde(default = "all_profiles", skip_serializing_if = "profiles_are_all")]
+ #[walk(profiles_of = sketch)]
+ profiles: ProfileSel,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(length = "Diameter")]
- diameter: Expr,
+ diameter: Option<Expr>,
#[walk(length = "Pitch")]
pitch: Expr,
#[walk(unitless = "Revolutions")]
turns: Expr,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(length = "Section size")]
- section_size: Expr,
+ section_size: Option<Expr>,
#[serde(default)]
section: CoilSection,
/// -1 inside, 0 on the centre, 1 outside of the diameter.
@@ -2412,6 +2421,10 @@ pub(crate) fn all_profiles() -> ProfileSel {
ProfileSel::All
}
+fn profiles_are_all(p: &ProfileSel) -> bool {
+ matches!(p, ProfileSel::All)
+}
+
fn yes() -> bool {
true
}
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 3da658d836..dd6aef2d26 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -4898,15 +4898,44 @@ fn feature_tools_with_constructor(
// Its sides are named by the profile's curves, its base `start`.
Ok(vec![crate::lineage::ProfileRoles::swept(Some(ss), Some(r)).tool(body, None)])
}
- FeatureKind::Coil { base, axis, diameter, pitch, turns, section_size, section, position, start_angle, clockwise, .. } => {
+ FeatureKind::Coil {
+ base, axis, diameter, pitch, turns, section_size, section, position, start_angle, clockwise, sketch, profiles, ..
+ } => {
let base = &point(vals, base)?;
let k = axis.normalized().ok_or_else(|| DocError::Invalid("coil axis".into()))?;
- let (d, p, n, s) = (
- val(vals, diameter, Kind::Length)?,
- val(vals, pitch, Kind::Length)?,
- val(vals, turns, Kind::Unitless)?,
- val(vals, section_size, Kind::Length)?,
- );
+ let p = val(vals, pitch, Kind::Length)?;
+ let n = val(vals, turns, Kind::Unitless)?;
+ if sketch.is_some()
+ && (diameter.is_some()
+ || section_size.is_some()
+ || start_angle.is_some()
+ || !matches!(section, crate::CoilSection::Circular)
+ || *position != 0)
+ {
+ return Err(DocError::Invalid(
+ "a coil with a `sketch` cannot also set `diameter`, `section_size`, `section`, `section_position` or `start_angle`".into(),
+ ));
+ }
+ if sketch.is_none() && !matches!(profiles, ProfileSel::All) {
+ return Err(DocError::Invalid("a coil's `profiles` need a `sketch`".into()));
+ }
+ if let Some(sk) = sketch {
+ let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk} (it must come earlier in the timeline)")))?;
+ let regions = select_profiles(ss, profiles)?;
+ if regions.iter().any(|r| !r.holes.is_empty()) {
+ return Err(DocError::Invalid("a coil from a sketch takes a profile without holes".into()));
+ }
+ let [region] = &regions[..] else {
+ return Err(DocError::Invalid(format!("a coil from a sketch takes one closed profile (the sketch has {})", regions.len())));
+ };
+ let axis = if *clockwise { k * -1.0 } else { k };
+ // A left-handed coil turns about −axis and climbs along +axis: mirror the pitch.
+ let pitch = if *clockwise { -p } else { p };
+ return Ok(unnamed(vec![kernel::sweep_helix(&ss.plane, region, *base, axis, pitch, n)?]));
+ }
+ let diameter = diameter.as_ref().ok_or_else(|| DocError::Invalid("a coil needs a `sketch` or a `diameter`".into()))?;
+ let section_size = section_size.as_ref().ok_or_else(|| DocError::Invalid("a coil needs a `sketch` or a `section_size`".into()))?;
+ let (d, s) = (val(vals, diameter, Kind::Length)?, val(vals, section_size, Kind::Length)?);
if !(d > 0.0 && s > 0.0 && n > 0.0) {
return Err(DocError::Invalid("the coil diameter, section size and revolutions must be positive".into()));
}
diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs
index 651576f648..db345f0724 100644
--- a/crates/doc/src/feature_walk_tests/fixtures.rs
+++ b/crates/doc/src/feature_walk_tests/fixtures.rs
@@ -126,6 +126,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
"coil",
json!({"type": "coil", "base": ["coil.x", "coil.y", "coil.z"], "diameter": "coil.diameter", "pitch": "coil.pitch", "turns": "coil.turns", "section_size": "coil.section_size", "start_angle": "coil.start_angle"}),
),
+ (
+ "coil_profile",
+ json!({"type": "coil", "base": ["coil_profile.x", "coil_profile.y", "coil_profile.z"], "sketch": 1, "profiles": {"type": "indices", "indices": [0]}, "pitch": "coil_profile.pitch", "turns": "coil_profile.turns"}),
+ ),
("sheet_base", json!({"type": "sheet_base", "sketch": 1, "profiles": {"type": "all"}})),
("sheet_contour", json!({"type": "sheet_contour", "sketch": 1, "curves": ["l1"], "distance": "contour.distance"})),
(
diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt
index ff4ba3a820..3125006073 100644
--- a/crates/doc/src/feature_walk_tests/golden_exprs.txt
+++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt
@@ -250,6 +250,11 @@ coil
Section size = coil.section_size (Length)
Start angle = coil.start_angle (Angle)
expressions: coil.diameter, coil.pitch, coil.turns, coil.section_size, coil.start_angle, coil.x, coil.y, coil.z
+coil_profile
+ inputs:
+ Pitch = coil_profile.pitch (Length)
+ Revolutions = coil_profile.turns (Unitless)
+ expressions: coil_profile.pitch, coil_profile.turns, coil_profile.x, coil_profile.y, coil_profile.z
sheet_base
sheet_contour
inputs:
diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt
index f33a46bfa0..2ea3bd5baf 100644
--- a/crates/doc/src/feature_walk_tests/golden_geometry.txt
+++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt
@@ -115,6 +115,10 @@ align
coil
moves: axis[0], axis[2], base[0], base[1], base[2]
placement: coil.x, coil.y, coil.z
+coil_profile
+ moves: axis[0], axis[2], base[0], base[1], base[2]
+ profiles: 1 indices
+ placement: coil_profile.x, coil_profile.y, coil_profile.z
sheet_base
profiles: 1 all
sheet_contour
diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt
index 8f30912bf3..8ab16cde78 100644
--- a/crates/doc/src/feature_walk_tests/golden_refs.txt
+++ b/crates/doc/src/feature_walk_tests/golden_refs.txt
@@ -127,6 +127,9 @@ align
remap_bodies: bodies[0]
coil
remap_bodies: targets[0]
+coil_profile
+ sketches: [1]
+ remap_refs: sketch
sheet_base
sketches: [1]
remap_refs: sketch
diff --git a/crates/doc/src/format/pending/coil-profile-from-sketch.rs b/crates/doc/src/format/pending/coil-profile-from-sketch.rs
new file mode 100644
index 0000000000..b0e17ff317
--- /dev/null
+++ b/crates/doc/src/format/pending/coil-profile-from-sketch.rs
@@ -0,0 +1,4 @@
+//! A coil's section can come from a sketch (`sketch`, `profiles?`): the sketch plane is the
+//! section plane, and `diameter`/`section_size` are then absent. Older designs need no
+//! transformation: a coil without `sketch` is the primitive circular or square section exactly
+//! as before. The last release refuses a design saved with this (the newer format number).
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 555616ee66..ce41722f7a 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -100,6 +100,8 @@ pub enum DocError {
pub type Result<T> = std::result::Result<T, DocError>;
+#[cfg(test)]
+mod coil_tests;
#[cfg(test)]
mod feature_walk_tests;
#[cfg(test)]
diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs
index a35b229d0d..ea57309b2c 100644
--- a/crates/engine/src/cmd/features_more.rs
+++ b/crates/engine/src/cmd/features_more.rs
@@ -20,7 +20,9 @@ pub static COMMANDS: &[CommandSpec] = &[
),
CommandSpec::new("solid.coil", "Coil", coil).at("SOLID", "CREATE").icon("coil").params(
"diameter; two of revolutions (or turns), height, pitch; section_size; section?: circular|square; section_position?: inside|center|outside; \
- base?: [x,y,z] (numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); start_angle?; clockwise?: bool; operation?, targets?, name?, body_name?",
+ base?: [x,y,z] (numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); start_angle?; clockwise?: bool; \
+ sketch? (a sketch; its plane is the section plane, so its placement sets the radius and start phase), profiles? (default: all; one closed profile without holes); \
+ operation?, targets?, name?, body_name?",
),
CommandSpec::new("solid.rib", "Rib", rib)
.at("SOLID", "CREATE")
@@ -47,10 +49,26 @@ pub static COMMANDS: &[CommandSpec] = &[
fn coil(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.coil";
+ let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
+ let profile_mode = given("sketch");
+ if profile_mode {
+ if let Some(k) = ["diameter", "section_size", "section", "section_position", "start_angle"].into_iter().find(|k| given(k)) {
+ return Err(bad(cmd, format!("`{k}` does not apply with `sketch`: the section comes from the sketch")));
+ }
+ } else if given("profiles") {
+ return Err(bad(cmd, "`profiles` needs `sketch`"));
+ }
+ let sketch = if profile_mode { Some(solidcraft_doc::SketchId(super::features::sketch_id(s, p.get("sketch"), cmd, "sketch")?)) } else { None };
+ let profiles = if profile_mode { super::features::profiles(p, cmd)? } else { solidcraft_doc::ProfileSel::All };
let base = point_param(s, p, "base", cmd)?.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO));
let axis = axis_dir_param(p, cmd)?;
- let diameter = req_expr(cmd, p, "diameter")?;
- check_expr(s, &diameter, Kind::Length, cmd, "diameter")?;
+ let diameter = if profile_mode {
+ None
+ } else {
+ let d = req_expr(cmd, p, "diameter")?;
+ check_expr(s, &d, Kind::Length, cmd, "diameter")?;
+ Some(d)
+ };
let turns = expr(p, "revolutions").or_else(|| expr(p, "turns"));
let (height, pitch) = (expr(p, "height"), expr(p, "pitch"));
// The pitch or the revolutions from the height keep the units the lengths were given in.
@@ -69,8 +87,13 @@ fn coil(s: &mut Session, p: &Value) -> Result<Value> {
};
check_expr(s, &turns, Kind::Unitless, cmd, "revolutions")?;
check_expr(s, &pitch, Kind::Length, cmd, "pitch")?;
- let section_size = req_expr(cmd, p, "section_size")?;
- check_expr(s, &section_size, Kind::Length, cmd, "section_size")?;
+ let section_size = if profile_mode {
+ None
+ } else {
+ let size = req_expr(cmd, p, "section_size")?;
+ check_expr(s, &size, Kind::Length, cmd, "section_size")?;
+ Some(size)
+ };
let section = match str_(p, "section").map(str::to_ascii_lowercase).as_deref() {
None | Some("circular" | "circle") => solidcraft_doc::CoilSection::Circular,
Some("square") => solidcraft_doc::CoilSection::Square,
@@ -94,6 +117,8 @@ fn coil(s: &mut Session, p: &Value) -> Result<Value> {
FeatureKind::Coil {
base,
axis: Dir(axis),
+ sketch,
+ profiles,
diameter,
pitch,
turns,
diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs
index 7060a6a440..5620ff88e6 100644
--- a/crates/engine/src/cmd/features_more_tests.rs
+++ b/crates/engine/src/cmd/features_more_tests.rs
@@ -1777,3 +1777,179 @@ fn duplicate_and_excess_profile_picks_are_refused_quickly() {
// One pick of the profile still builds.
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom", "profiles": [0]}, {"sketch": "Top"}]}));
}
+
+#[test]
+fn coil_from_a_sketch_profile_sweeps_its_plane() {
+ use std::f64::consts::PI;
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ // A 1 x 1 mm square, 10..11 mm from the Z axis, on a plane through the axis.
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.coil", json!({"sketch": "Section", "revolutions": 3, "pitch": 8}));
+ // Pappus for a screw sweep: V = 2 pi n A r_centroid.
+ assert!(rel(volume(&mut s), 2.0 * PI * 3.0 * 1.0 * 10.5) < 1e-3, "{}", volume(&mut s));
+ let m = measure(&mut s);
+ let b = &m["bodies"][0]["bbox"];
+ assert!((b["min"][2].as_f64().unwrap_or(f64::NAN) + 0.5).abs() < 1e-6, "{m}");
+ assert!((b["max"][2].as_f64().unwrap_or(f64::NAN) - 24.5).abs() < 1e-6, "{m}");
+}
+
+#[test]
+fn coil_from_a_sketch_cuts_a_thread_groove() {
+ use std::f64::consts::PI;
+ let mut s = Session::default();
+ run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 40, "body_name": "Shaft"}));
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Groove"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [18, 1], "p1": [19, 2]}));
+ run(&mut s, "sketch.finish", json!({}));
+ let before = volume(&mut s);
+ run(&mut s, "solid.coil", json!({"sketch": "Groove", "revolutions": 3, "pitch": 8, "operation": "cut", "targets": ["Shaft"]}));
+ let removed = before - volume(&mut s);
+ assert!(rel(removed, 2.0 * PI * 3.0 * 1.0 * 18.5) < 1e-3, "{removed}");
+ assert_eq!(measure(&mut s)["body_count"], 1);
+}
+
+fn clockwise_coil_bbox(clockwise: bool) -> Value {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.coil", json!({"sketch": "Section", "revolutions": 0.25, "pitch": 8, "clockwise": clockwise}));
+ measure(&mut s)["bodies"][0]["bbox"].clone()
+}
+
+#[test]
+fn a_sketch_coil_clockwise_is_the_mirror_image() {
+ let right = clockwise_coil_bbox(false);
+ let left = clockwise_coil_bbox(true);
+ let at = |v: &Value, k: &str, i: usize| v[k][i].as_f64().unwrap_or(f64::NAN);
+ assert!((at(&right, "min", 0) + at(&left, "max", 0)).abs() < 1e-6, "{right} {left}");
+ assert!((at(&right, "max", 0) + at(&left, "min", 0)).abs() < 1e-6, "{right} {left}");
+ for i in 1..3 {
+ assert!((at(&right, "min", i) - at(&left, "min", i)).abs() < 1e-6, "{right} {left}");
+ assert!((at(&right, "max", i) - at(&left, "max", i)).abs() < 1e-6, "{right} {left}");
+ }
+}
+
+#[test]
+fn a_sketch_coil_refuses_profiles_it_cannot_sweep() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Holed"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -2], "p1": [14, 2]}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [11, -1], "p1": [13, 1]}));
+ run(&mut s, "sketch.finish", json!({}));
+ let e = s.execute("solid.coil", &json!({"sketch": "Holed", "revolutions": 3, "pitch": 8})).unwrap_err().to_string();
+ assert!(e.contains("without holes"), "{e}");
+
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Two"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [12, -0.5], "p1": [13, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ let e = s.execute("solid.coil", &json!({"sketch": "Two", "revolutions": 3, "pitch": 8})).unwrap_err().to_string();
+ assert!(e.contains("one closed profile"), "{e}");
+
+ // The kernel refuses a pitch no larger than the profile's axial extent.
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ let e = s.execute("solid.coil", &json!({"sketch": "Section", "revolutions": 3, "pitch": 0.5})).unwrap_err().to_string();
+ assert!(e.contains("runs into itself"), "{e}");
+}
+
+#[test]
+fn a_sketch_coil_refuses_contradictory_parameters() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ for (k, v) in [
+ ("diameter", json!(40)),
+ ("section_size", json!(2)),
+ ("section", json!("square")),
+ ("section_position", json!("outside")),
+ ("start_angle", json!(0)),
+ ] {
+ let mut p = json!({"sketch": "Section", "revolutions": 3, "pitch": 8});
+ p[k] = v;
+ let e = s.execute("solid.coil", &p).unwrap_err().to_string();
+ assert!(e.contains("does not apply with `sketch`"), "{k}: {e}");
+ }
+ let e = s
+ .execute("solid.coil", &json!({"profiles": "all", "diameter": 40, "revolutions": 3, "pitch": 8, "section_size": 2}))
+ .unwrap_err()
+ .to_string();
+ assert!(e.contains("`profiles` needs `sketch`"), "{e}");
+ let e = s.execute("solid.coil", &json!({"sketch": "Nope", "revolutions": 3, "pitch": 8})).unwrap_err().to_string();
+ assert!(e.contains("no sketch `Nope`"), "{e}");
+}
+
+#[test]
+fn a_loaded_coil_cannot_be_both_primitive_and_from_a_sketch() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.coil", json!({"sketch": "Section", "revolutions": 3, "pitch": 8}));
+ let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
+ let coil = v["features"].as_array_mut().unwrap().iter_mut().find(|f| f["type"] == "coil").unwrap();
+ coil["diameter"] = json!("40");
+ let reopened = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap());
+ let err = reopened.model.results.iter().find_map(|r| r.error.clone()).unwrap_or_default();
+ assert!(err.contains("cannot also set"), "{err}");
+}
+
+#[test]
+fn a_loaded_sketch_coil_cannot_also_set_the_primitive_section() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.coil", json!({"sketch": "Section", "revolutions": 3, "pitch": 8}));
+ for (field, value) in [("section", json!("square")), ("position", json!(1)), ("start_angle", json!("45 deg"))] {
+ let mut v: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
+ let coil = v["features"].as_array_mut().unwrap().iter_mut().find(|f| f["type"] == "coil").unwrap();
+ coil[field] = value;
+ let reopened = Session::new(solidcraft_doc::Document::from_json(&v.to_string()).unwrap());
+ let err = reopened.model.results.iter().find_map(|r| r.error.clone()).unwrap_or_default();
+ assert!(err.contains("cannot also set"), "{field}: {err}");
+ }
+}
+
+#[test]
+fn a_sketch_coil_never_panics_on_hostile_parameters() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "YZ", "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, -0.5], "p1": [11, 0.5]}));
+ run(&mut s, "sketch.finish", json!({}));
+ // A valid profile coil, so that each hostile value reaches the parameter it attacks.
+ let with = |k: &str, v: Value| {
+ let mut p = json!({"sketch": "Section", "revolutions": 3, "pitch": 8});
+ p[k] = v;
+ p
+ };
+ for hostile in [json!(true), json!(-1), json!(1e308), json!("nope"), json!([]), json!([0, 0, 0]), json!({"type": "indices"})] {
+ for k in ["sketch", "profiles", "pitch", "revolutions"] {
+ let result = s.execute("solid.coil", &with(k, hostile.clone()));
+ assert!(!matches!(result, Err(crate::EngineError::Internal(..))), "{k} {hostile} panicked: {result:?}");
+ }
+ }
+ // Profile selections reach the parser and the evaluator: no index, shape or point may panic.
+ for profiles in [
+ json!([]),
+ json!([0]),
+ json!([999]),
+ json!([-1]),
+ json!(1e308),
+ json!("nope"),
+ json!({"type": "indices"}),
+ json!([{"point": [1]}]),
+ json!([[]]),
+ json!([{"curves": 7}]),
+ ] {
+ let result = s.execute("solid.coil", &with("profiles", profiles.clone()));
+ assert!(!matches!(result, Err(crate::EngineError::Internal(..))), "profiles {profiles} panicked: {result:?}");
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index dbd15b4039..e782e96f06 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -823,7 +823,7 @@ impl Dialog {
operation: 0,
at: None,
},
- vec![],
+ vec![SelInput::new("Profile", PROFILES, false)],
),
"solid.combine" => Dialog::new(
Kind::Combine { operation: 1, keep_tools: false },
@@ -3917,6 +3917,14 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
for (k, v) in fields {
p.insert((*k).into(), json!(v));
}
+ if *cmd == "solid.coil"
+ && let Some((sketch, index)) = sels(d, 0).profiles().first().copied()
+ {
+ p.insert("sketch".into(), json!(sketch));
+ p.insert("profiles".into(), json!([index]));
+ p.remove("diameter");
+ p.remove("section_size");
+ }
if let Some((point, normal)) = *at {
match *cmd {
"solid.box" => {
@@ -4763,19 +4771,40 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
d.extra.insert("center".into(), pt_expr(center));
d
}
- FeatureKind::Coil { base, axis, diameter, pitch, turns, section_size, section, position, start_angle, clockwise, operation, targets } => {
+ FeatureKind::Coil {
+ base,
+ axis,
+ sketch,
+ profiles,
+ diameter,
+ pitch,
+ turns,
+ section_size,
+ section,
+ position,
+ start_angle,
+ clockwise,
+ operation,
+ targets,
+ } => {
let mut d = start("solid.coil")?;
d.kind = Kind::Primitive {
cmd: "solid.coil",
fields: vec![
- ("diameter", stored_length(s, diameter)),
+ ("diameter", diameter.as_ref().map(|e| stored_length(s, e)).unwrap_or_default()),
("revolutions", turns.to_string()),
("pitch", stored_length(s, pitch)),
- ("section_size", stored_length(s, section_size)),
+ ("section_size", section_size.as_ref().map(|e| stored_length(s, e)).unwrap_or_default()),
],
operation: op_index(operation),
at: None,
};
+ if let Some(sketch) = sketch {
+ let items = st.sketch(sketch.0).map(|ss| profile_indices(ss, profiles)).unwrap_or_default();
+ if let Some(inp) = d.inputs.get_mut(0) {
+ inp.items = items.into_iter().map(|index| Sel::Profile { sketch: sketch.0, index }).collect();
+ }
+ }
d.extra.insert("base".into(), pt_expr(base));
d.extra.insert("axis".into(), pt3(axis.0));
if *section == solidcraft_engine::doc::CoilSection::Square {
diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs
index 8e2b6ab866..434c2c186b 100644
--- a/crates/ui-egui/src/dialogs_all_tests.rs
+++ b/crates/ui-egui/src/dialogs_all_tests.rs
@@ -34,6 +34,9 @@ fn representative(h: &Harness, command: &str) -> Dialog {
if command == "joint.gear" {
continue;
}
+ if command == "solid.coil" {
+ continue; // an empty Profile input keeps the primitive section, which this form checks
+ }
if matches!(input.label, "Rail" | "Second Rail" | "Pass through" | "Direction" | "Roller (optional)" | "Tip (optional)") {
continue;
}
@@ -470,3 +473,20 @@ fn solid_pattern_quantity_arrows_step_the_count_the_command_receives() {
h.settle();
}
}
+
+#[test]
+fn coil_from_a_profile_hides_the_primitive_section() {
+ let h = fixture();
+ let mut d = Dialog::for_command(&h.app, "solid.coil").unwrap();
+ let sketch = h.app.session.world_state().sketches[0].feature;
+ d.inputs[0].items = vec![Sel::Profile { sketch, index: 0 }];
+ let commands = apply_commands(&h.app, &d).unwrap();
+ let (id, p) = &commands[0];
+ assert_eq!(id, "solid.coil");
+ assert_eq!(p["sketch"], json!(sketch));
+ assert_eq!(p["profiles"], json!([0]));
+ assert!(p.get("diameter").is_none(), "{p}");
+ assert!(p.get("section_size").is_none(), "{p}");
+ assert!(p.get("revolutions").is_some() && p.get("pitch").is_some(), "{p}");
+ assert!(p.get("operation").is_some(), "{p}");
+}
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index 475eb43520..cdc5b01f5f 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -784,7 +784,11 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
extra_options(ui, "move_options", &mut d.extra, &[("Create Copy", "copy")]);
}
Kind::Primitive { cmd, fields, operation, at } => {
+ let from_sketch = *cmd == "solid.coil" && d.inputs.first().is_some_and(|i| i.accept & selection::PROFILES != 0 && !i.items.is_empty());
for (k, v) in fields.iter_mut() {
+ if from_sketch && (*k == "diameter" || *k == "section_size") {
+ continue;
+ }
enter |= expr_row(ui, k, v);
}
if *cmd == "solid.coil" {