Skip to content

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

Agents and scripts: the sketch projection commands describe their exact parameters and reply (#12505) (#12598)

PeppaWutz4d96c780e11f
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index a96158d30f..e288b5c5a4 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -129,6 +129,7 @@ mod sketch_import;
mod sketch_inspect;
mod sketch_modify;
mod sketch_project;
+pub(crate) use sketch_project::{RefForm, ref_form};
mod sketch_store;
mod surface;
mod surface_analysis;
diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs
index c48bb06008..0b1de8ec77 100644
--- a/crates/engine/src/cmd/sketch_project.rs
+++ b/crates/engine/src/cmd/sketch_project.rs
@@ -13,6 +13,12 @@ use solidcraft_sketch::{ConstraintKind, LinkKind, LinkSource, Sketch};
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, bool_, str_, vec3};
+use crate::schema::sketch_project::{
+ AutoProjectParams, AutoProjectResult, FitCurvesParams, FitSectionResult, Include3dParams, IntersectParams, IntersectionCurveParams,
+ IsoCurveParams, LinkMade, ProjectParams, ProjectResult, ProjectToSurfaceParams, ProjectToSurfaceResult, ProjectedLink, SketchBreakLinkParams,
+ SketchBreakLinkResult, SketchLinkResult, SpunProfileParams,
+};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
macro_rules! refs_doc {
@@ -21,105 +27,160 @@ macro_rules! refs_doc {
};
}
+const PROJECT_CONTRACT: TypedContract<ProjectParams> = TypedContract::new();
+const INTERSECT_CONTRACT: TypedContract<IntersectParams> = TypedContract::new();
+const INCLUDE_3D_CONTRACT: TypedContract<Include3dParams> = TypedContract::new();
+const PROJECT_TO_SURFACE_CONTRACT: TypedContract<ProjectToSurfaceParams> = TypedContract::new();
+const INTERSECTION_CURVE_CONTRACT: TypedContract<IntersectionCurveParams> = TypedContract::new();
+const SPUN_PROFILE_CONTRACT: TypedContract<SpunProfileParams> = TypedContract::new();
+const ISO_CURVE_CONTRACT: TypedContract<IsoCurveParams> = TypedContract::new();
+const FIT_SECTION_CONTRACT: TypedContract<FitCurvesParams> = TypedContract::new();
+const BREAK_LINK_CONTRACT: TypedContract<SketchBreakLinkParams> = TypedContract::new();
+const AUTO_PROJECT_CONTRACT: TypedContract<AutoProjectParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sketch.project", "Project", project_cmd).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).params(
+ CommandSpec::new("sketch.project", "Project", crate::checked!("sketch.project", project_cmd)).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).contract(&PROJECT_CONTRACT).output(output_schema_for::<ProjectResult>).params(
concat!(refs_doc!(), "; projection_link?: bool (default true)", created_doc!()),
),
- CommandSpec::new("sketch.intersect", "Intersect", intersect_cmd).at("SKETCH", "CREATE").icon("intersect").enabled(in_sketch).params(
+ CommandSpec::new("sketch.intersect", "Intersect", crate::checked!("sketch.intersect", intersect_cmd)).at("SKETCH", "CREATE").icon("intersect").enabled(in_sketch).contract(&INTERSECT_CONTRACT).output(output_schema_for::<ProjectResult>).params(
concat!("refs: [{body}, {face: [x,y,z], body?}, {edge: [x,y,z], body?}, {sketch, curve}]: section curves (or points) with the sketch plane; projection_link?: bool (default true)", created_doc!()),
),
- CommandSpec::new("sketch.include_3d", "Include 3D Geometry", include_cmd)
+ CommandSpec::new("sketch.include_3d", "Include 3D Geometry", crate::checked!("sketch.include_3d", include_cmd))
.at("SKETCH", "CREATE")
.icon("include")
.enabled(in_sketch)
- .params(concat!("refs: like Project (edges, vertices, sketch curves and points); curves out of the sketch plane are flattened onto it", created_doc!())),
- CommandSpec::new("sketch.project_to_surface", "Project To Surface", project_to_surface)
+ .contract(&INCLUDE_3D_CONTRACT).output(output_schema_for::<ProjectResult>).params(concat!("refs: like Project (edges, vertices, sketch curves and points); curves out of the sketch plane are flattened onto it", created_doc!())),
+ CommandSpec::new("sketch.project_to_surface", "Project To Surface", crate::checked!("sketch.project_to_surface", project_to_surface))
.at("SKETCH", "CREATE")
.icon("project_surface")
.enabled(in_sketch)
- .params(concat!("curves: [{sketch, curve}…] (curves of other sketches), face: [x,y,z] point on the target face, body?: projected along the active sketch's normal onto the face, as linked 3D curves", created_doc!())),
- CommandSpec::new("sketch.intersection_curve", "Intersection Curve", intersection_curve)
+ .contract(&PROJECT_TO_SURFACE_CONTRACT).output(output_schema_for::<ProjectToSurfaceResult>).params(concat!("curves: [{sketch, curve}…] (curves of other sketches), face: [x,y,z] point on the target face, body?: projected along the active sketch's normal onto the face, as linked 3D curves", created_doc!())),
+ CommandSpec::new("sketch.intersection_curve", "Intersection Curve", crate::checked!("sketch.intersection_curve", intersection_curve))
.at("SKETCH", "CREATE")
.icon("intersection_curve")
.enabled(in_sketch)
- .params(concat!("a, b: {body} | {face: [x,y,z], body?} | {sketch, curve} (a curve of another sketch, standing in for its extrusion along that sketch's normal): where they meet, as linked 3D curves", created_doc!())),
- CommandSpec::new("sketch.spun_profile", "Spun Profile", spun_profile)
+ .contract(&INTERSECTION_CURVE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("a, b: {body} | {face: [x,y,z], body?} | {sketch, curve} (a curve of another sketch, standing in for its extrusion along that sketch's normal): where they meet, as linked 3D curves", created_doc!())),
+ CommandSpec::new("sketch.spun_profile", "Spun Profile", crate::checked!("sketch.spun_profile", spun_profile))
.at("SKETCH", "CREATE")
.icon("spun")
.enabled(in_sketch)
- .params(concat!("body: name, axis: a line of the active sketch (curve id) | X|Y|Z: the body's outline revolved about the axis, in the sketch plane", created_doc!())),
- CommandSpec::new("sketch.isoparametric_curve", "Isoparametric Curve", iso_curve)
+ .contract(&SPUN_PROFILE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("body: name, axis: a line of the active sketch (curve id) | X|Y|Z: the body's outline revolved about the axis, in the sketch plane", created_doc!())),
+ CommandSpec::new("sketch.isoparametric_curve", "Isoparametric Curve", crate::checked!("sketch.isoparametric_curve", iso_curve))
.at("SKETCH", "CREATE")
.icon("iso_curve")
.enabled(in_sketch)
- .params(concat!("face: [x,y,z] point on the face (the curve passes through it), body?, direction?: u|v|[x,y,z] (default u): linked 3D curve", created_doc!())),
- CommandSpec::new("sketch.fit_curves_to_section", "Fit Curves to Mesh Section", fit_section)
+ .contract(&ISO_CURVE_CONTRACT).output(output_schema_for::<SketchLinkResult>).params(concat!("face: [x,y,z] point on the face (the curve passes through it), body?, direction?: u|v|[x,y,z] (default u): linked 3D curve", created_doc!())),
+ CommandSpec::new("sketch.fit_curves_to_section", "Fit Curves to Mesh Section", crate::checked!("sketch.fit_curves_to_section", fit_section))
.at("SKETCH", "CREATE")
.icon("fit_section")
.enabled(in_sketch)
- .params(concat!("body: name (a mesh or solid body): its section with the sketch plane, fitted with lines and arcs, as normal (unlinked) geometry", created_doc!())),
- CommandSpec::new("sketch.break_link", "Break Link", break_link).icon("sketch_break")
+ .contract(&FIT_SECTION_CONTRACT).output(output_schema_for::<FitSectionResult>).params(concat!("body: name (a mesh or solid body): its section with the sketch plane, fitted with lines and arcs, as normal (unlinked) geometry", created_doc!())),
+ CommandSpec::new("sketch.break_link", "Break Link", crate::checked!("sketch.break_link", break_link)).icon("sketch_break")
.enabled(in_sketch)
- .params("link?: link id (j1) | entities?: [curve or point ids]: linked geometry becomes normal sketch geometry"),
- CommandSpec::new("sketch.auto_project", "Auto-Project Edges on Reference", auto_project).icon("project")
+ .contract(&BREAK_LINK_CONTRACT).output(output_schema_for::<SketchBreakLinkResult>).params("link?: link id (j1) | entities?: [curve or point ids]: linked geometry becomes normal sketch geometry"),
+ CommandSpec::new("sketch.auto_project", "Auto-Project Edges on Reference", crate::checked!("sketch.auto_project", auto_project)).icon("project")
.noundo()
- .params("value?: bool (default toggles): project a face's edges when a sketch is created on it"),
+ .contract(&AUTO_PROJECT_CONTRACT).output(output_schema_for::<AutoProjectResult>).params("value?: bool (default toggles): project a face's edges when a sketch is created on it"),
];
-/// Parse one reference.
-fn source(s: &Session, v: &Value, cmd: &str) -> Result<LinkSource> {
+/// What a reference says in its JSON, before the design is asked what it names (`source` goes on
+/// from here, and so does the contract of the commands that take references).
+pub(crate) enum RefForm<'a> {
+ /// Text: `origin`, an axis letter or a body name, which the design decides.
+ Name(&'a str),
+ /// `{edge: [x,y,z], body?}`.
+ Edge { body: String, at: Vec3 },
+ /// `{face: [x,y,z], body?}`.
+ Face { body: String, at: Vec3 },
+ /// `{vertex: [x,y,z], body?}`.
+ Vertex { body: String, at: Vec3 },
+ /// `{sketch, curve}` or `{sketch, point}`: the sketch as the lookup reads it (an id or a name)
+ /// and the `curve` or `point` given. With neither, the handler refuses it once the sketch is
+ /// found.
+ Sketch { key: String, curve: Option<&'a str>, point: Option<&'a str> },
+ /// `{body: name}`.
+ Body(&'a str),
+ /// `{axis: X|Y|Z|name}`.
+ Axis(&'a str),
+ /// `{plane: XY|XZ|YZ|name}`.
+ Plane(&'a str),
+ /// `{origin: …}`.
+ Origin,
+}
+
+/// The form of one reference, or the message (without the command's name) for what no design
+/// could make sense of. The forms are tried in this order, the first that fits wins: an edge, face
+/// or vertex whose value is not a point is passed over, not refused.
+pub(crate) fn ref_form(v: &Value) -> std::result::Result<RefForm<'_>, String> {
if let Some(name) = v.as_str() {
- return match name.to_ascii_lowercase().as_str() {
- "origin" => Ok(LinkSource::Origin),
- "x" | "y" | "z" => Ok(LinkSource::Axis { name: name.to_ascii_uppercase() }),
- _ if s.model.state().body(name).is_some() => Ok(LinkSource::Body { body: name.to_string() }),
- _ => Err(bad(cmd, format!("unknown reference `{name}`"))),
- };
+ return Ok(RefForm::Name(name));
}
let body = || str_(v, "body").unwrap_or("").to_string();
if let Some(at) = v.get("edge").and_then(vec3) {
- return Ok(LinkSource::Edge { body: body(), at });
+ return Ok(RefForm::Edge { body: body(), at });
}
if let Some(at) = v.get("face").and_then(vec3) {
- return Ok(LinkSource::Face { body: body(), at });
+ return Ok(RefForm::Face { body: body(), at });
}
if let Some(at) = v.get("vertex").and_then(vec3) {
- return Ok(LinkSource::Vertex { body: body(), at });
+ return Ok(RefForm::Vertex { body: body(), at });
}
if let Some(sk) = v.get("sketch") {
let key = match sk {
Value::Number(n) => n.to_string(),
Value::String(x) => x.clone(),
- _ => return Err(bad(cmd, "`sketch` must be an id or a name")),
+ _ => return Err("`sketch` must be an id or a name".into()),
};
- let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
- if !matches!(f.kind, FeatureKind::Sketch { .. }) {
- return Err(bad(cmd, format!("`{key}` is not a sketch")));
- }
- if Some(f.id) == s.active_sketch {
- return Err(bad(cmd, "a sketch cannot project its own geometry"));
- }
- if let Some(c) = str_(v, "curve") {
- return Ok(LinkSource::SketchCurve { sketch: f.id, curve: c.to_string() });
- }
- if let Some(p) = str_(v, "point") {
- return Ok(LinkSource::SketchPoint { sketch: f.id, point: p.to_string() });
- }
- return Err(bad(cmd, "a sketch reference needs `curve` or `point`"));
+ return Ok(RefForm::Sketch { key, curve: str_(v, "curve"), point: str_(v, "point") });
}
if let Some(b) = str_(v, "body") {
- return Ok(LinkSource::Body { body: b.to_string() });
+ return Ok(RefForm::Body(b));
}
if let Some(a) = str_(v, "axis") {
- return axis_source(s, a, cmd);
+ return Ok(RefForm::Axis(a));
}
if let Some(p) = str_(v, "plane") {
- return Ok(LinkSource::Plane { name: p.to_string() });
+ return Ok(RefForm::Plane(p));
}
if v.get("origin").is_some() {
- return Ok(LinkSource::Origin);
+ return Ok(RefForm::Origin);
+ }
+ Err(format!("cannot project {v}"))
+}
+
+/// Parse one reference.
+fn source(s: &Session, v: &Value, cmd: &str) -> Result<LinkSource> {
+ match ref_form(v).map_err(|why| bad(cmd, why))? {
+ RefForm::Name(name) => match name.to_ascii_lowercase().as_str() {
+ "origin" => Ok(LinkSource::Origin),
+ "x" | "y" | "z" => Ok(LinkSource::Axis { name: name.to_ascii_uppercase() }),
+ _ if s.model.state().body(name).is_some() => Ok(LinkSource::Body { body: name.to_string() }),
+ _ => Err(bad(cmd, format!("unknown reference `{name}`"))),
+ },
+ RefForm::Edge { body, at } => Ok(LinkSource::Edge { body, at }),
+ RefForm::Face { body, at } => Ok(LinkSource::Face { body, at }),
+ RefForm::Vertex { body, at } => Ok(LinkSource::Vertex { body, at }),
+ RefForm::Sketch { key, curve, point } => {
+ let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
+ if !matches!(f.kind, FeatureKind::Sketch { .. }) {
+ return Err(bad(cmd, format!("`{key}` is not a sketch")));
+ }
+ if Some(f.id) == s.active_sketch {
+ return Err(bad(cmd, "a sketch cannot project its own geometry"));
+ }
+ if let Some(c) = curve {
+ return Ok(LinkSource::SketchCurve { sketch: f.id, curve: c.to_string() });
+ }
+ if let Some(p) = point {
+ return Ok(LinkSource::SketchPoint { sketch: f.id, point: p.to_string() });
+ }
+ Err(bad(cmd, "a sketch reference needs `curve` or `point`"))
+ }
+ RefForm::Body(b) => Ok(LinkSource::Body { body: b.to_string() }),
+ RefForm::Axis(a) => axis_source(s, a, cmd),
+ RefForm::Plane(p) => Ok(LinkSource::Plane { name: p.to_string() }),
+ RefForm::Origin => Ok(LinkSource::Origin),
}
- Err(bad(cmd, format!("cannot project {v}")))
}
/// An origin axis (`X`, `Y` or `Z`, in any case), or a construction axis by its name (#9324).
@@ -391,10 +452,17 @@ fn add_link_unless_present(
Ok(Some(link))
}
-fn link_json(sk: &Sketch, link: &str) -> Value {
+/// A command's reply as JSON: they build their replies from the types their output schemas
+/// describe, so the two can't drift apart.
+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
+}
+
+/// The ids of the curves and of the points that link `link` made.
+fn link_parts(sk: &Sketch, link: &str) -> (Vec<String>, Vec<String>) {
let curves: Vec<String> = sk.link_curves(link).iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect();
let points: Vec<String> = sk.link_points(link).iter().filter_map(|p| sk.points.get(*p).map(|p| p.id.clone())).collect();
- json!({"link": link, "curves": curves, "points": points})
+ (curves, points)
}
fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_link: bool) -> Result<Value> {
@@ -418,9 +486,10 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_l
let what = src.describe();
match add_link_unless_present(s, doc, id, sk, kind, src, kind == LinkKind::Project) {
Ok(Some(l)) => {
- let mut result = link_json(sk, &l);
+ let (curves, points) = link_parts(sk, &l);
+ let mut result = ProjectedLink { link: Some(l.clone()), curves, points };
if !projection_link {
- result["link"] = Value::Null;
+ result.link = None;
sk.break_link(&l)?;
}
out.push(result);
@@ -435,11 +504,7 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_l
}
Ok((out, present))
})?;
- let mut r = json!({"links": out});
- if !present.is_empty() {
- r["already_projected"] = json!(present);
- }
- Ok(r)
+ reply(cmd, ProjectResult { links: out, already_projected: present, created: None, param_warnings: Vec::new() })
}
fn project_cmd(s: &mut Session, p: &Value) -> Result<Value> {
@@ -543,16 +608,15 @@ pub(super) fn project_entities(s: &mut Session, p: &Value, cmd: &str) -> Result<
}
/// Add one link from `src` to the active sketch and report it.
-fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<Value> {
+fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<LinkMade> {
let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?;
sketch_store::update(s, id, |s, doc, sk| {
refresh(s, doc, id, sk);
let what = src.describe();
let l = add_link(s, doc, id, sk, kind, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?;
- let mut out = link_json(sk, &l);
+ let (curves, points) = link_parts(sk, &l);
let wires: Vec<String> = sk.link_wires(&l).iter().filter_map(|w| sk.wires.get(*w).map(|w| w.id.clone())).collect();
- out["wires"] = json!(wires);
- Ok(out)
+ Ok(LinkMade { link: l, curves, points, wires })
})
}
@@ -571,7 +635,7 @@ fn project_to_surface(s: &mut Session, p: &Value) -> Result<Value> {
};
out.push(one_link(s, cmd, LinkKind::Project, LinkSource::OnSurface { sketch, curve, body: body.clone(), at })?);
}
- Ok(json!({"links": out}))
+ reply(cmd, ProjectToSurfaceResult { links: out, created: None, param_warnings: Vec::new() })
}
fn intersection_curve(s: &mut Session, p: &Value) -> Result<Value> {
@@ -584,7 +648,8 @@ fn intersection_curve(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let (a, b) = (side("a")?, side("b")?);
- one_link(s, cmd, LinkKind::Include, LinkSource::Intersection { a: Box::new(a), b: Box::new(b) })
+ let made = one_link(s, cmd, LinkKind::Include, LinkSource::Intersection { a: Box::new(a), b: Box::new(b) })?;
+ reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
}
fn spun_profile(s: &mut Session, p: &Value) -> Result<Value> {
@@ -605,7 +670,8 @@ fn spun_profile(s: &mut Session, p: &Value) -> Result<Value> {
(wa, wb - wa)
}
};
- one_link(s, cmd, LinkKind::Project, LinkSource::Spun { body, origin, dir })
+ let made = one_link(s, cmd, LinkKind::Project, LinkSource::Spun { body, origin, dir })?;
+ reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
}
fn iso_curve(s: &mut Session, p: &Value) -> Result<Value> {
@@ -620,7 +686,8 @@ fn iso_curve(s: &mut Session, p: &Value) -> Result<Value> {
format!("{},{},{}", d.x, d.y, d.z)
}
};
- one_link(s, cmd, LinkKind::Include, LinkSource::Iso { body, at, dir })
+ let made = one_link(s, cmd, LinkKind::Include, LinkSource::Iso { body, at, dir })?;
+ reply(cmd, SketchLinkResult { made, created: None, param_warnings: Vec::new() })
}
fn fit_section(s: &mut Session, p: &Value) -> Result<Value> {
@@ -636,7 +703,7 @@ fn fit_section(s: &mut Session, p: &Value) -> Result<Value> {
sk.break_link(&l)?;
Ok(curves)
})?;
- Ok(json!({"curves": curves}))
+ reply(cmd, FitSectionResult { curves, created: None, param_warnings: Vec::new() })
}
fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
@@ -670,12 +737,12 @@ fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(links)
})?;
- Ok(json!({"broken": links}))
+ reply(cmd, SketchBreakLinkResult { broken: links, created: None, param_warnings: Vec::new() })
}
fn auto_project(s: &mut Session, p: &Value) -> Result<Value> {
s.auto_project = bool_(p, "value").unwrap_or(!s.auto_project);
- Ok(json!({"auto_project": s.auto_project}))
+ reply("sketch.auto_project", AutoProjectResult { auto_project: s.auto_project, created: None, param_warnings: Vec::new() })
}
/// `"x:<a>+<b>:x,y"` from interactive snapping: two distinct curve ids and a hint point.
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 2df052d85e..e97d3dc184 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -112,6 +112,7 @@ pub mod sketch_ends;
pub mod sketch_equation;
pub mod sketch_inspect;
pub mod sketch_modify;
+pub mod sketch_project;
pub mod sketch_shapes;
pub mod surface_analysis;
pub mod surface_boundary;
diff --git a/crates/engine/src/schema/sketch_project.rs b/crates/engine/src/schema/sketch_project.rs
new file mode 100644
index 0000000000..761f2c07e8
--- /dev/null
+++ b/crates/engine/src/schema/sketch_project.rs
@@ -0,0 +1,767 @@
+//! Contracts and result types for the commands in `cmd/sketch_project.rs`: `sketch.project`,
+//! `sketch.intersect`, `sketch.include_3d`, `sketch.project_to_surface`,
+//! `sketch.intersection_curve`, `sketch.spun_profile`, `sketch.isoparametric_curve`,
+//! `sketch.fit_curves_to_section`, `sketch.break_link` and `sketch.auto_project`.
+//!
+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
+//! reads it and fails with the handler's message. What only the design can tell (a body, sketch or
+//! curve that exists, an axis name, whether a reference projects to anything) stays the handler's
+//! to check: a reference given as text, or as an axis name, passes here and is looked up there, and
+//! so does a reference to a sketch, whose `curve` or `point` the handler checks once it has found
+//! the sketch.
+//! A call with several problems may get a different one first in strict than with the check off
+//! (the check goes key by key, the handlers in their own order).
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Map, Value, json};
+
+use super::check::whole;
+use super::motion::require;
+use super::types::Point3;
+use crate::cmd::{RefForm, ref_form};
+use crate::params;
+
+/// What a reference to model geometry may look like, for the descriptions.
+const REF_FORMS: &str = "a reference: `{\"edge\": [x, y, z], \"body\"?}` (the edge through that point), `{\"face\": [x, y, z], \"body\"?}` (the edges of the face), `{\"vertex\": [x, y, z], \"body\"?}`, `{\"body\": name}` (its silhouette or outline), `{\"sketch\": id or name, \"curve\": id}` or `{\"sketch\": id or name, \"point\": id}` (a curve or point of another sketch), `\"origin\"` or `{\"origin\": …}`, `{\"axis\": \"X\"|\"Y\"|\"Z\"|a construction axis's name}`, `{\"plane\": \"XY\"|\"XZ\"|\"YZ\"|a plane's name}`; text alone is `origin`, X, Y, Z (any case) or a body's name";
+
+/// The most references one `refs` takes into account: the handler reads no more.
+const MAX_REFS: usize = 1000;
+
+/// Whether text is what `cmd/sketch_project.rs` reads as the origin or an origin axis, which is
+/// settled without the design; any other text may be a body's name.
+fn is_origin_or_axis(name: &str) -> bool {
+ ["origin", "x", "y", "z"].iter().any(|word| name.eq_ignore_ascii_case(word))
+}
+
+/// The handler's message for a reference that says nothing a design could be asked about, in its
+/// own words, or `None` when the form is fine. A sketch reference with neither `curve` nor `point`
+/// is fine here: the handler refuses it only once it has looked the sketch up, and says "no sketch"
+/// first when there is none.
+fn ref_problem(v: &Value) -> Option<String> {
+ ref_form(v).err()
+}
+
+/// One reference of `sketch.project`, `sketch.intersect` and `sketch.include_3d`, kept as given
+/// for the handler.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ProjectRef(pub Value);
+
+impl<'de> Deserialize<'de> for ProjectRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ match ref_problem(&v) {
+ Some(why) => Err(D::Error::custom(whole(why))),
+ None => Ok(ProjectRef(v)),
+ }
+ }
+}
+
+impl JsonSchema for ProjectRef {
+ fn schema_name() -> Cow<'static, str> {
+ "ProjectRef".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ let with_body = |key: &str| {
+ json!({
+ "type": "object",
+ "properties": {key: point, "body": {"type": "string", "description": "The body's name. Default: any body. Text only: the handler reads anything else as left out, which the schema does not take."}},
+ "required": [key]
+ })
+ };
+ json_schema!({
+ "description": REF_FORMS,
+ "anyOf": [
+ {"type": "string"},
+ with_body("edge"),
+ with_body("face"),
+ with_body("vertex"),
+ {
+ "type": "object",
+ "properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
+ "required": ["sketch", "curve"]
+ },
+ {
+ "type": "object",
+ "properties": {"sketch": {"type": ["number", "string"]}, "point": {"type": "string"}},
+ "required": ["sketch", "point"]
+ },
+ {"type": "object", "properties": {"body": {"type": "string"}}, "required": ["body"]},
+ {"type": "object", "properties": {"axis": {"type": "string"}}, "required": ["axis"]},
+ {"type": "object", "properties": {"plane": {"type": "string"}}, "required": ["plane"]},
+ {"type": "object", "required": ["origin"]}
+ ]
+ })
+ }
+}
+
+/// The references of `refs` (or `ref`): a list, or one reference. Only the first 1000 of a list
+/// count, as the handler reads no more.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ProjectRefs(pub Vec<Value>);
+
+impl ProjectRefs {
+ /// The references `v` lists, or the handler's message for them. A value that is not a list is
+ /// one reference.
+ fn read(v: &Value) -> Result<ProjectRefs, String> {
+ let list: Vec<&Value> = match v {
+ Value::Array(a) => a.iter().take(MAX_REFS).collect(),
+ one => vec![one],
+ };
+ if list.is_empty() {
+ return Err("`refs` is empty".into());
+ }
+ if let Some(why) = list.iter().find_map(|r| ref_problem(r)) {
+ return Err(why);
+ }
+ Ok(ProjectRefs(list.into_iter().cloned().collect()))
+ }
+}
+
+impl JsonSchema for ProjectRefs {
+ fn schema_name() -> Cow<'static, str> {
+ "ProjectRefs".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let one = generator.subschema_for::<ProjectRef>();
+ json_schema!({
+ "description": "One reference or a non-empty list of them (the first 1000 count).",
+ "anyOf": [one, {"type": "array", "items": one, "minItems": 1}]
+ })
+ }
+}
+
+/// `refs`, or `ref` when `refs` is absent (the handler reads `ref` only then, `null` included).
+fn read_refs(o: &Map<String, Value>) -> Result<(Option<ProjectRefs>, Option<ProjectRefs>), String> {
+ match (o.get("refs"), o.get("ref")) {
+ (Some(v), _) => Ok((Some(ProjectRefs::read(v)?), None)),
+ (None, Some(v)) => Ok((None, Some(ProjectRefs::read(v)?))),
+ (None, None) => Ok((None, None)),
+ }
+}
+
+/// `projection_link`: a boolean, and `null` is refused too (the message is the same for both
+/// commands that take it).
+fn read_link_flag(o: &Map<String, Value>) -> Result<Option<bool>, String> {
+ match o.get("projection_link") {
+ None => Ok(None),
+ Some(Value::Bool(b)) => Ok(Some(*b)),
+ Some(_) => Err("`projection_link` must be a boolean".into()),
+ }
+}
+
+/// `refs` and `ref` are one of them required: left out, the handler refuses with its own message.
+fn refs_required(schema: &mut Schema) {
+ schema.insert("anyOf".into(), json!([{"required": ["refs"]}, {"required": ["ref"]}]));
+}
+
+/// Bring model edges, faces, bodies, other sketches' curves and points, the origin, an axis or a
+/// plane into the active sketch as linked reference geometry: fixed, drawn purple and updated
+/// when the upstream geometry changes. What the sketch already shows (the border of its face, an
+/// edge projected before) is skipped and listed in `already_projected`; a call that adds nothing is
+/// refused. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = refs_required)]
+pub struct ProjectParams {
+ /// What to project: one reference or a list.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ProjectRefs")]
+ pub refs: Option<ProjectRefs>,
+ /// The same as `refs`, used only when `refs` is not given.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(rename = "ref", with = "ProjectRefs")]
+ pub reference: Option<ProjectRefs>,
+ /// Keep the geometry linked to its source (true), or make it normal sketch geometry at once
+ /// (false: the replies' `link` is then null). Default: true.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub projection_link: Option<bool>,
+}
+
+impl<'de> Deserialize<'de> for ProjectParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let o = Map::<String, Value>::deserialize(d)?;
+ // The handler reads `projection_link` before the references.
+ let projection_link = read_link_flag(&o).map_err(|why| D::Error::custom(whole(why)))?;
+ let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
+ Ok(ProjectParams { refs, reference, projection_link })
+ }
+}
+
+/// Intersect the sketch plane with model bodies, faces, edges and other sketches' curves, and
+/// bring the section curves (or points) into the active sketch as linked reference geometry. One
+/// undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = refs_required)]
+pub struct IntersectParams {
+ /// What to intersect with the sketch plane: one reference or a list (`{body}`, `{face}`,
+ /// `{edge}` or `{sketch, curve}` are the forms that make sense here).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ProjectRefs")]
+ pub refs: Option<ProjectRefs>,
+ /// The same as `refs`, used only when `refs` is not given.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(rename = "ref", with = "ProjectRefs")]
+ pub reference: Option<ProjectRefs>,
+ /// Keep the geometry linked to its source (true), or make it normal sketch geometry at once
+ /// (false: the reply's `link` is then null). Default: true.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub projection_link: Option<bool>,
+}
+
+impl<'de> Deserialize<'de> for IntersectParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let o = Map::<String, Value>::deserialize(d)?;
+ let projection_link = read_link_flag(&o).map_err(|why| D::Error::custom(whole(why)))?;
+ let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
+ Ok(IntersectParams { refs, reference, projection_link })
+ }
+}
+
+/// Include model edges, vertices, and other sketches' curves and points in the active sketch as
+/// linked geometry; curves out of the sketch plane are flattened onto it. Takes the references of
+/// `sketch.project`, and always keeps the link. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = refs_required)]
+pub struct Include3dParams {
+ /// What to include: one reference or a list.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ProjectRefs")]
+ pub refs: Option<ProjectRefs>,
+ /// The same as `refs`, used only when `refs` is not given.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(rename = "ref", with = "ProjectRefs")]
+ pub reference: Option<ProjectRefs>,
+}
+
+impl<'de> Deserialize<'de> for Include3dParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let o = Map::<String, Value>::deserialize(d)?;
+ let (refs, reference) = read_refs(&o).map_err(|why| D::Error::custom(whole(why)))?;
+ Ok(Include3dParams { refs, reference })
+ }
+}
+
+/// A key that, once given (`null` included), must parse as `T`, as the handlers read it.
+fn some<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
+ T::deserialize(d).map(Some)
+}
+
+/// A point `[x, y, z]` or `{x, y, z}` with the handler's own message.
+macro_rules! point_with_message {
+ ($(#[$doc:meta])* $name:ident, $message:literal) => {
+ $(#[$doc])*
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub struct $name(pub solidcore_record::Vec3);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec3(&Value::deserialize(d)?).map($name).ok_or_else(|| D::Error::custom(whole($message)))
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<Point3>()
+ }
+ }
+ };
+}
+
+point_with_message!(
+ /// `sketch.project_to_surface`'s `face`, with the handler's message.
+ TargetFacePoint,
+ "`face` must be a point [x,y,z] on the target face"
+);
+point_with_message!(
+ /// `sketch.isoparametric_curve`'s `face`, with the handler's message.
+ IsoFacePoint,
+ "`face` must be a point [x,y,z] on the face"
+);
+
+/// A curve to project onto a surface: `{sketch, curve}`, read as the handler reads it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SurfaceCurve(pub Value);
+
+impl SurfaceCurve {
+ fn problem(v: &Value) -> Option<String> {
+ const EACH: &str = "each entry must be {sketch, curve}";
+ match ref_form(v) {
+ Err(why) => Some(why),
+ // What the handler says of a sketch reference comes after it has found the sketch.
+ Ok(RefForm::Sketch { .. }) => None,
+ // Whether text names a body, or an axis a construction axis, only the design knows;
+ // either way it is not a curve.
+ Ok(RefForm::Name(name)) if !is_origin_or_axis(name) => None,
+ Ok(RefForm::Axis(name)) if !is_origin_or_axis(name) => None,
+ Ok(_) => Some(EACH.into()),
+ }
+ }
+}
+
+/// The `curves` of `sketch.project_to_surface`: 1 to 500 of them.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SurfaceCurves(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for SurfaceCurves {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = match Value::deserialize(d)? {
+ Value::Array(list) => list,
+ _ => return Err(D::Error::custom(whole("`curves` must list {sketch, curve}"))),
+ };
+ if list.is_empty() || list.len() > 500 {
+ return Err(D::Error::custom(whole("`curves` must list 1…500 curves")));
+ }
+ if let Some(why) = list.iter().find_map(SurfaceCurve::problem) {
+ return Err(D::Error::custom(whole(why)));
+ }
+ Ok(SurfaceCurves(list))
+ }
+}
+
+impl JsonSchema for SurfaceCurves {
+ fn schema_name() -> Cow<'static, str> {
+ "SurfaceCurves".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "From 1 to 500 curves of other sketches, each {\"sketch\": id or name, \"curve\": curve id}.",
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 500,
+ "items": {
+ "type": "object",
+ "properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
+ "required": ["sketch", "curve"]
+ }
+ })
+ }
+}
+
+/// Project curves of other sketches along the active sketch's normal onto a face of the model,
+/// as linked 3D curves. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = surface_required)]
+pub struct ProjectToSurfaceParams {
+ // Optional in the type and required in the schema (`surface_required`): left out, the handler
+ // refuses it with its own message, not the check's "is required".
+ /// The curves to project: 1 to 500 of `{"sketch": id or name, "curve": id}`, curves of other
+ /// sketches.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SurfaceCurves")]
+ pub curves: Option<SurfaceCurves>,
+ /// A point [x, y, z] in mm on the target face.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "TargetFacePoint")]
+ pub face: Option<TargetFacePoint>,
+ /// The face's body. Default: any body the point is on. Text only; anything else is read as
+ /// left out.
+ #[serde(default)]
+ pub body: Option<String>,
+}
+
+fn surface_required(schema: &mut Schema) {
+ require(schema, "curves");
+ require(schema, "face");
+}
+
+/// One side of `sketch.intersection_curve`: a body, a face, or a curve of another sketch.
+macro_rules! intersection_side {
+ ($(#[$doc:meta])* $name:ident, $key:literal) => {
+ $(#[$doc])*
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct $name(pub Value);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let wrong = || D::Error::custom(whole(concat!("`", $key, "` must be a body, a face or a curve of another sketch")));
+ match ref_form(&v) {
+ Err(why) => Err(D::Error::custom(whole(why))),
+ // A sketch reference is judged by the handler once it has found the sketch.
+ Ok(RefForm::Body(_) | RefForm::Face { .. } | RefForm::Sketch { .. }) => Ok($name(v)),
+ // Text is a body's name, or the origin or an axis; an axis name is looked up.
+ Ok(RefForm::Name(name)) if !is_origin_or_axis(name) => Ok($name(v)),
+ Ok(RefForm::Axis(name)) if !is_origin_or_axis(name) => Ok($name(v)),
+ Ok(_) => Err(wrong()),
+ }
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "A body `{\"body\": name}` (or its name as text), a face `{\"face\": [x, y, z], \"body\"?}` (the face through that point), or a curve of another sketch `{\"sketch\": id or name, \"curve\": id}`, which stands for its extrusion along that sketch's normal.",
+ "anyOf": [
+ {"type": "string"},
+ {"type": "object", "properties": {"body": {"type": "string"}}, "required": ["body"]},
+ {
+ "type": "object",
+ "properties": {"face": point, "body": {"type": "string"}},
+ "required": ["face"]
+ },
+ {
+ "type": "object",
+ "properties": {"sketch": {"type": ["number", "string"]}, "curve": {"type": "string"}},
+ "required": ["sketch", "curve"]
+ }
+ ]
+ })
+ }
+ }
+ };
+}
+
+intersection_side!(
+ /// `sketch.intersection_curve`'s `a`.
+ IntersectionSideA,
+ "a"
+);
+intersection_side!(
+ /// `sketch.intersection_curve`'s `b`.
+ IntersectionSideB,
+ "b"
+);
+
+/// Add where two pieces of model geometry meet to the active sketch, as a linked 3D curve. One
+/// undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = sides_required)]
+pub struct IntersectionCurveParams {
+ // Optional in the type and required in the schema, as `curves` above.
+ /// The first side: a body, a face or a curve of another sketch.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "IntersectionSideA")]
+ pub a: Option<IntersectionSideA>,
+ /// The second side, of the same forms.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "IntersectionSideB")]
+ pub b: Option<IntersectionSideB>,
+}
+
+fn sides_required(schema: &mut Schema) {
+ require(schema, "a");
+ require(schema, "b");
+}
+
+/// A body's name, with the handler's message for text it is not given as.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BodyName(pub String);
+
+impl<'de> Deserialize<'de> for BodyName {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(name) => Ok(BodyName(name)),
+ _ => Err(D::Error::custom(whole("`body` must name a body"))),
+ }
+ }
+}
+
+impl JsonSchema for BodyName {
+ fn schema_name() -> Cow<'static, str> {
+ "BodyName".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A body's name.", "type": "string"})
+ }
+}
+
+/// `sketch.spun_profile`'s `axis`: X, Y or Z (any case), or the id of a line of the active sketch.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SpunAxis(pub String);
+
+impl<'de> Deserialize<'de> for SpunAxis {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(axis) => Ok(SpunAxis(axis)),
+ _ => Err(D::Error::custom(whole("`axis` must be a sketch line or X|Y|Z"))),
+ }
+ }
+}
+
+impl JsonSchema for SpunAxis {
+ fn schema_name() -> Cow<'static, str> {
+ "SpunAxis".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The axis to revolve about: X, Y or Z (any case: the origin's axis), or the id of a line of the active sketch.",
+ "type": "string"
+ })
+ }
+}
+
+/// Add the outline of a body, revolved about an axis, to the active sketch as a linked 3D curve
+/// in the sketch plane. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = spun_required)]
+pub struct SpunProfileParams {
+ // Optional in the type and required in the schema, as `curves` above.
+ /// The body to revolve.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BodyName")]
+ pub body: Option<BodyName>,
+ /// The axis to revolve about: X, Y or Z, or the id of a line of the active sketch.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SpunAxis")]
+ pub axis: Option<SpunAxis>,
+}
+
+fn spun_required(schema: &mut Schema) {
+ require(schema, "body");
+ require(schema, "axis");
+}
+
+/// `sketch.isoparametric_curve`'s `direction`: `u` or `v` (any case), or a direction [x, y, z].
+#[derive(Clone, Debug, PartialEq)]
+pub struct IsoDirection(pub Value);
+
+impl<'de> Deserialize<'de> for IsoDirection {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let word = matches!(&v, Value::String(d) if d.eq_ignore_ascii_case("u") || d.eq_ignore_ascii_case("v"));
+ if word || params::vec3(&v).is_some() { Ok(IsoDirection(v)) } else { Err(D::Error::custom(whole("`direction` must be u, v or [x,y,z]"))) }
+ }
+}
+
+impl JsonSchema for IsoDirection {
+ fn schema_name() -> Cow<'static, str> {
+ "IsoDirection".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "u or v (any case): along the face's parametric direction; or a direction [x, y, z].",
+ "anyOf": [{"type": "string", "enum": ["u", "v", "U", "V"]}, point]
+ })
+ }
+}
+
+/// Add the curve of constant u or v through a point of a face to the active sketch, as a linked
+/// 3D curve. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = face_required)]
+pub struct IsoCurveParams {
+ // Optional in the type and required in the schema, as `curves` above.
+ /// A point [x, y, z] in mm on the face: the curve passes through it.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "IsoFacePoint")]
+ pub face: Option<IsoFacePoint>,
+ /// The face's body. Default: any body the point is on. Text only; anything else is read as
+ /// left out.
+ #[serde(default)]
+ pub body: Option<String>,
+ /// Which way the curve runs: u or v, or a direction [x, y, z]. Default: u.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "IsoDirection")]
+ pub direction: Option<IsoDirection>,
+}
+
+fn face_required(schema: &mut Schema) {
+ require(schema, "face");
+}
+
+/// Fit lines and arcs to the section of a mesh or solid body with the sketch plane, and add them
+/// to the active sketch as normal (unlinked) geometry. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = body_required)]
+pub struct FitCurvesParams {
+ // Optional in the type and required in the schema, as `curves` above.
+ /// The body to cut with the sketch plane.
+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BodyName")]
+ pub body: Option<BodyName>,
+}
+
+fn body_required(schema: &mut Schema) {
+ require(schema, "body");
+}
+
+/// `sketch.break_link`'s `entities`: one id or a list of ids, as `params::string_list` reads them.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct EntityIds(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for EntityIds {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ match params::string_list("", &json!({"entities": v}), "entities") {
+ Ok(ids) => Ok(EntityIds(ids)),
+ Err(crate::EngineError::BadParams { msg, .. }) => Err(D::Error::custom(whole(msg))),
+ Err(other) => Err(D::Error::custom(whole(other))),
+ }
+ }
+}
+
+impl JsonSchema for EntityIds {
+ fn schema_name() -> Cow<'static, str> {
+ "EntityIds".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The id of a curve or point, or a list of ids (at most 10000).",
+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}]
+ })
+ }
+}
+
+/// Turn linked sketch geometry into normal sketch geometry, by its link or by any of its curves
+/// and points. Give `link` or `entities`. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = link_or_entities)]
+pub struct SketchBreakLinkParams {
+ /// A link's id (`j1`). Text only; anything else is read as left out.
+ #[serde(default)]
+ pub link: Option<String>,
+ /// The ids of linked curves or points: each one's whole link is broken. Default: none.
+ #[serde(default)]
+ pub entities: Option<EntityIds>,
+}
+
+/// The handler refuses a call with neither key (or an empty list), with its own message.
+fn link_or_entities(schema: &mut Schema) {
+ schema.insert("anyOf".into(), json!([{"required": ["link"]}, {"required": ["entities"]}]));
+}
+
+/// Choose whether a sketch created on a face projects that face's edges into it at once, or
+/// toggle the choice. A setting the session keeps: not an undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct AutoProjectParams {
+ /// True to project, false not to. Default: the opposite of what it is now. Anything but true
+ /// or false is read as left out.
+ #[serde(default)]
+ pub value: Option<bool>,
+}
+
+/// One link a projection made, and what it brought into the sketch.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ProjectedLink {
+ /// The link's id (`j1`); null when `projection_link` was false: the geometry is normal sketch
+ /// geometry then.
+ pub link: Option<String>,
+ /// The ids of the curves it made.
+ pub curves: Vec<String>,
+ /// The ids of the points it made.
+ pub points: Vec<String>,
+}
+
+/// What `sketch.project`, `sketch.intersect` and `sketch.include_3d` return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ProjectResult {
+ /// One entry for each reference that added something, in order.
+ pub links: Vec<ProjectedLink>,
+ /// What was left out because the sketch shows it already (`sketch.project` only).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub already_projected: Vec<String>,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// The link one command made: what `sketch.intersection_curve`, `sketch.spun_profile` and
+/// `sketch.isoparametric_curve` return, and each of the `links` of `sketch.project_to_surface`.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LinkMade {
+ /// The link's id (`j1`).
+ pub link: String,
+ /// The ids of the curves it made.
+ pub curves: Vec<String>,
+ /// The ids of the points it made.
+ pub points: Vec<String>,
+ /// The ids of the wires it made.
+ pub wires: Vec<String>,
+}
+
+/// What `sketch.intersection_curve`, `sketch.spun_profile` and `sketch.isoparametric_curve`
+/// return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchLinkResult {
+ #[serde(flatten)]
+ pub made: LinkMade,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.project_to_surface` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ProjectToSurfaceResult {
+ /// One link for each curve, in order.
+ pub links: Vec<LinkMade>,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.fit_curves_to_section` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct FitSectionResult {
+ /// The ids of the curves added.
+ pub curves: Vec<String>,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.break_link` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchBreakLinkResult {
+ /// The ids of the links that were broken.
+ pub broken: Vec<String>,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.auto_project` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct AutoProjectResult {
+ /// Whether a sketch created on a face projects its edges now.
+ pub auto_project: bool,
+ /// What the command added to the sketch, as every sketch command reports it (the engine adds
+ /// it): `{points, curves, constraints, dimensions}`, and `wires` when there are any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "sketch_project_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/sketch_project_tests.rs b/crates/engine/src/schema/sketch_project_tests.rs
new file mode 100644
index 0000000000..a7cf8ebe9f
--- /dev/null
+++ b/crates/engine/src/schema/sketch_project_tests.rs
@@ -0,0 +1,514 @@
+use serde_json::{Value, json};
+
+use super::{
+ AutoProjectParams, AutoProjectResult, FitCurvesParams, FitSectionResult, Include3dParams, IntersectParams, IntersectionCurveParams,
+ IsoCurveParams, ProjectParams, ProjectRef, ProjectResult, ProjectToSurfaceParams, ProjectToSurfaceResult, SketchBreakLinkParams,
+ SketchBreakLinkResult, SketchLinkResult, SpunProfileParams,
+};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
+
+/// A box and a tall cylinder through it (two bodies), a finished sketch `Src` with a line `source`,
+/// and a sketch being edited, on the XY plane at height 5.
+fn scene(level: ParamCheck) -> Session {
+ scene_on(level, "XY")
+}
+
+/// [`scene`] with the sketch being edited on `plane`.
+fn scene_on(level: ParamCheck, plane: &str) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ for (id, p) in [
+ ("solid.box", json!({"corner": [0, 0, 0], "length": 20, "width": 20, "height": 10, "body_name": "Block"})),
+ ("solid.cylinder", json!({"base": [10, 10, -5], "radius": 4, "height": 30, "operation": "new", "body_name": "Pin"})),
+ ("sketch.create", json!({"plane": "XY", "offset": 20, "name": "Src"})),
+ ("sketch.line", json!({"points": [[2, 2], [18, 2]], "ids": ["source"]})),
+ ("sketch.line", json!({"points": [[2, 4], [18, 8]], "ids": ["other"]})),
+ ("sketch.finish", json!({})),
+ ("sketch.create", json!({"plane": plane, "offset": 5})),
+ ] {
+ if let Err(e) = s.execute(id, &p) {
+ panic!("{id} {p}: {e}");
+ }
+ }
+ s
+}
+
+fn error(level: ParamCheck, id: &str, p: &Value) -> Option<String> {
+ scene(level).execute(id, p).err().map(|e| e.to_string())
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<ProjectParams>(), &["projection_link", "ref", "refs"]);
+ assert_keys(input_schema_for::<IntersectParams>(), &["projection_link", "ref", "refs"]);
+ assert_keys(input_schema_for::<Include3dParams>(), &["ref", "refs"]);
+ assert_keys(input_schema_for::<ProjectToSurfaceParams>(), &["body", "curves", "face"]);
+ assert_keys(input_schema_for::<IntersectionCurveParams>(), &["a", "b"]);
+ assert_keys(input_schema_for::<SpunProfileParams>(), &["axis", "body"]);
+ assert_keys(input_schema_for::<IsoCurveParams>(), &["body", "direction", "face"]);
+ assert_keys(input_schema_for::<FitCurvesParams>(), &["body"]);
+ assert_keys(input_schema_for::<SketchBreakLinkParams>(), &["entities", "link"]);
+ assert_keys(input_schema_for::<AutoProjectParams>(), &["value"]);
+}
+
+/// Strict gives the handlers' messages for the calls they refuse for a key. These fail before the
+/// handler looks at the sketch being edited, so they hold with none open.
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("sketch.project", json!({})),
+ ("sketch.project", json!({"refs": []})),
+ ("sketch.project", json!({"ref": []})),
+ ("sketch.project", json!({"refs": [], "ref": "origin"})),
+ ("sketch.project", json!({"projection_link": "no", "refs": ["origin"]})),
+ ("sketch.project", json!({"projection_link": null, "refs": ["origin"]})),
+ ("sketch.project", json!({"projection_link": 1})),
+ ("sketch.intersect", json!({})),
+ ("sketch.intersect", json!({"refs": []})),
+ ("sketch.intersect", json!({"projection_link": "no", "refs": [{"body": "Block"}]})),
+ ("sketch.include_3d", json!({})),
+ ("sketch.include_3d", json!({"refs": []})),
+ ("sketch.project_to_surface", json!({})),
+ ("sketch.project_to_surface", json!({"face": [1, 2]})),
+ ("sketch.project_to_surface", json!({"face": null})),
+ ("sketch.project_to_surface", json!({"face": "top"})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3]})),
+ ("sketch.spun_profile", json!({})),
+ ("sketch.spun_profile", json!({"body": 5, "axis": "Z"})),
+ ("sketch.spun_profile", json!({"body": null})),
+ ("sketch.spun_profile", json!({"body": "Block"})),
+ ("sketch.spun_profile", json!({"body": "Block", "axis": 3})),
+ ("sketch.spun_profile", json!({"body": "Block", "axis": null})),
+ ("sketch.isoparametric_curve", json!({})),
+ ("sketch.isoparametric_curve", json!({"face": [1, 2]})),
+ ("sketch.isoparametric_curve", json!({"face": {"x": 1, "y": 2}})),
+ ("sketch.fit_curves_to_section", json!({})),
+ ("sketch.fit_curves_to_section", json!({"body": 7})),
+ ("sketch.fit_curves_to_section", json!({"body": null})),
+ ("sketch.fit_curves_to_section", json!({"body": ["Block"]})),
+ ]);
+}
+
+/// The same for the calls that fail only once the handler has a sketch to work in: what it
+/// refuses in a reference or a list, with the sketch being edited open.
+#[test]
+fn strict_keeps_todays_errors_in_a_sketch() {
+ let cases = [
+ ("sketch.project", json!({"refs": null})),
+ ("sketch.project", json!({"refs": [true]})),
+ ("sketch.project", json!({"refs": [5]})),
+ ("sketch.project", json!({"refs": [null]})),
+ ("sketch.project", json!({"refs": [[1, 2, 3]]})),
+ ("sketch.project", json!({"refs": [{}]})),
+ ("sketch.project", json!({"refs": [{"edge": [1, 2]}]})),
+ ("sketch.project", json!({"refs": [{"edge": "x"}, {"plane": 3}]})),
+ ("sketch.project", json!({"refs": ["origin", {"sketch": [1], "curve": "source"}]})),
+ ("sketch.project", json!({"refs": [{"sketch": true}]})),
+ ("sketch.project", json!({"refs": [{"sketch": "Src"}]})),
+ ("sketch.project", json!({"refs": [{"sketch": "Src", "curve": 4}]})),
+ ("sketch.project", json!({"ref": {"axis": 5}})),
+ ("sketch.project", json!({"ref": 5})),
+ ("sketch.intersect", json!({"refs": [{"vertex": [1, 2]}]})),
+ ("sketch.intersect", json!({"ref": {"sketch": "Src", "point": 1}})),
+ ("sketch.include_3d", json!({"refs": [1.5]})),
+ ("sketch.include_3d", json!({"refs": {"colour": "red"}})),
+ ("sketch.include_3d", json!({"refs": null})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": 5})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": null})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": {"sketch": "Src", "curve": "source"}})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": []})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": vec![json!({"sketch": "Src", "curve": "source"}); 501]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"edge": [1, 2, 3]}]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"sketch": "Src", "point": "p1"}]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"body": "Block"}]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": ["origin"]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"origin": true}]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"nothing": 1}]})),
+ ("sketch.project_to_surface", json!({"face": [1, 2, 3], "curves": [{"sketch": "Src"}]})),
+ ("sketch.intersection_curve", json!({})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": null, "b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": 5, "b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"nothing": 1}})),
+ ("sketch.intersection_curve", json!({"a": "origin", "b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": "x"})),
+ ("sketch.intersection_curve", json!({"a": {"edge": [1, 2, 3]}, "b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"vertex": [1, 2, 3]}})),
+ ("sketch.intersection_curve", json!({"a": {"plane": "XY"}, "b": {"body": "Block"}})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"sketch": "Src", "point": "p1"}})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"sketch": "Src"}})),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": null})),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": "w"})),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": [1, 2]})),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "direction": 3})),
+ ("sketch.break_link", json!({})),
+ ("sketch.break_link", json!({"entities": []})),
+ ("sketch.break_link", json!({"entities": 5})),
+ ("sketch.break_link", json!({"entities": [1]})),
+ ("sketch.break_link", json!({"entities": ["a", true]})),
+ ("sketch.break_link", json!({"entities": {"a": 1}})),
+ ("sketch.break_link", json!({"link": "j9"})),
+ ];
+ for (id, p) in cases {
+ let off = error(ParamCheck::Off, id, &p);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict, id, &p), off, "{id} {p}");
+ }
+}
+
+/// Strict says the same wherever the handler's message comes from the contract's reading: every
+/// shape of reference is read by the type as the handler reads it, so the contract refuses it
+/// exactly when the handler does for its form (a sketch that exists and is another sketch's).
+#[test]
+fn the_reference_type_reads_like_the_handler() {
+ let forms = [
+ json!("origin"),
+ json!("ORIGIN"),
+ json!("x"),
+ json!("Z"),
+ json!("Block"),
+ json!("nothing"),
+ json!({"edge": [10, 0, 5]}),
+ json!({"edge": {"x": 10, "y": 0, "z": 5}, "body": "Block"}),
+ json!({"edge": "bad", "body": "Block"}),
+ json!({"edge": [1, 2], "face": [10, 10, 10]}),
+ json!({"edge": [1, 2, 3, 4]}),
+ json!({"face": [10, 10, 10], "body": 4}),
+ json!({"vertex": [0, 0, 10]}),
+ json!({"vertex": [1e9, 0, 0]}),
+ json!({"sketch": "Src", "curve": "source"}),
+ json!({"sketch": "Src", "point": "p1"}),
+ json!({"sketch": "Src", "curve": "source", "point": "p1"}),
+ json!({"sketch": "Src", "curve": 7, "point": "p1"}),
+ json!({"sketch": "Src"}),
+ json!({"sketch": "Src", "curve": null}),
+ json!({"sketch": 1.5}),
+ json!({"sketch": true}),
+ json!({"sketch": null}),
+ json!({"sketch": ["Src"]}),
+ json!({"sketch": {"name": "Src"}, "body": "Block"}),
+ json!({"body": "Block"}),
+ json!({"body": 5}),
+ json!({"body": "Block", "axis": "Z"}),
+ json!({"axis": "X"}),
+ json!({"axis": "x"}),
+ json!({"axis": 5}),
+ json!({"plane": "XY"}),
+ json!({"plane": null}),
+ json!({"origin": null}),
+ json!({"origin": [0, 0, 0]}),
+ json!({}),
+ json!([]),
+ json!(null),
+ json!(true),
+ json!(5),
+ json!({"nothing": 1}),
+ ];
+ for form in forms {
+ let issues = issues("sketch.include_3d", &json!({"refs": [form]}));
+ let off = error(ParamCheck::Off, "sketch.include_3d", &json!({"refs": [form]}));
+ let strict = error(ParamCheck::Strict, "sketch.include_3d", &json!({"refs": [form]}));
+ let typed = serde_json::from_value::<ProjectRef>(form.clone());
+ // The type, the check and the handler agree on what is refused for its form.
+ assert_eq!(typed.is_err(), !issues.is_empty(), "{form}");
+ if typed.is_err() {
+ assert_eq!(strict, off, "{form}");
+ } else {
+ let message = off.unwrap_or_default();
+ // What the handler refuses of a form the type accepts needs the design.
+ for shape in ["cannot project", "`sketch` must be", "`refs` is empty"] {
+ assert!(!message.contains(shape), "{form}: {message}");
+ }
+ }
+ }
+ // A single reference is read as a list of one, and `ref` is read only without `refs`.
+ let count = |p: Value| issues("sketch.project", &p).len();
+ assert_eq!(count(json!({"refs": "origin"})), 0);
+ assert_eq!(count(json!({"refs": {"origin": 1}})), 0);
+ assert_eq!(count(json!({"ref": "origin"})), 0);
+ assert_eq!(count(json!({"refs": ["origin"], "ref": 5})), 0, "`ref` is not read when `refs` is given");
+ assert_eq!(count(json!({"refs": null, "ref": "origin"})), 1, "`refs` is read even when null");
+ assert_eq!(count(json!({"ref": 5})), 1);
+ assert_eq!(count(json!({"refs": []})), 1);
+ assert_eq!(count(json!({"refs": [], "ref": "origin"})), 1);
+ // Only the first 1000 references are read.
+ let mut many = vec![json!("origin"); 1000];
+ many.push(json!(5));
+ assert_eq!(count(json!({"refs": many})), 0);
+ many.insert(0, json!(5));
+ assert_eq!(count(json!({"refs": many})), 1);
+ // `include_3d` takes no `projection_link`: the handler never reads it, so strict names it.
+ assert_eq!(issues("sketch.include_3d", &json!({"refs": ["origin"], "projection_link": false})).len(), 1);
+ assert_eq!(issues("sketch.project", &json!({"refs": ["origin"], "projection_link": false})).len(), 0);
+}
+
+/// What the contracts take and refuse in the schemas as well as the types.
+#[test]
+fn the_schemas_take_what_the_handlers_read() {
+ let check = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value().clone();
+ for (p, takes) in cases {
+ assert_eq!(conforms(&schema, &schema, p), *takes, "{p}");
+ }
+ };
+ for schema in [input_schema_for::<ProjectParams>(), input_schema_for::<IntersectParams>()] {
+ check(
+ schema,
+ &[
+ (json!({"refs": [{"edge": [1, 2, 3], "body": "Block"}, {"face": [1, 2, 3]}, "origin", {"axis": "X"}]}), true),
+ (json!({"refs": {"sketch": 2, "curve": "c1"}, "projection_link": false}), true),
+ (json!({"ref": {"body": "Block"}}), true),
+ (json!({"refs": [{"sketch": "Src", "point": "p1"}, {"plane": "XY"}, {"vertex": {"x": 1, "y": 2, "z": 3}}]}), true),
+ (json!({}), false),
+ (json!({"projection_link": true}), false),
+ (json!({"refs": []}), false),
+ (json!({"refs": [{"edge": [1, 2]}]}), false),
+ (json!({"refs": ["origin"], "projection_link": "yes"}), false),
+ (json!({"refs": ["origin"], "projection_lnk": true}), false),
+ ],
+ );
+ }
+ check(
+ input_schema_for::<Include3dParams>(),
+ &[(json!({"refs": ["origin"]}), true), (json!({"refs": ["origin"], "projection_link": true}), false)],
+ );
+ check(
+ input_schema_for::<ProjectToSurfaceParams>(),
+ &[
+ (json!({"face": [0, 0, 20], "curves": [{"sketch": 4, "curve": "source"}]}), true),
+ (json!({"face": [0, 0, 20], "curves": [{"sketch": "Src", "curve": "source"}], "body": "Block"}), true),
+ (json!({"face": [0, 0, 20]}), false),
+ (json!({"curves": [{"sketch": 4, "curve": "source"}]}), false),
+ (json!({"face": [0, 0, 20], "curves": []}), false),
+ (json!({"face": [0, 0, 20], "curves": [{"sketch": 4}]}), false),
+ ],
+ );
+ check(
+ input_schema_for::<IntersectionCurveParams>(),
+ &[
+ (json!({"a": {"body": "Block"}, "b": {"face": [1, 2, 3], "body": "Pin"}}), true),
+ (json!({"a": {"sketch": "Src", "curve": "source"}, "b": "Pin"}), true),
+ (json!({"a": {"body": "Block"}}), false),
+ (json!({"a": {"body": "Block"}, "b": {"edge": [1, 2, 3]}}), false),
+ ],
+ );
+ check(
+ input_schema_for::<SpunProfileParams>(),
+ &[
+ (json!({"body": "Pin", "axis": "Z"}), true),
+ (json!({"body": "Pin"}), false),
+ (json!({"axis": "Z"}), false),
+ (json!({"body": 1, "axis": "Z"}), false),
+ ],
+ );
+ check(
+ input_schema_for::<IsoCurveParams>(),
+ &[
+ (json!({"face": [1, 2, 3]}), true),
+ (json!({"face": [1, 2, 3], "body": "Block", "direction": "v"}), true),
+ (json!({"face": [1, 2, 3], "direction": [0, 1, 0]}), true),
+ (json!({"direction": "u"}), false),
+ (json!({"face": [1, 2, 3], "direction": "w"}), false),
+ ],
+ );
+ check(input_schema_for::<FitCurvesParams>(), &[(json!({"body": "Pin"}), true), (json!({}), false)]);
+ check(
+ input_schema_for::<SketchBreakLinkParams>(),
+ &[
+ (json!({"link": "j1"}), true),
+ (json!({"entities": "c1"}), true),
+ (json!({"entities": ["c1", "p2"], "link": "j1"}), true),
+ (json!({}), false),
+ (json!({"entities": [1]}), false),
+ ],
+ );
+ check(input_schema_for::<AutoProjectParams>(), &[(json!({}), true), (json!({"value": false}), true), (json!({"value": "no"}), false)]);
+}
+
+/// Every command replies as its output schema says, in Warn without warnings, and in the same JSON
+/// as with the check off.
+#[test]
+fn replies_match_the_output_schema() {
+ fn matches(schema: schemars::Schema, r: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+ }
+ let calls: Vec<(&str, Value, fn() -> schemars::Schema)> = vec![
+ ("sketch.project", json!({"refs": [{"edge": [10, 0, 10]}]}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"refs": [{"vertex": [0, 0, 10]}, {"face": [10, 10, 10], "body": "Block"}]}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"refs": {"edge": [20, 10, 10], "body": "Block"}, "projection_link": true}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"ref": {"edge": [10, 20, 10]}, "projection_link": false}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"refs": ["origin"]}), output_schema_for::<ProjectResult>),
+ (
+ "sketch.project",
+ json!({"refs": [{"axis": "X"}, {"plane": "XZ"}, {"sketch": "Src", "curve": "source"}]}),
+ output_schema_for::<ProjectResult>,
+ ),
+ ("sketch.project", json!({"refs": [{"sketch": "Src", "point": "source.start"}]}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"refs": [{"edge": "bad", "body": "Pin"}]}), output_schema_for::<ProjectResult>),
+ ("sketch.project", json!({"refs": ["Pin"], "ref": 5}), output_schema_for::<ProjectResult>),
+ ("sketch.intersect", json!({"refs": [{"body": "Block"}]}), output_schema_for::<ProjectResult>),
+ ("sketch.intersect", json!({"refs": {"face": [0, 10, 5], "body": "Block"}, "projection_link": false}), output_schema_for::<ProjectResult>),
+ ("sketch.intersect", json!({"ref": {"edge": [0, 0, 5]}}), output_schema_for::<ProjectResult>),
+ ("sketch.include_3d", json!({"refs": [{"edge": [20, 10, 10]}]}), output_schema_for::<ProjectResult>),
+ ("sketch.include_3d", json!({"ref": {"vertex": [0, 0, 10]}}), output_schema_for::<ProjectResult>),
+ (
+ "sketch.project_to_surface",
+ json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}, {"sketch": "Src", "curve": "other"}]}),
+ output_schema_for::<ProjectToSurfaceResult>,
+ ),
+ (
+ "sketch.project_to_surface",
+ json!({"face": {"x": 10, "y": 10, "z": 10}, "body": "Block", "curves": [{"sketch": 3, "curve": "source"}]}),
+ output_schema_for::<ProjectToSurfaceResult>,
+ ),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"body": "Pin"}}), output_schema_for::<SketchLinkResult>),
+ ("sketch.intersection_curve", json!({"a": {"face": [10, 10, 10], "body": "Block"}, "b": "Pin"}), output_schema_for::<SketchLinkResult>),
+ (
+ "sketch.intersection_curve",
+ json!({"a": {"sketch": "Src", "curve": "source"}, "b": {"body": "Block"}}),
+ output_schema_for::<SketchLinkResult>,
+ ),
+ ("sketch.spun_profile", json!({"body": "Pin", "axis": "Z"}), output_schema_for::<SketchLinkResult>),
+ ("sketch.spun_profile", json!({"body": "Pin", "axis": "x"}), output_schema_for::<SketchLinkResult>),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10]}), output_schema_for::<SketchLinkResult>),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": "Block", "direction": "V"}), output_schema_for::<SketchLinkResult>),
+ ("sketch.isoparametric_curve", json!({"face": {"x": 10, "y": 10, "z": 10}, "direction": [1, 0, 0]}), output_schema_for::<SketchLinkResult>),
+ ("sketch.fit_curves_to_section", json!({"body": "Block"}), output_schema_for::<FitSectionResult>),
+ ("sketch.auto_project", json!({}), output_schema_for::<AutoProjectResult>),
+ ("sketch.auto_project", json!({"value": true}), output_schema_for::<AutoProjectResult>),
+ ];
+ for (id, p, output) in calls {
+ // The spun profile needs a plane the cylinder's axis lies in.
+ let plane = if id == "sketch.spun_profile" { "XZ" } else { "XY" };
+ let a = scene_on(ParamCheck::Off, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let b = scene_on(ParamCheck::Warn, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ assert!(b.get("param_warnings").is_none(), "{id} {p}: {b}");
+ assert_eq!(a, b, "{id} {p}");
+ matches(output(), &b);
+ }
+ let run = |p: Value| scene(ParamCheck::Warn).execute("sketch.project", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ // The shapes a caller sees: the link, its curves and points; null where the link is not kept.
+ let r = run(json!({"refs": [{"edge": [10, 0, 10]}]}));
+ assert_eq!(r["links"].as_array().map(Vec::len), Some(1), "{r}");
+ let l = &r["links"][0];
+ assert!(l["link"].is_string() && l["curves"].is_array() && l["points"].is_array(), "{r}");
+ assert_eq!(l.as_object().map(|o| o.len()), Some(3), "{r}");
+ assert!(r.get("already_projected").is_none(), "no `already_projected` when all was projected: {r}");
+ assert!(r["created"]["curves"].is_array(), "the engine reports what a sketch command created: {r}");
+ let r = run(json!({"refs": [{"edge": [10, 0, 10]}], "projection_link": false}));
+ assert!(r["links"][0]["link"].is_null() && r["links"][0]["curves"][0].is_string(), "{r}");
+ matches(output_schema_for::<ProjectResult>(), &r);
+ // Projecting what the sketch shows already says so, and the reply still matches.
+ let mut s = scene(ParamCheck::Warn);
+ s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}]})).unwrap_or_default();
+ let r = s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}, {"edge": [10, 20, 10]}]})).unwrap_or_default();
+ assert_eq!(r["already_projected"].as_array().map(Vec::len), Some(1), "{r}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ matches(output_schema_for::<ProjectResult>(), &r);
+ // A `value` that is not true or false is read as left out, and the check says so.
+ let r = scene(ParamCheck::Warn).execute("sketch.auto_project", &json!({"value": "maybe"})).unwrap_or_default();
+ assert_eq!(r["param_warnings"], json!(["`value` must be true or false"]), "{r}");
+ matches(output_schema_for::<AutoProjectResult>(), &r);
+ // The shape of the others.
+ let mut s = scene(ParamCheck::Warn);
+ let r = s.execute("sketch.isoparametric_curve", &json!({"face": [10, 10, 10]})).unwrap_or_default();
+ let mut keys: Vec<_> = r.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
+ keys.sort();
+ assert_eq!(keys, ["created", "curves", "link", "points", "wires"], "{r}");
+ let r = s.execute("sketch.auto_project", &json!({"value": true})).unwrap_or_default();
+ assert_eq!(r["auto_project"], json!(true));
+ let r = s.execute("sketch.auto_project", &json!({})).unwrap_or_default();
+ assert_eq!(r["auto_project"], json!(false), "no value toggles");
+ let r = s.execute("sketch.fit_curves_to_section", &json!({"body": "Block"})).unwrap_or_default();
+ assert!(r["curves"].is_array(), "{r}");
+}
+
+/// Breaking links: by `link`, by `entities` of both kinds (a curve, a point), and with both.
+#[test]
+fn break_link_replies_without_warnings() {
+ let mut s = scene(ParamCheck::Warn);
+ let linked = |s: &mut Session, p: Value| {
+ let r = s.execute("sketch.project", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ let l = &r["links"][0];
+ let text = |v: &Value| v.as_str().unwrap_or_default().to_string();
+ (text(&l["link"]), text(&l["curves"][0]), text(&l["points"][0]))
+ };
+ let (l1, _, _) = linked(&mut s, json!({"refs": [{"edge": [10, 0, 10]}]}));
+ let (_, c2, _) = linked(&mut s, json!({"refs": [{"edge": [10, 20, 10]}]}));
+ let (l3, _, _) = linked(&mut s, json!({"refs": [{"edge": [20, 10, 10]}]}));
+ let (_, _, p4) = linked(&mut s, json!({"refs": [{"vertex": [0, 0, 10]}]}));
+ assert!(!c2.is_empty() && !p4.is_empty());
+ let schema = output_schema_for::<SketchBreakLinkResult>();
+ for p in [json!({"link": l1}), json!({"entities": c2}), json!({"entities": [p4], "link": l3})] {
+ let r = s.execute("sketch.break_link", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+ assert_eq!(r["broken"].as_array().map(Vec::len), Some(p.as_object().map_or(0, |o| o.len())), "{p}: {r}");
+ }
+}
+
+/// A key spelt wrong runs in warn and says so (the reply still matches), and strict refuses it.
+#[test]
+fn a_misspelt_key_is_reported_in_warn_and_refused_in_strict() {
+ let cases = [
+ ("sketch.project", json!({"refs": ["origin"], "projection_lnk": false})),
+ ("sketch.intersect", json!({"refs": [{"body": "Block"}], "projectionlink": false})),
+ ("sketch.include_3d", json!({"refs": [{"edge": [20, 10, 10]}], "projection_link": false})),
+ ("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "bdy": "Block"})),
+ ("sketch.intersection_curve", json!({"a": {"body": "Block"}, "b": {"body": "Pin"}, "c": 1})),
+ ("sketch.spun_profile", json!({"body": "Pin", "axis": "Z", "axes": "Y"})),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "directon": "v"})),
+ ("sketch.fit_curves_to_section", json!({"body": "Block", "bodies": []})),
+ ("sketch.auto_project", json!({"vlaue": false})),
+ ];
+ for (id, p) in cases {
+ let plane = if id == "sketch.spun_profile" { "XZ" } else { "XY" };
+ let r = scene_on(ParamCheck::Warn, plane).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let warnings = r["param_warnings"].as_array().unwrap_or_else(|| panic!("{id} {p}: {r}"));
+ assert_eq!(warnings.len(), 1, "{id} {p}: {r}");
+ assert!(warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {r}");
+ let error = error(ParamCheck::Strict, id, &p).unwrap_or_default();
+ assert!(error.contains("unknown key"), "{id}: {error}");
+ }
+ let r = scene(ParamCheck::Warn).execute("sketch.auto_project", &json!({"vlaue": false})).unwrap_or_default();
+ assert_eq!(r["param_warnings"], json!(["unknown key `vlaue`"]), "{r}");
+ // The reply with its warnings still matches its schema.
+ let schema = output_schema_for::<AutoProjectResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+}
+
+/// Wrong-typed values the handlers read as left out: the typed field names them in warn (and
+/// strict refuses), `null` is left out and gets no warning, and the reply is the same as with the
+/// check off.
+#[test]
+fn values_read_as_left_out_are_reported_but_change_nothing() {
+ let cases = [
+ ("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "body": 5}), true),
+ ("sketch.project_to_surface", json!({"face": [10, 10, 10], "curves": [{"sketch": "Src", "curve": "source"}], "body": null}), false),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": 5}), true),
+ ("sketch.isoparametric_curve", json!({"face": [10, 10, 10], "body": null}), false),
+ ("sketch.auto_project", json!({"value": null}), false),
+ ("sketch.auto_project", json!({"value": 1}), true),
+ ];
+ for (id, p, warns) in cases {
+ let off = scene(ParamCheck::Off).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let mut warn = scene(ParamCheck::Warn).execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ assert_eq!(warn.get("param_warnings").is_some(), warns, "{id} {p}: {warn}");
+ if let Some(o) = warn.as_object_mut() {
+ o.remove("param_warnings");
+ }
+ assert_eq!(off, warn, "{id} {p}");
+ }
+ // break_link: `link` of the wrong type is left out, so `entities` alone does the work.
+ let mut s = scene(ParamCheck::Warn);
+ let r = s.execute("sketch.project", &json!({"refs": [{"edge": [10, 0, 10]}]})).unwrap_or_default();
+ let curve = r["links"][0]["curves"][0].clone();
+ let r = s.execute("sketch.break_link", &json!({"link": 5, "entities": [curve]})).unwrap_or_default();
+ assert_eq!(r["broken"].as_array().map(Vec::len), Some(1), "{r}");
+ assert_eq!(r["param_warnings"].as_array().map(Vec::len), Some(1), "{r}");
+ let r = scene(ParamCheck::Warn).execute("sketch.break_link", &json!({"link": null}));
+ assert!(r.is_err(), "nothing to break");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 31a4267a4e..2f12c27809 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -58,8 +58,6 @@ sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern
sheet.path_flange
-sketch.auto_project
-sketch.break_link
sketch.chain
sketch.construction
sketch.create
@@ -70,20 +68,13 @@ sketch.drag
sketch.drag_end
sketch.draw.dimensioned
sketch.export_dxf
-sketch.fit_curves_to_section
-sketch.include_3d
sketch.insert_dxf
sketch.insert_svg
-sketch.intersect
-sketch.intersection_curve
-sketch.isoparametric_curve
sketch.move_point
sketch.options
sketch.polygon.circumscribed
sketch.polygon.edge
sketch.polygon.inscribed
-sketch.project
-sketch.project_to_surface
sketch.rectangle.center
sketch.rectangle.rounded
sketch.rectangle.three_point
@@ -91,7 +82,6 @@ sketch.rectangle.two_point
sketch.slot.center_to_center
sketch.slot.overall
sketch.solve
-sketch.spun_profile
solid.align
solid.chamfer
solid.coil