SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: the 3D sketch commands describe their exact parameters and reply (#12507) (#12600)
PeppaWutz1f29f432eeab
diff --git a/crates/engine/src/cmd/sketch_3d.rs b/crates/engine/src/cmd/sketch_3d.rsindex 3658001592..3fe59d235f 100644--- a/crates/engine/src/cmd/sketch_3d.rs+++ b/crates/engine/src/cmd/sketch_3d.rs@@ -11,16 +11,30 @@ use super::sketch::edit;use super::sketch_store;use super::{CommandSpec, in_sketch};use crate::params::{bad, req_vec3, vec3};+use crate::schema::sketch_3d::{Curves3dResult, Line3dParams, Move3dParams, Move3dResult, Point3dParams, Point3dResult, Spline3dParams};+use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};+const LINE3D_CONTRACT: TypedContract<Line3dParams> = TypedContract::new();+const SPLINE3D_CONTRACT: TypedContract<Spline3dParams> = TypedContract::new();+const POINT3D_CONTRACT: TypedContract<Point3dParams> = TypedContract::new();+const MOVE3D_CONTRACT: TypedContract<Move3dParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("sketch.line3d", "3D Line", line3d).icon("line").enabled(in_sketch_3d).params(concat!(- "points: [[x,y,z]…] world points (2 or more): one 3D line per segment, joined end to end (needs 3D Sketch on)",- created_doc!()- )),- CommandSpec::new("sketch.spline3d", "3D Spline", spline3d)+ CommandSpec::new("sketch.line3d", "3D Line", crate::checked!("sketch.line3d", line3d))+ .icon("line")+ .enabled(in_sketch_3d)+ .contract(&LINE3D_CONTRACT)+ .output(output_schema_for::<Curves3dResult>)+ .params(concat!(+ "points: [[x,y,z]…] world points (2 or more): one 3D line per segment, joined end to end (needs 3D Sketch on)",+ created_doc!()+ )),+ CommandSpec::new("sketch.spline3d", "3D Spline", crate::checked!("sketch.spline3d", spline3d)).icon("spline").enabled(in_sketch_3d)+ .contract(&SPLINE3D_CONTRACT)+ .output(output_schema_for::<Curves3dResult>).params(concat!("points: [[x,y,z]…] world fit points (2 or more): a smooth 3D curve through them (needs 3D Sketch on)", created_doc!())),CommandSpec::new("sketch.arc3d", "3D Arc", arc3d).icon("arc3")@@ -29,16 +43,26 @@ pub static COMMANDS: &[CommandSpec] = &["start, through, end: [x,y,z] world points: an exact circular arc through them, from start through through to end (needs 3D Sketch on). Stored exactly (centre, radius, angles), so path consumers can treat it as a true arc",created_doc!())),- CommandSpec::new("sketch.point3d", "3D Point", point3d)+ CommandSpec::new("sketch.point3d", "3D Point", crate::checked!("sketch.point3d", point3d)).icon("point").enabled(in_sketch_3d)+ .contract(&POINT3D_CONTRACT)+ .output(output_schema_for::<Point3dResult>).params(concat!("point: [x,y,z] world point (needs 3D Sketch on)", created_doc!())),- CommandSpec::new("sketch.move3d", "Move 3D Point", move3d)+ CommandSpec::new("sketch.move3d", "Move 3D Point", crate::checked!("sketch.move3d", move3d)).icon("sketch_move").enabled(in_sketch)+ .contract(&MOVE3D_CONTRACT)+ .output(output_schema_for::<Move3dResult>).params("wire: drawn 3D curve or point id, index?: fit point (default 0), to: [x,y,z] | by: [dx,dy,dz]; points joined to it move too"),];+/// A command's reply as JSON: built from the type its output schema describes, 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()))+}+fn points(cmd: &str, p: &Value, min: usize) -> Result<Vec<Vec3>> {let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must list [x,y,z] points"))?;if a.len() < min || a.len() > solidcraft_sketch::MAX_FIT_POINTS {@@ -106,7 +130,7 @@ fn line3d(s: &mut Session, p: &Value) -> Result<Value> {needs_3d(sk, cmd)?;pts.windows(2).map(|w| sk.add_drawn_wire_in(w, WireSpace::Component).map_err(Into::into)).collect::<Result<Vec<String>>>()})?;- Ok(json!({"curves": ids, "sketch": info}))+ reply(cmd, Curves3dResult { curves: ids, sketch: info, param_warnings: Vec::new() })}fn spline3d(s: &mut Session, p: &Value) -> Result<Value> {@@ -117,7 +141,7 @@ fn spline3d(s: &mut Session, p: &Value) -> Result<Value> {needs_3d(sk, cmd)?;Ok(sk.add_drawn_wire_in(&pts, WireSpace::Component)?)})?;- Ok(json!({"curves": [id], "sketch": info}))+ reply(cmd, Curves3dResult { curves: vec![id], sketch: info, param_warnings: Vec::new() })}fn arc3d(s: &mut Session, p: &Value) -> Result<Value> {@@ -145,7 +169,7 @@ fn point3d(s: &mut Session, p: &Value) -> Result<Value> {needs_3d(sk, cmd)?;Ok(sk.add_drawn_wire_in(&[at], WireSpace::Component)?)})?;- Ok(json!({"point": id, "sketch": info}))+ reply(cmd, Point3dResult { point: id, sketch: info, param_warnings: Vec::new() })}fn move3d(s: &mut Session, p: &Value) -> Result<Value> {@@ -183,7 +207,7 @@ fn move3d(s: &mut Session, p: &Value) -> Result<Value> {};Ok(sk.move_drawn_point(&wire, index, to)?)})?;- Ok(json!({"moved": n, "sketch": info}))+ reply(cmd, Move3dResult { moved: n, sketch: info, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex 8d5418f5f5..2df052d85e 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -104,6 +104,7 @@ pub mod section;pub mod sheet;pub mod silhouette;pub mod sketch;+pub mod sketch_3d;pub mod sketch_clipboard;pub mod sketch_constraints;pub mod sketch_create;diff --git a/crates/engine/src/schema/sketch_3d.rs b/crates/engine/src/schema/sketch_3d.rsnew file mode 100644index 0000000000..bdceb54331--- /dev/null+++ b/crates/engine/src/schema/sketch_3d.rs@@ -0,0 +1,289 @@+//! Contracts and result types for the commands in `cmd/sketch_3d.rs`: `sketch.line3d`,+//! `sketch.spline3d`, `sketch.point3d` and `sketch.move3d`.+//!+//! 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. Whether the sketch has 3D Sketch on, a wire+//! exists or a point is in range stays the handler's to check, as does `move3d` being given+//! neither `to` nor `by`. 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::{Value, json};+use solidcore_record::Vec3;++use super::check::whole;+use super::motion::require;+use super::sketch_ends::SketchTarget;+use super::types::Point3;+use crate::params;++/// Draw 3D lines through world points, one line per segment, joined end to end. Needs 3D Sketch+/// on for the sketch (`sketch.options` with `sketch_3d: true`). One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = points_required)]+pub struct Line3dParams {+ // Optional in the type and required in the schema (`points_required`): left out, the handler+ // refuses it with its own message, not the check's "is required".+ /// The world points [x, y, z] in mm, 2 to 500: one line per segment between neighbours.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "DrawnPoints")]+ pub points: Option<DrawnPoints>,+ /// The sketch to draw in: its feature id or its name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Draw a smooth 3D curve through world fit points. Needs 3D Sketch on for the sketch+/// (`sketch.options` with `sketch_3d: true`). One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = points_required)]+pub struct Spline3dParams {+ // Optional in the type and required in the schema, as `Line3dParams::points`.+ /// The world fit points [x, y, z] in mm, 2 to 500, which the curve passes through.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "DrawnPoints")]+ pub points: Option<DrawnPoints>,+ /// The sketch to draw in: its feature id or its name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Draw a 3D point at a world point. Needs 3D Sketch on for the sketch (`sketch.options` with+/// `sketch_3d: true`). One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = point_required)]+pub struct Point3dParams {+ // Optional in the type and required in the schema, as `Line3dParams::points`.+ /// The world point [x, y, z] in mm.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "WorldPoint")]+ pub point: Option<WorldPoint>,+ /// The sketch to draw in: its feature id or its name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Move one fit point of a drawn 3D curve or point, to a world point or by a world offset. The+/// points joined to it move too. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = move_required)]+pub struct Move3dParams {+ // Optional in the type and required in the schema, as `Line3dParams::points`.+ /// The drawn 3D curve or point to move, by id.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "WireId")]+ pub wire: Option<WireId>,+ /// Which fit point of the curve (0 is the first), below 500. Default: 0.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "FitIndex")]+ pub index: Option<FitIndex>,+ /// Where the fit point goes, as a world point [x, y, z] in mm. Wins over `by`. The schema+ /// requires `to` or `by`; the handler refuses a call with neither.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "MoveTarget")]+ pub to: Option<MoveTarget>,+ /// How far the fit point moves, as a world offset [dx, dy, dz] in mm. Used when `to` is not+ /// given.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "MoveTarget")]+ pub by: Option<MoveTarget>,+ /// The sketch the curve is in: its feature id or its name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// 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)+}++fn points_required(schema: &mut Schema) {+ require(schema, "points");+}++fn point_required(schema: &mut Schema) {+ require(schema, "point");+}++fn move_required(schema: &mut Schema) {+ require(schema, "wire");+ schema.insert("anyOf".into(), json!([{"required": ["to"]}, {"required": ["by"]}]));+}++/// The `points` of `sketch.line3d` and `sketch.spline3d`: a list of 2 to 500 points, as their+/// `points` reader takes it, with its messages.+#[derive(Clone, Debug, PartialEq)]+pub struct DrawnPoints(pub Vec<Vec3>);++impl<'de> Deserialize<'de> for DrawnPoints {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let max = solidcraft_sketch::MAX_FIT_POINTS;+ let Value::Array(a) = Value::deserialize(d)? else {+ return Err(D::Error::custom(whole("`points` must list [x,y,z] points")));+ };+ if a.len() < 2 || a.len() > max {+ return Err(D::Error::custom(whole(format!("`points` needs 2 to {max} points"))));+ }+ a.iter()+ .map(|v| params::vec3(v).ok_or_else(|| D::Error::custom(whole("a point must be [x, y, z]"))))+ .collect::<Result<_, _>>()+ .map(DrawnPoints)+ }+}++impl JsonSchema for DrawnPoints {+ fn schema_name() -> Cow<'static, str> {+ "DrawnPoints".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let point = generator.subschema_for::<Point3>();+ json_schema!({+ "description": "World points [x, y, z] in mm, 2 to 500.",+ "type": "array",+ "items": point,+ "minItems": 2,+ "maxItems": solidcraft_sketch::MAX_FIT_POINTS+ })+ }+}++/// The `point` of `sketch.point3d`: a [`Point3`], with the handler's message.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct WorldPoint(pub Vec3);++impl<'de> Deserialize<'de> for WorldPoint {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec3(&Value::deserialize(d)?).map(WorldPoint).ok_or_else(|| D::Error::custom("must be a point [x, y, z]"))+ }+}++impl JsonSchema for WorldPoint {+ fn schema_name() -> Cow<'static, str> {+ "WorldPoint".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<Point3>()+ }+}++/// The `to` and `by` of `sketch.move3d`: a [`Point3`], with the handler's message.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct MoveTarget(pub Vec3);++impl<'de> Deserialize<'de> for MoveTarget {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec3(&Value::deserialize(d)?).map(MoveTarget).ok_or_else(|| D::Error::custom("must be [x,y,z]"))+ }+}++impl JsonSchema for MoveTarget {+ fn schema_name() -> Cow<'static, str> {+ "MoveTarget".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<Point3>()+ }+}++/// The `wire` of `sketch.move3d`: text, as the handler reads it. Whether a drawn curve or point+/// has that id is the handler's to check.+#[derive(Clone, Debug, PartialEq)]+pub struct WireId(pub String);++impl<'de> Deserialize<'de> for WireId {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(s) => Ok(WireId(s)),+ _ => Err(D::Error::custom("must be a 3D curve or point id")),+ }+ }+}++impl JsonSchema for WireId {+ fn schema_name() -> Cow<'static, str> {+ "WireId".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type": "string"})+ }+}++/// The `index` of `sketch.move3d`: a whole number below 500, as the handler reads it.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct FitIndex(pub usize);++impl<'de> Deserialize<'de> for FitIndex {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Value::deserialize(d)?+ .as_u64()+ .and_then(|v| usize::try_from(v).ok())+ .filter(|v| *v < solidcraft_sketch::MAX_FIT_POINTS)+ .map(FitIndex)+ .ok_or_else(|| D::Error::custom("must be a fit point index below 500"))+ }+}++impl JsonSchema for FitIndex {+ fn schema_name() -> Cow<'static, str> {+ "FitIndex".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type": "integer", "minimum": 0, "maximum": solidcraft_sketch::MAX_FIT_POINTS - 1})+ }+}++/// What `sketch.line3d` and `sketch.spline3d` return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Curves3dResult {+ /// The ids of the curves drawn: one per segment for a line, one for a spline.+ pub curves: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: 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.point3d` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Point3dResult {+ /// The id of the point drawn.+ pub point: String,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: 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.move3d` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Move3dResult {+ /// How many fit points moved: the one asked for and the points joined to it.+ pub moved: usize,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: 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_3d_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/sketch_3d_tests.rs b/crates/engine/src/schema/sketch_3d_tests.rsnew file mode 100644index 0000000000..a0002a24c7--- /dev/null+++ b/crates/engine/src/schema/sketch_3d_tests.rs@@ -0,0 +1,241 @@+use serde_json::{Value, json};++use super::{Curves3dResult, Line3dParams, Move3dParams, Move3dResult, Point3dParams, Point3dResult, Spline3dParams};+use crate::Session;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<Line3dParams>(), &["points", "sketch"]);+ assert_keys(input_schema_for::<Spline3dParams>(), &["points", "sketch"]);+ assert_keys(input_schema_for::<Point3dParams>(), &["point", "sketch"]);+ assert_keys(input_schema_for::<Move3dParams>(), &["by", "index", "sketch", "to", "wire"]);+}++#[test]+fn strict_keeps_todays_errors() {+ let many: Vec<Value> = (0..501).map(|i| json!([i, 0, 0])).collect();+ assert_strict_keeps_todays_errors(&[+ ("sketch.line3d", json!({})),+ ("sketch.line3d", json!({"points": null})),+ ("sketch.line3d", json!({"points": "x"})),+ ("sketch.line3d", json!({"points": {"0": [0, 0, 0]}})),+ ("sketch.line3d", json!({"points": []})),+ ("sketch.line3d", json!({"points": [[0, 0, 0]]})),+ ("sketch.line3d", json!({"points": many})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1, 2]]})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], "a"]})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": true})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": -1})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": 1.5})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1]], "sketch": [1]})),+ ("sketch.spline3d", json!({})),+ ("sketch.spline3d", json!({"points": [[0, 0, 0]]})),+ ("sketch.spline3d", json!({"points": 5})),+ ("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1]]})),+ ("sketch.point3d", json!({})),+ ("sketch.point3d", json!({"point": null})),+ ("sketch.point3d", json!({"point": [1, 2]})),+ ("sketch.point3d", json!({"point": "1,2,3"})),+ ("sketch.point3d", json!({"point": [1, 2, 3], "sketch": {}})),+ ("sketch.move3d", json!({})),+ ("sketch.move3d", json!({"wire": 3, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": null, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "index": -1, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "index": 500, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "index": 1.5, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "index": "1", "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "index": null, "to": [0, 0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "to": [0, 0]})),+ ("sketch.move3d", json!({"wire": "w1", "to": null})),+ ("sketch.move3d", json!({"wire": "w1", "by": "up"})),+ ("sketch.move3d", json!({"wire": "w1", "by": null})),+ ("sketch.move3d", json!({"wire": "w1", "to": [0, 0, 0], "by": [1]})),+ ("sketch.move3d", json!({"wire": "w1", "to": [0, 0, 0], "sketch": true})),+ ]);+}++/// A session with a 3D sketch being edited, and the ids of a drawn line's curves.+fn three_d(level: ParamCheck) -> (Session, Vec<String>) {+ let mut s = Session { param_check: level, ..Session::default() };+ for (id, p) in [("sketch.create", json!({"plane": "XY", "name": "Path"})), ("sketch.options", json!({"sketch_3d": true}))] {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));+ }+ let drawn = s.execute("sketch.line3d", &json!({"points": [[0, 0, 0], [0, 0, 10], [10, 0, 10]]})).unwrap_or_else(|e| panic!("{e}"));+ let ids = drawn["curves"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(String::from)).collect();+ (s, ids)+}++/// Calls the handlers take today (every form of each key, `null` for `sketch`) get no issue from+/// the contracts; calls they refuse are refused by strict with the same message.+#[test]+fn the_types_read_each_key_as_the_handlers_do() {+ let (_, ids) = three_d(ParamCheck::Off);+ let wire = ids[0].clone();+ let cases = [+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]]})),+ ("sketch.line3d", json!({"points": [{"x": 0, "y": 0, "z": 0}, [1, 1, 1], [2, 2, 2]], "sketch": null})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": "Path"})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": 9999})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": "no such sketch"})),+ ("sketch.line3d", json!({"points": [[0, 0, 0], [1e9, 1, 1]]})),+ ("sketch.line3d", json!({"points": (0..500).map(|i| json!([i, 0, 0])).collect::<Vec<_>>()})),+ ("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1, 1], [2, 0, 3]]})),+ ("sketch.spline3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": null})),+ ("sketch.point3d", json!({"point": [3, 4, 5]})),+ ("sketch.point3d", json!({"point": {"x": 3, "y": 4, "z": 5}, "sketch": "Path"})),+ ("sketch.move3d", json!({"wire": wire, "to": [1, 2, 3]})),+ ("sketch.move3d", json!({"wire": wire, "index": 1, "by": [1, 0, 0]})),+ ("sketch.move3d", json!({"wire": wire, "index": 0, "to": [1, 2, 3], "by": [1, 0, 0]})),+ ("sketch.move3d", json!({"wire": wire, "by": {"x": 1, "y": 0, "z": 0}, "sketch": null})),+ ("sketch.move3d", json!({"wire": wire, "by": [1, 0, 0], "to": null})),+ ("sketch.move3d", json!({"wire": wire})),+ ("sketch.move3d", json!({"wire": "no such wire", "to": [1, 2, 3]})),+ ("sketch.move3d", json!({"wire": wire, "index": 7, "to": [1, 2, 3]})),+ ];+ for (id, p) in cases {+ let (mut off, _) = three_d(ParamCheck::Off);+ let (mut strict, _) = three_d(ParamCheck::Strict);+ let (mut warn, _) = three_d(ParamCheck::Warn);+ let today = off.execute(id, &p).map_err(|e| e.to_string());+ let checked = strict.execute(id, &p).map_err(|e| e.to_string());+ let warned = warn.execute(id, &p);+ let issues: Vec<_> = crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect();+ match &today {+ // A refusal the handler gives about the document (no such sketch, wire or point).+ Err(e) if issues.is_empty() => {+ let document = ["no sketch", "is not an editable drawn 3D curve", "has no drawn point", "give `to` or `by`"];+ assert!(document.iter().any(|m| e.contains(m)), "{id} {p}: refused for another reason: {e}");+ assert_eq!(checked.as_ref().err(), Some(e), "{id} {p}");+ assert!(warned.is_err(), "{id} {p}");+ }+ Err(e) => assert_eq!(checked.as_ref().err(), Some(e), "{id} {p}: {issues:?}"),+ Ok(reply) => {+ assert!(issues.is_empty(), "{id} {p}: {issues:?}");+ assert_eq!(checked.as_ref().ok(), Some(reply), "{id} {p}");+ assert_eq!(warned.ok().as_ref(), Some(reply), "{id} {p}");+ }+ }+ }+}++/// The schemas say what the handlers need: the keys they refuse without are required, `to` or+/// `by` is needed, and a point is `[x, y, z]` or `{x, y, z}`.+#[test]+fn the_schemas_take_what_the_handlers_read() {+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {+ let schema = schema.as_value();+ for (p, takes) in cases {+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");+ }+ };+ let two = json!([[0, 0, 0], [1, 1, 1]]);+ for schema in [input_schema_for::<Line3dParams>(), input_schema_for::<Spline3dParams>()] {+ takes(+ schema,+ &[+ (json!({"points": two}), true),+ (json!({"points": [{"x": 0, "y": 0, "z": 0}, [1, 1, 1]], "sketch": "Path"}), true),+ (json!({"points": two, "sketch": 4}), true),+ (json!({}), false),+ (json!({"points": [[0, 0, 0]]}), false),+ (json!({"points": [[0, 0, 0], [1, 1]]}), false),+ (json!({"points": two, "sketch": true}), false),+ ],+ );+ }+ takes(+ input_schema_for::<Point3dParams>(),+ &[+ (json!({"point": [1, 2, 3]}), true),+ (json!({"point": {"x": 1, "y": 2, "z": 3}}), true),+ (json!({}), false),+ (json!({"point": [1, 2]}), false),+ ],+ );+ takes(+ input_schema_for::<Move3dParams>(),+ &[+ (json!({"wire": "w1", "to": [1, 2, 3]}), true),+ (json!({"wire": "w1", "by": [1, 2, 3], "index": 499}), true),+ (json!({"wire": "w1", "to": [1, 2, 3], "by": [1, 2, 3], "sketch": "Path"}), true),+ (json!({"to": [1, 2, 3]}), false),+ (json!({"wire": "w1"}), false),+ (json!({"wire": "w1", "to": [1, 2, 3], "index": 500}), false),+ (json!({"wire": "w1", "to": [1, 2, 3], "index": -1}), false),+ (json!({"wire": 3, "to": [1, 2, 3]}), false),+ ],+ );+}++fn matches(schema: schemars::Schema, id: &str, reply: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");+}++/// Each command, in Warn: the real reply matches its output schema and carries no warning.+#[test]+fn replies_match_the_output_schema() {+ let (mut s, _) = three_d(ParamCheck::Warn);+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let line = run("sketch.line3d", json!({"points": [[0, 5, 0], [0, 5, 10], [10, 5, 10]]}));+ assert_eq!(line["curves"].as_array().map(Vec::len), Some(2), "{line}");+ matches(output_schema_for::<Curves3dResult>(), "sketch.line3d", &line);+ let by_name = run("sketch.line3d", json!({"points": [[0, 6, 0], [0, 6, 10]], "sketch": "Path"}));+ matches(output_schema_for::<Curves3dResult>(), "sketch.line3d", &by_name);+ let spline = run("sketch.spline3d", json!({"points": [[0, 8, 0], [5, 9, 5], [10, 8, 10]]}));+ assert_eq!(spline["curves"].as_array().map(Vec::len), Some(1), "{spline}");+ matches(output_schema_for::<Curves3dResult>(), "sketch.spline3d", &spline);+ let point = run("sketch.point3d", json!({"point": {"x": 3, "y": 4, "z": 5}}));+ assert!(point["point"].is_string(), "{point}");+ matches(output_schema_for::<Point3dResult>(), "sketch.point3d", &point);+ let curve = line["curves"][0].clone();+ for p in [+ json!({"wire": curve, "index": 1, "by": [0, 0, 5]}),+ json!({"wire": curve, "to": [1, 5, 1]}),+ json!({"wire": point["point"], "to": [3, 4, 6], "by": [9, 9, 9]}),+ ] {+ let moved = run("sketch.move3d", p);+ assert!(moved["moved"].as_u64().is_some_and(|n| n >= 1), "{moved}");+ matches(output_schema_for::<Move3dResult>(), "sketch.move3d", &moved);+ }+}++/// A misspelt key still runs in Warn, and says so, with a reply that still matches.+#[test]+fn a_misspelt_key_is_reported_in_warn() {+ let (mut s, ids) = three_d(ParamCheck::Warn);+ let calls = [+ ("sketch.line3d", json!({"points": [[0, 5, 0], [0, 5, 10]], "skech": "Path"})),+ ("sketch.spline3d", json!({"points": [[0, 5, 0], [0, 5, 10]], "skech": "Path"})),+ ("sketch.point3d", json!({"point": [1, 2, 3], "pont": [1, 2, 3]})),+ ("sketch.move3d", json!({"wire": ids[0], "to": [1, 2, 3], "inex": 1})),+ ];+ for (id, p) in calls {+ let reply = s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));+ let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();+ assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {reply}");+ let schema = match id {+ "sketch.point3d" => output_schema_for::<Point3dResult>(),+ "sketch.move3d" => output_schema_for::<Move3dResult>(),+ _ => output_schema_for::<Curves3dResult>(),+ };+ assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{id}: {reply}");+ }+}++/// The warning for what a key gets wrong is the handler's own wording.+#[test]+fn the_check_names_what_is_wrong_with_a_key() {+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();+ assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0]]})), ["`points` needs 2 to 500 points"]);+ assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0], [1]]})), ["a point must be [x, y, z]"]);+ assert_eq!(issues("sketch.spline3d", json!({"points": 1})), ["`points` must list [x,y,z] points"]);+ assert_eq!(issues("sketch.point3d", json!({"point": [1]})), ["`point` must be a point [x, y, z]"]);+ assert_eq!(issues("sketch.move3d", json!({"wire": 1})), ["`wire` must be a 3D curve or point id"]);+ assert_eq!(issues("sketch.move3d", json!({"wire": "w", "index": 500})), ["`index` must be a fit point index below 500"]);+ assert_eq!(issues("sketch.move3d", json!({"wire": "w", "by": 1})), ["`by` must be [x,y,z]"]);+ assert_eq!(issues("sketch.line3d", json!({"points": [[0, 0, 0], [1, 1, 1]], "sketch": true})), ["`sketch` must be an id or a name"]);+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 7b5dd35770..b6c296749e 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -90,11 +90,8 @@ sketch.inspectsketch.intersectsketch.intersection_curvesketch.isoparametric_curve-sketch.line3d-sketch.move3dsketch.move_pointsketch.options-sketch.point3dsketch.polygon.circumscribedsketch.polygon.edgesketch.polygon.inscribed@@ -108,7 +105,6 @@ sketch.slot.center_to_centersketch.slot.overallsketch.snapsketch.solve-sketch.spline3dsketch.spun_profilesketch.toggle_drivensolid.align