SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Auto Constrain, the constrainer, snapping and the curvature and polygon constraints describe their exact parameters and reply (#12506) (#12599)
PeppaWutzcf9ae4d25ec2
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 0fda65c5ed..e022cc39dc 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -2070,8 +2070,7 @@ fn constrain_reply(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Skreply(cmd, ConstraintResult { made, param_warnings: Vec::new() })}-/// The constraint a command added and, when the sketch already determined it, what determines it-/// (see [`constraint_result`], which the other constraint commands build their reply with).+/// The constraint a command added and, when the sketch already determined it, what determines it.fn constrained(p: &Value, cmd: &str, id: String, info: Value, by: Option<Vec<String>>) -> Result<Constrained> {let Some(by) = by else { return Ok(Constrained { constraint: id, sketch: info, redundant: None, determined_by: None }) };keep_redundant(p, cmd, &by)?;@@ -2384,21 +2383,6 @@ pub(super) fn keep_redundant(p: &Value, cmd: &str, by: &[String]) -> Result<()>Ok(())}-/// The result of a constraint command: the constraint, and whether it is redundant (and what-/// determines it).-pub(super) fn constraint_result(p: &Value, cmd: &str, id: String, info: Value, by: Option<Vec<String>>, extra: Value) -> Result<Value> {- let mut out = json!({"constraint": id, "sketch": info});- if let Some(by) = by {- keep_redundant(p, cmd, &by)?;- out["redundant"] = json!(true);- out["determined_by"] = json!(by);- }- if let (Some(o), Value::Object(e)) = (out.as_object_mut(), extra) {- o.extend(e);- }- Ok(out)-}-/// The residual of the constraint `id` where the sketch is now (see/// [`solidcraft_sketch::constraint_residual`]).pub(super) fn residual_of(sk: &Sketch, id: &str) -> Option<f64> {diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rsindex e29baa601a..464a43df23 100644--- a/crates/engine/src/cmd/sketch_constraints.rs+++ b/crates/engine/src/cmd/sketch_constraints.rs@@ -1,54 +1,81 @@//! More sketch constraints (curvature, polygon), constraint glyph anchors and snapping//! inference for interactive tools.-use serde_json::{Value, json};+use serde_json::Value;use solidcore_record::Vec2;use solidcraft_geom::prelude::*;use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch};-use super::sketch::{add_c, constraint_result, dof_now, edit, listed, redundancy, residual_of};+use super::sketch::{add_c, dof_now, edit, keep_redundant, listed, redundancy, residual_of};use super::sketch_store;use super::{CommandSpec, in_sketch};use crate::params::{bad, num, req_vec2, str_, string_list, vec2};-use crate::schema::sketch_constraints::{ToggleDiameterParams, ToggleDiameterResult};+use crate::schema::sketch_constraints::{+ AutoConstrainDatumParams, AutoConstrainParams, AutoConstrainResult, ConstrainerParams, ConstrainerResult, ConstraintAdded, CurvatureParams,+ FinishAutoConstrainParams, Glyph, GlyphsParams, GlyphsResult, PolygonParams, PolygonResult, Snap, SnapParams, SnapResult, ToggleDiameterParams,+ ToggleDiameterResult, ToggleDrivenParams, ToggleDrivenResult,+};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};const TOGGLE_DIAMETER_CONTRACT: TypedContract<ToggleDiameterParams> = TypedContract::new();+const CURVATURE_CONTRACT: TypedContract<CurvatureParams> = TypedContract::new();+const POLYGON_CONTRACT: TypedContract<PolygonParams> = TypedContract::new();+const AUTO_CONSTRAIN_CONTRACT: TypedContract<AutoConstrainParams> = TypedContract::new();+const AUTO_CONSTRAIN_DATUM_CONTRACT: TypedContract<AutoConstrainDatumParams> = TypedContract::new();+const FINISH_AUTO_CONSTRAIN_CONTRACT: TypedContract<FinishAutoConstrainParams> = TypedContract::new();+const CONSTRAINER_CONTRACT: TypedContract<ConstrainerParams> = TypedContract::new();+const TOGGLE_DRIVEN_CONTRACT: TypedContract<ToggleDrivenParams> = TypedContract::new();+const GLYPHS_CONTRACT: TypedContract<GlyphsParams> = TypedContract::new();+const SNAP_CONTRACT: TypedContract<SnapParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("sketch.constraint.curvature", "Curvature", c_smooth)+ CommandSpec::new("sketch.constraint.curvature", "Curvature", crate::checked!("sketch.constraint.curvature", c_smooth)).at("SKETCH", "CONSTRAINTS").icon("c_smooth").enabled(in_sketch)+ .contract(&CURVATURE_CONTRACT)+ .output(output_schema_for::<ConstraintAdded>).params("a, b: two curves sharing an end point (curvature continuous, G2)"),- CommandSpec::new("sketch.constraint.polygon", "Polygon", c_polygon)+ CommandSpec::new("sketch.constraint.polygon", "Polygon", crate::checked!("sketch.constraint.polygon", c_polygon)).at("SKETCH", "CONSTRAINTS").icon("c_polygon").enabled(in_sketch)+ .contract(&POLYGON_CONTRACT)+ .output(output_schema_for::<PolygonResult>).params("lines: [line ids] of a closed chain: equal sides with every corner on one circle (a regular polygon)"),- CommandSpec::new("sketch.auto_constrain", "AutoConstrain", auto_constrain)+ CommandSpec::new("sketch.auto_constrain", "AutoConstrain", crate::checked!("sketch.auto_constrain", auto_constrain)).at("SKETCH", "CONSTRAINTS").icon("auto_constrain").enabled(in_sketch)+ .contract(&AUTO_CONSTRAIN_CONTRACT)+ .output(output_schema_for::<AutoConstrainResult>).params("tolerance?: mm (default 0.01), angle_tolerance?: deg (default 1), dimensions?: bool (default true): infer constraints, then dimension until fully constrained"),- CommandSpec::new("sketch.auto_constrain_from_datum", "AutoConstrain from Datum", auto_constrain_datum)+ CommandSpec::new("sketch.auto_constrain_from_datum", "AutoConstrain from Datum", crate::checked!("sketch.auto_constrain_from_datum", auto_constrain_datum)).at("SKETCH", "CONSTRAINTS").icon("auto_constrain").enabled(in_sketch)+ .contract(&AUTO_CONSTRAIN_DATUM_CONTRACT)+ .output(output_schema_for::<AutoConstrainResult>).params("datum: point ref (default origin); like AutoConstrain with positions measured from the datum"),- CommandSpec::new("sketch.finish_auto_constrain", "Finish with AutoConstrain", auto_constrain_finish)+ CommandSpec::new("sketch.finish_auto_constrain", "Finish with AutoConstrain", crate::checked!("sketch.finish_auto_constrain", auto_constrain_finish)).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch)+ .contract(&FINISH_AUTO_CONSTRAIN_CONTRACT)+ .output(output_schema_for::<AutoConstrainResult>).params("like AutoConstrain, then Finish Sketch"),- CommandSpec::new("sketch.constrainer", "Sketch Constrainer", smart_constrain)+ CommandSpec::new("sketch.constrainer", "Sketch Constrainer", crate::checked!("sketch.constrainer", smart_constrain)).at("SKETCH", "CREATE").icon("constrainer").enabled(in_sketch)+ .contract(&CONSTRAINER_CONTRACT)+ .output(output_schema_for::<ConstrainerResult>).params("entities: [one or two sketch entity ids]: applies the constraint the geometry nearly has (horizontal/vertical, parallel, perpendicular, collinear, coincident, concentric, equal, tangent)"),- CommandSpec::new("sketch.toggle_driven", "Toggle Driven Dimension", toggle_driven).icon("dimension")+ CommandSpec::new("sketch.toggle_driven", "Toggle Driven Dimension", crate::checked!("sketch.toggle_driven", toggle_driven)).icon("dimension").enabled(in_sketch)+ .contract(&TOGGLE_DRIVEN_CONTRACT)+ .output(output_schema_for::<ToggleDrivenResult>).params("constraint: dimension id, driven?: bool (default toggles); a driving dimension gets a parameter with its current value"),CommandSpec::new("sketch.toggle_diameter", "Toggle Radius / Diameter", crate::checked!("sketch.toggle_diameter", toggle_diameter)).icon("dimension")@@ -56,13 +83,17 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&TOGGLE_DIAMETER_CONTRACT).output(output_schema_for::<ToggleDiameterResult>).params("constraint: a circle's or an arc's radius or diameter dimension id; diameter?: bool (default: the other one); sketch?: id|name (default: the one being edited). The circle stays the same size: its parameter is halved or doubled (a plain value is rewritten, an expression becomes `(e) / 2` or `2 * (e)`); refused when anything else uses that parameter"),- CommandSpec::new("sketch.glyphs", "Constraint Glyphs", glyphs).icon("eye")+ CommandSpec::new("sketch.glyphs", "Constraint Glyphs", crate::checked!("sketch.glyphs", glyphs)).icon("eye").enabled(in_sketch).noundo()+ .contract(&GLYPHS_CONTRACT)+ .output(output_schema_for::<GlyphsResult>).params("sketch?: id|name: every constraint with where to draw its glyph (sketch coordinates)"),- CommandSpec::new("sketch.snap", "Snap Inference", snap).icon("snap")+ CommandSpec::new("sketch.snap", "Snap Inference", crate::checked!("sketch.snap", snap)).icon("snap").enabled(in_sketch).noundo()+ .contract(&SNAP_CONTRACT)+ .output(output_schema_for::<SnapResult>).params("at: [x,y], from?: [x,y] (previous click), radius?: mm (snap distance, default 1): what a click there would snap to and infer"),];@@ -78,7 +109,26 @@ fn c_smooth(s: &mut Session, p: &Value) -> Result<Value> {Ok(id)})?;let by = redundancy(s, p, cmd, before, &info, residual, &id)?;- constraint_result(p, cmd, id, info, by, Value::Null)+ let (redundant, determined_by) = redundant_part(p, cmd, by)?;+ reply(cmd, ConstraintAdded { constraint: id, sketch: info, redundant, determined_by, created: None, param_warnings: Vec::new() })+}++/// 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()))+}++/// What a new constraint's reply says of redundancy: whether it is, and by which constraints. A+/// redundant one is refused when the call asked for `if_redundant: "refuse"`.+fn redundant_part(p: &Value, cmd: &str, by: Option<Vec<String>>) -> Result<(bool, Option<Vec<String>>)> {+ match by {+ Some(by) => {+ keep_redundant(p, cmd, &by)?;+ Ok((true, Some(by)))+ }+ None => Ok((false, None)),+ }}fn curve(sk: &Sketch, v: Option<&Value>, cmd: &str) -> Result<usize> {@@ -126,7 +176,7 @@ fn c_polygon(s: &mut Session, p: &Value) -> Result<Value> {}Ok(cons)})?;- Ok(json!({"constraints": out, "sketch": info}))+ reply(cmd, PolygonResult { constraints: out, sketch: info, created: None, param_warnings: Vec::new() })}/// Most constraints AutoConstrain tries.@@ -273,7 +323,7 @@ fn auto(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {// its freedom whenever they change constraints; no separate initial solve is needed.Ok(run_auto(sk, doc, p, datum, rep.dof))})?;- Ok(json!({"added": added, "dof": dof, "sketch": info}))+ reply(cmd, AutoConstrainResult { added, dof, sketch: info, created: None, param_warnings: Vec::new() })}fn auto_constrain(s: &mut Session, p: &Value) -> Result<Value> {@@ -375,7 +425,19 @@ fn smart_constrain(s: &mut Session, p: &Value) -> Result<Value> {Ok(id)})?;let by = redundancy(s, p, cmd, before, &info, residual, &id)?;- constraint_result(p, cmd, id, info, by, json!({"type": name}))+ let (redundant, determined_by) = redundant_part(p, cmd, by)?;+ reply(+ cmd,+ ConstrainerResult {+ constraint: id,+ sketch: info,+ redundant,+ determined_by,+ kind: name.to_string(),+ created: None,+ param_warnings: Vec::new(),+ },+ )}fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {@@ -417,7 +479,7 @@ fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {}}s.doc_mut().prune_model_params();- Ok(json!({"constraint": cid, "driven": driven, "sketch": info}))+ reply(cmd, ToggleDrivenResult { constraint: cid, driven, sketch: info, created: None, param_warnings: Vec::new() })}fn toggle_diameter(s: &mut Session, p: &Value) -> Result<Value> {@@ -528,26 +590,32 @@ fn glyphs(s: &mut Session, p: &Value) -> Result<Value> {let st = s.model.state();let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;let failing = &ss.report.failing;- let list: Vec<Value> = ss+ let glyphs: Vec<Glyph> = ss.sketch.constraints.iter()- .map(|c| {- json!({- "id": c.id,- "name": c.kind.name(),- "dimension": c.kind.is_dimension(),- "driven": c.driven,- "value": c.kind.value(),- "param": c.param,- "at": anchor(&ss.sketch, &c.kind),- "failing": failing.contains(&c.id),- // Implied by the others (it removes no freedom) but holding: shown dimmed.- "redundant": ss.report.redundant.contains(&c.id),- })+ .map(|c| Glyph {+ id: c.id.clone(),+ name: c.kind.name().to_string(),+ dimension: c.kind.is_dimension(),+ driven: c.driven,+ value: c.kind.value(),+ param: c.param.clone(),+ at: anchor(&ss.sketch, &c.kind).map(|a| [a.x, a.y]),+ failing: failing.contains(&c.id),+ // Implied by the others (it removes no freedom) but holding: shown dimmed.+ redundant: ss.report.redundant.contains(&c.id),}).collect();- Ok(json!({"sketch": id, "glyphs": list, "dof": ss.report.dof, "fully_constrained": ss.report.fully_constrained(), "conflicts": failing}))+ let result = GlyphsResult {+ sketch: id,+ glyphs,+ dof: ss.report.dof,+ fully_constrained: ss.report.fully_constrained(),+ conflicts: failing.clone(),+ param_warnings: Vec::new(),+ };+ reply("sketch.glyphs", result)}/// Snap inference for a click at `at`: the nearest sketch point (coincident), the midpoint of a@@ -562,12 +630,12 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {let st = s.model.state();let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch is not evaluated".into()))?;let sk = &ss.sketch;- let mut out: Vec<(f64, Value)> = Vec::new();+ let mut out: Vec<(f64, Snap)> = Vec::new();// Points (end points, centres, the origin).for q in &sk.points {let d = q.pos.dist(at);if d <= r {- out.push((d * 0.5, json!({"type": "coincident", "point": q.id, "at": q.pos})));+ out.push((d * 0.5, Snap::Coincident { point: q.id.clone(), at: [q.pos.x, q.pos.y] }));}}for (i, c) in sk.curves.iter().enumerate() {@@ -577,13 +645,13 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {let m = (pa + pb) * 0.5;let d = m.dist(at);if d <= r {- out.push((d * 0.6, json!({"type": "midpoint", "curve": c.id, "at": m})));+ out.push((d * 0.6, Snap::Midpoint { curve: c.id.clone(), at: [m.x, m.y] }));}}if let Some(sh) = sk.shape(i) {let q = sh.project(at);if sh.dist(at) <= r && q.dist(at) <= r {- out.push((sh.dist(at) + r * 0.5, json!({"type": "on_curve", "curve": c.id, "at": q})));+ out.push((sh.dist(at) + r * 0.5, Snap::OnCurve { curve: c.id.clone(), at: [q.x, q.y] }));}}}@@ -591,15 +659,15 @@ fn snap(s: &mut Session, p: &Value) -> Result<Value> {if let Some(f) = from {let d = at - f;if d.y.abs() <= r && d.x.abs() > r {- out.push((d.y.abs() + r, json!({"type": "horizontal", "at": [at.x, f.y]})));+ out.push((d.y.abs() + r, Snap::Horizontal { at: [at.x, f.y] }));}if d.x.abs() <= r && d.y.abs() > r {- out.push((d.x.abs() + r, json!({"type": "vertical", "at": [f.x, at.y]})));+ out.push((d.x.abs() + r, Snap::Vertical { at: [f.x, at.y] }));}}out.sort_by(|a, b| a.0.total_cmp(&b.0));- let list: Vec<Value> = out.into_iter().take(8).map(|x| x.1).collect();- Ok(json!({"snaps": list}))+ let snaps: Vec<Snap> = out.into_iter().take(8).map(|x| x.1).collect();+ reply(cmd, SnapResult { snaps, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/schema/sketch_constraints.rs b/crates/engine/src/schema/sketch_constraints.rsindex 9ab8de3142..3c58469915 100644--- a/crates/engine/src/schema/sketch_constraints.rs+++ b/crates/engine/src/schema/sketch_constraints.rs@@ -1,10 +1,28 @@-//! Contracts and result types for the commands in `cmd/sketch_constraints.rs`.+//! Contracts and result types for the commands in `cmd/sketch_constraints.rs`: the curvature and+//! polygon constraints, the constrainer, Auto Constrain (three commands), Toggle Driven Dimension,+//! Toggle Radius / Diameter, the constraint glyphs and Snap Inference.+//!+//! 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 (whether a+//! sketch, curve, point or dimension exists) stays the handler's to check. A key the handler+//! refuses when it is left out (`a`, `b`, `lines`, `entities`, `constraint`, `at`) is optional in+//! the type, so the handler keeps its own message, and required in the schema. 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 schemars::JsonSchema;-use serde::{Deserialize, Serialize};+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;-use super::types::{SketchRef, present};+use super::check::whole;+use super::config::NameList;+use super::motion::require;+use super::sketch_ends::SketchTarget;+use super::types::{Point2, SketchRef, present};+use crate::params;/// Switch a circle's or an arc's dimension between its radius and its diameter.#[derive(Debug, Deserialize, JsonSchema)]@@ -44,6 +62,464 @@ pub struct ToggleDiameterResult {pub param_warnings: Vec<String>,}+/// A curve's id, as `sketch.constraint.curvature` reads `a` and `b`: text, else its message.+#[derive(Clone, Debug, PartialEq)]+pub struct CurveId(pub String);++impl<'de> Deserialize<'de> for CurveId {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(s) => Ok(CurveId(s)),+ _ => Err(D::Error::custom(whole("expected a curve id"))),+ }+ }+}++impl JsonSchema for CurveId {+ fn schema_name() -> Cow<'static, str> {+ "CurveId".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A curve's id in the sketch, such as `c3`.", "type": "string"})+ }+}++/// A dimension's constraint id, as `sketch.toggle_driven` reads `constraint`.+#[derive(Clone, Debug, PartialEq)]+pub struct DimensionId(pub String);++impl<'de> Deserialize<'de> for DimensionId {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(s) => Ok(DimensionId(s)),+ _ => Err(D::Error::custom("must be a dimension id")),+ }+ }+}++impl JsonSchema for DimensionId {+ fn schema_name() -> Cow<'static, str> {+ "DimensionId".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A dimension's constraint id in the sketch.", "type": "string"})+ }+}++/// The point of `sketch.snap`'s `at`: `[x, y]` or `{x, y}` of numbers (below 1e9), with+/// `params::req_vec2`'s message.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ClickPoint(pub solidcore_record::Vec2);++impl<'de> Deserialize<'de> for ClickPoint {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec2(&Value::deserialize(d)?).map(ClickPoint).ok_or_else(|| D::Error::custom("must be a point [x, y]"))+ }+}++impl JsonSchema for ClickPoint {+ fn schema_name() -> Cow<'static, str> {+ "ClickPoint".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<Point2>()+ }+}++/// The ids of the refusing-when-left-out keys are listed in the schema's `required`.+fn require_keys(schema: &mut Schema, keys: &[&str]) {+ for key in keys {+ require(schema, key);+ }+}++fn curvature_required(schema: &mut Schema) {+ require_keys(schema, &["a", "b"]);+}++fn polygon_required(schema: &mut Schema) {+ require_keys(schema, &["lines"]);+}++fn constrainer_required(schema: &mut Schema) {+ require_keys(schema, &["entities"]);+}++fn driven_required(schema: &mut Schema) {+ require_keys(schema, &["constraint"]);+}++fn snap_required(schema: &mut Schema) {+ require_keys(schema, &["at"]);+}++/// Make two curves meet with curvature continuity (G2): they must share an end point.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = curvature_required)]+pub struct CurvatureParams {+ // Optional in the type and required in the schema (`curvature_required`): left out, the+ // handler refuses it with its own message, not the check's "is required".+ /// The first curve's id.+ #[serde(default)]+ pub a: Option<CurveId>,+ /// The second curve's id.+ #[serde(default)]+ pub b: Option<CurveId>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// `refuse` (any case) refuses the constraint when the others already determine it. Anything+ /// else keeps it, shown dimmed as redundant. Read only then.+ #[serde(default)]+ pub if_redundant: Option<String>,+}++/// Make a closed chain of lines a regular polygon: the sides equal and every corner on one+/// (construction) circle, which is added.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = polygon_required)]+pub struct PolygonParams {+ // Optional in the type and required in the schema, as `a` above.+ /// The ids of the lines of the closed chain: 3 to 200 of them, each a line whose end points+ /// are shared with its neighbours.+ #[serde(default)]+ pub lines: Option<NameList>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Apply the constraint one or two sketch entities nearly have already: horizontal or vertical+/// for one line; for two, coincident, point on curve, collinear, parallel, perpendicular, equal,+/// concentric or tangent, whichever the geometry is closest to.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = constrainer_required)]+pub struct ConstrainerParams {+ // Optional in the type and required in the schema, as `a` above.+ /// One or two sketch entity ids (curves or points): one line, or two entities.+ #[serde(default)]+ pub entities: Option<NameList>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// `refuse` (any case) refuses the constraint when the others already determine it. Anything+ /// else keeps it, shown dimmed as redundant. Read only then.+ #[serde(default)]+ pub if_redundant: Option<String>,+}++/// Infer the constraints the sketch's geometry nearly has (coincident points, horizontal and+/// vertical lines, tangent joints), then dimension what is left until it is fully constrained.+/// A constraint that removes no freedom or that the sketch could not solve with is dropped.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct AutoConstrainParams {+ /// How close two points must be to be made coincident, in mm (a number of 0 or less, or of+ /// 1e9 or more, is read as the default). Default: 0.01.+ #[serde(default)]+ pub tolerance: Option<f64>,+ /// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a+ /// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.+ #[serde(default)]+ pub angle_tolerance: Option<f64>,+ /// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.+ #[serde(default)]+ pub dimensions: Option<bool>,+ /// The point the position dimensions are measured from: a point id or a name the sketch+ /// resolves (as `sketch.auto_constrain_from_datum` takes it). Default: the sketch origin.+ #[serde(default)]+ pub datum: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Auto Constrain with the position dimensions measured from a datum point instead of the+/// origin.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct AutoConstrainDatumParams {+ /// How close two points must be to be made coincident, in mm (a number of 0 or less, or of+ /// 1e9 or more, is read as the default). Default: 0.01.+ #[serde(default)]+ pub tolerance: Option<f64>,+ /// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a+ /// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.+ #[serde(default)]+ pub angle_tolerance: Option<f64>,+ /// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.+ #[serde(default)]+ pub dimensions: Option<bool>,+ /// The point the position dimensions are measured from: a point id or a name the sketch+ /// resolves. Default: the sketch origin.+ #[serde(default)]+ pub datum: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Auto Constrain, then Finish Sketch: the sketch is closed when it is done.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct FinishAutoConstrainParams {+ /// How close two points must be to be made coincident, in mm (a number of 0 or less, or of+ /// 1e9 or more, is read as the default). Default: 0.01.+ #[serde(default)]+ pub tolerance: Option<f64>,+ /// How far a line may be from horizontal or vertical, or a joint from tangent, in degrees (a+ /// number of 0 or less, or of 1e9 or more, is read as the default). Default: 1.+ #[serde(default)]+ pub angle_tolerance: Option<f64>,+ /// Add dimensions (lengths, radii, diameters, distances from the datum). Default: true.+ #[serde(default)]+ pub dimensions: Option<bool>,+ /// The point the position dimensions are measured from: a point id or a name the sketch+ /// resolves. Default: the sketch origin.+ #[serde(default)]+ pub datum: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Make a dimension driven (it measures, and is no longer a parameter) or driving again (it gets+/// a parameter holding its current value).+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = driven_required)]+pub struct ToggleDrivenParams {+ // Optional in the type and required in the schema, as `a` above.+ /// The dimension's constraint id.+ #[serde(default)]+ pub constraint: Option<DimensionId>,+ /// `true` for driven, `false` for driving. Default: the other one from now.+ #[serde(default)]+ pub driven: Option<bool>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// List every constraint of a sketch with where its glyph is drawn (sketch coordinates), what it+/// is and whether it fails or is redundant, with the sketch's freedom. Changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct GlyphsParams {+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// What a click at a point in the sketch being edited would snap to or infer, best first: a+/// point, a line's midpoint, a point on a curve, and horizontal or vertical alignment with the+/// previous click. Changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = snap_required)]+pub struct SnapParams {+ // Optional in the type and required in the schema, as `a` above.+ /// The click, [x, y] in the sketch's coordinates, in mm.+ #[serde(default)]+ pub at: Option<ClickPoint>,+ /// The previous click, [x, y]: horizontal and vertical alignment with it is offered. Default:+ /// none.+ #[serde(default)]+ pub from: Option<Point2>,+ /// The snap distance in mm (a number of 0 or less, or of 1e9 or more, is read as the+ /// default). Default: 1.+ #[serde(default)]+ pub radius: Option<f64>,+}++/// What the curvature constraint returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ConstraintAdded {+ /// The new constraint's id.+ pub constraint: String,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// `true` when the other constraints already determine it (present only then).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub redundant: bool,+ /// The constraints that already determine it, as "id (Name)" (present only when redundant).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub determined_by: Option<Vec<String>>,+ /// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists+ /// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.+ #[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.constrainer` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ConstrainerResult {+ /// The new constraint's id.+ pub constraint: String,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// `true` when the other constraints already determine it (present only then).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub redundant: bool,+ /// The constraints that already determine it, as "id (Name)" (present only when redundant).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub determined_by: Option<Vec<String>>,+ /// The kind of constraint applied, such as `Horizontal` or `Tangent`.+ #[serde(rename = "type")]+ pub kind: String,+ /// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists+ /// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.+ #[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 the polygon constraint returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct PolygonResult {+ /// The new constraints' ids: equal sides, then the corners on the circle.+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists+ /// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.+ #[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 the Auto Constrain commands return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct AutoConstrainResult {+ /// The ids of the constraints and dimensions it added.+ pub added: Vec<String>,+ /// The degrees of freedom left (0: fully constrained).+ pub dof: usize,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists+ /// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.+ #[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.toggle_driven` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ToggleDrivenResult {+ /// The dimension's constraint id (unchanged).+ pub constraint: String,+ /// Whether it is driven now.+ pub driven: bool,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// What the command added to its sketch, `{points, curves, constraints, dimensions}` (lists+ /// of ids): the session adds it to the reply of a sketch command, so the handler leaves it out.+ #[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>,+}++/// One constraint of `sketch.glyphs`, with where its glyph goes.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Glyph {+ /// The constraint's id.+ pub id: String,+ /// Its kind, such as `Horizontal` or `Radius`.+ pub name: String,+ /// Whether it is a dimension.+ pub dimension: bool,+ /// Whether it is driven (it measures; it does not constrain).+ pub driven: bool,+ /// A dimension's value (mm, or radians for an angle); `null` for another constraint.+ pub value: Option<f64>,+ /// The parameter a driving dimension takes its value from; `null` for none.+ pub param: Option<String>,+ /// Where to draw the glyph, [x, y] in sketch coordinates; `null` when it has no place.+ pub at: Option<[f64; 2]>,+ /// Whether it is one of the constraints the solver could not satisfy.+ pub failing: bool,+ /// Whether the others imply it (it removes no freedom) though it holds: shown dimmed.+ pub redundant: bool,+}++/// What `sketch.glyphs` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct GlyphsResult {+ /// The sketch's feature id.+ pub sketch: u64,+ /// Its constraints, in order.+ pub glyphs: Vec<Glyph>,+ /// The degrees of freedom left.+ pub dof: usize,+ /// Whether nothing is left free.+ pub fully_constrained: bool,+ /// The ids of the constraints that fail.+ pub conflicts: Vec<String>,+ /// 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>,+}++/// One thing a click would snap to or infer.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum Snap {+ /// An existing point (an end point, a centre, the origin): the click is made coincident.+ Coincident {+ /// The point's id.+ point: String,+ /// Where it is, [x, y].+ at: [f64; 2],+ },+ /// The middle of a line.+ Midpoint {+ /// The line's id.+ curve: String,+ /// The middle, [x, y].+ at: [f64; 2],+ },+ /// The nearest place on a curve.+ OnCurve {+ /// The curve's id.+ curve: String,+ /// That place, [x, y].+ at: [f64; 2],+ },+ /// Level with the previous click (`from`).+ Horizontal {+ /// The click moved to that level, [x, y].+ at: [f64; 2],+ },+ /// Straight above or below the previous click (`from`).+ Vertical {+ /// The click moved to that line, [x, y].+ at: [f64; 2],+ },+}++/// What `sketch.snap` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SnapResult {+ /// At most eight, best first: the first is what a click would use.+ pub snaps: Vec<Snap>,+ /// 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_constraints_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/sketch_constraints_tests.rs b/crates/engine/src/schema/sketch_constraints_tests.rsindex 9a225954e0..8ed6740c08 100644--- a/crates/engine/src/schema/sketch_constraints_tests.rs+++ b/crates/engine/src/schema/sketch_constraints_tests.rs@@ -1,13 +1,29 @@-use serde_json::json;+use serde_json::{Value, json};-use super::{ToggleDiameterParams, ToggleDiameterResult};+use super::{+ AutoConstrainDatumParams, AutoConstrainParams, AutoConstrainResult, ConstrainerParams, ConstrainerResult, ConstraintAdded, CurvatureParams,+ FinishAutoConstrainParams, GlyphsParams, GlyphsResult, PolygonParams, PolygonResult, SnapParams, SnapResult, ToggleDiameterParams,+ ToggleDiameterResult, ToggleDrivenParams, ToggleDrivenResult,+};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};+const AUTO_KEYS: [&str; 5] = ["angle_tolerance", "datum", "dimensions", "sketch", "tolerance"];+#[test]fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<ToggleDiameterParams>(), &["constraint", "diameter", "sketch"]);+ assert_keys(input_schema_for::<CurvatureParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<PolygonParams>(), &["lines", "sketch"]);+ assert_keys(input_schema_for::<ConstrainerParams>(), &["entities", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<AutoConstrainParams>(), &AUTO_KEYS);+ assert_keys(input_schema_for::<AutoConstrainDatumParams>(), &AUTO_KEYS);+ assert_keys(input_schema_for::<FinishAutoConstrainParams>(), &AUTO_KEYS);+ assert_keys(input_schema_for::<ToggleDrivenParams>(), &["constraint", "driven", "sketch"]);+ // Snap Inference works in the sketch being edited: it reads no `sketch`.+ assert_keys(input_schema_for::<GlyphsParams>(), &["sketch"]);+ assert_keys(input_schema_for::<SnapParams>(), &["at", "from", "radius"]);}#[test]@@ -17,9 +33,195 @@ fn strict_keeps_todays_errors() {("sketch.toggle_diameter", json!({"constraint": null})),("sketch.toggle_diameter", json!({"constraint": "c1"})),("sketch.toggle_diameter", json!({"constraint": "c1", "diameter": true})),+ // The keys these handlers read before they need a sketch.+ ("sketch.constrainer", json!({"entities": 5})),+ ("sketch.constrainer", json!({"entities": [1]})),+ ("sketch.constrainer", json!({"entities": ["a", 2]})),+ ("sketch.constrainer", json!({})),+ ("sketch.constrainer", json!({"entities": null})),+ ("sketch.constraint.polygon", json!({"lines": true})),+ ("sketch.constraint.polygon", json!({"lines": [{}]})),+ ("sketch.constraint.polygon", json!({})),+ ("sketch.constraint.polygon", json!({"lines": ["l1", "l2"]})),+ ("sketch.toggle_driven", json!({})),+ ("sketch.toggle_driven", json!({"constraint": 5})),+ ("sketch.toggle_driven", json!({"constraint": null})),+ ("sketch.toggle_driven", json!({"constraint": ["k1"]})),+ ("sketch.snap", json!({})),+ ("sketch.snap", json!({"at": 5})),+ ("sketch.snap", json!({"at": [1]})),+ ("sketch.snap", json!({"at": null})),+ ("sketch.snap", json!({"at": [1, "2"]})),+ ("sketch.snap", json!({"at": [1, 2]})),+ ("sketch.glyphs", json!({})),+ ("sketch.auto_constrain", json!({})),]);}+/// A session that is editing a sketch with a line and a circle in it.+fn editing(level: ParamCheck) -> Session {+ let mut s = Session { param_check: level, ..Session::default() };+ for (id, p) in [+ ("sketch.create", json!({"plane": "XY"})),+ ("sketch.line", json!({"points": [[0, 0], [10, 0.5]]})),+ ("sketch.circle.center", json!({"center": [50, 0], "radius": 5})),+ ] {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));+ }+ s+}++/// The same refusals in a sketch being edited, where the handlers go on to read the sketch, the+/// curves and the points: strict says what the handler says.+#[test]+fn strict_keeps_todays_errors_in_a_sketch() {+ let cases = [+ ("sketch.constraint.curvature", json!({})),+ ("sketch.constraint.curvature", json!({"a": 5, "b": "c1"})),+ ("sketch.constraint.curvature", json!({"a": "c1"})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": null})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": ["c2"]})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": true})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": -1})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": 1.5})),+ ("sketch.constraint.curvature", json!({"a": "c1", "b": "c2", "sketch": [1]})),+ ("sketch.constrainer", json!({"entities": ["c1"], "sketch": {}})),+ ("sketch.constraint.polygon", json!({"lines": ["c1", "c2", "c3"], "sketch": false})),+ ("sketch.toggle_driven", json!({"constraint": "k1", "sketch": -3})),+ ("sketch.glyphs", json!({"sketch": true})),+ ("sketch.glyphs", json!({"sketch": 2.5})),+ ("sketch.auto_constrain", json!({"sketch": ["a"]})),+ ("sketch.auto_constrain_from_datum", json!({"sketch": -1})),+ ("sketch.finish_auto_constrain", json!({"sketch": {}})),+ ];+ for (index, (id, p)) in cases.iter().enumerate() {+ let error = |level: ParamCheck| editing(level).execute(id, p).err().map(|e| e.to_string());+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{index} {id} {p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{index} {id} {p}");+ }+}++/// What strict adds on purpose: a value of the wrong type the handlers read as if the key were+/// left out (a wrong-typed option or `from`).+#[test]+fn strict_refuses_options_the_handlers_ignore() {+ let mut s = editing(ParamCheck::Strict);+ let line = s.execute("sketch.constrainer", &json!({"entities": ["c1"], "if_redundant": 5}));+ assert!(line.is_err_and(|e| e.to_string().contains("`if_redundant` must be text")));+ for (id, p) in [+ ("sketch.auto_constrain", json!({"tolerance": "0.1"})),+ ("sketch.auto_constrain", json!({"angle_tolerance": true})),+ ("sketch.auto_constrain", json!({"dimensions": "no"})),+ ("sketch.auto_constrain", json!({"datum": 3})),+ ("sketch.snap", json!({"at": [1, 1], "from": "x"})),+ ("sketch.snap", json!({"at": [1, 1], "radius": "1"})),+ ] {+ let e = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(e.contains("invalid parameters"), "{id} {p}: {e}");+ s.param_check = ParamCheck::Off;+ assert!(s.execute(id, &p).is_ok(), "{id} {p} works with the check off");+ s.param_check = ParamCheck::Strict;+ }+}++/// The schemas take what the handlers read: the keys they refuse when left out are required.+#[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}");+ }+ };+ check(+ input_schema_for::<CurvatureParams>(),+ &[+ (json!({"a": "c1", "b": "c2"}), true),+ (json!({"a": "c1", "b": "c2", "sketch": 3, "if_redundant": "refuse"}), true),+ (json!({"a": "c1"}), false),+ (json!({"b": "c1"}), false),+ (json!({"a": 1, "b": "c2"}), false),+ (json!({"a": "c1", "b": "c2", "sketch": -1}), false),+ (json!({"a": "c1", "b": "c2", "from": 1}), false),+ ],+ );+ check(+ input_schema_for::<PolygonParams>(),+ &[(json!({"lines": ["l1", "l2", "l3"]}), true), (json!({"lines": "l1", "sketch": "Sketch1"}), true), (json!({}), false)],+ );+ check(+ input_schema_for::<ConstrainerParams>(),+ &[(json!({"entities": ["l1"]}), true), (json!({"entities": "p1"}), true), (json!({}), false), (json!({"entities": [1]}), false)],+ );+ check(+ input_schema_for::<ToggleDrivenParams>(),+ &[(json!({"constraint": "k1"}), true), (json!({"constraint": "k1", "driven": false}), true), (json!({"driven": true}), false)],+ );+ check(+ input_schema_for::<SnapParams>(),+ &[+ (json!({"at": [1, 2]}), true),+ (json!({"at": {"x": 1, "y": 2}, "from": [0, 0], "radius": 2}), true),+ (json!({}), false),+ (json!({"at": [1, 2, 3]}), false),+ (json!({"at": [1, 2], "sketch": 1}), false),+ ],+ );+ for schema in+ [input_schema_for::<AutoConstrainParams>(), input_schema_for::<AutoConstrainDatumParams>(), input_schema_for::<FinishAutoConstrainParams>()]+ {+ check(+ schema,+ &[+ (json!({}), true),+ (json!({"tolerance": 0.1, "angle_tolerance": 2, "dimensions": false, "datum": "p1", "sketch": 4}), true),+ (json!({"tolerance": "x"}), false),+ (json!({"dimension": true}), false),+ ],+ );+ }+ check(input_schema_for::<GlyphsParams>(), &[(json!({}), true), (json!({"sketch": "S"}), true), (json!({"curve": 1}), false)]);+}++/// Each key reads as its handler reads it: `null` is left out, a number is a whole sketch id,+/// and every key the handler takes in only some cases (`if_redundant`, `datum`) is still read.+#[test]+fn the_types_read_each_key_like_the_handlers() {+ fn parses<T: serde::de::DeserializeOwned>(v: Value) -> bool {+ serde_json::from_value::<T>(v).is_ok()+ }+ // `null` is a key left out, as every reader reads it.+ assert!(parses::<CurvatureParams>(json!({"a": null, "b": null, "sketch": null, "if_redundant": null})));+ assert!(parses::<PolygonParams>(json!({"lines": null, "sketch": null})));+ assert!(parses::<ConstrainerParams>(json!({"entities": null})));+ assert!(parses::<ToggleDrivenParams>(json!({"constraint": null, "driven": null})));+ assert!(parses::<SnapParams>(json!({"at": null, "from": null, "radius": null})));+ assert!(parses::<GlyphsParams>(json!({"sketch": null})));+ // A key left out is the handler's to refuse, with its own message.+ assert!(parses::<CurvatureParams>(json!({})) && parses::<PolygonParams>(json!({})) && parses::<SnapParams>(json!({})));+ // `sketch`: a whole number or text.+ for ok in [json!(3), json!("Sketch1"), json!("7")] {+ assert!(parses::<GlyphsParams>(json!({"sketch": ok})), "{ok}");+ }+ for bad in [json!(-1), json!(2.5), json!(true), json!([1]), json!({})] {+ assert!(!parses::<GlyphsParams>(json!({"sketch": bad})), "{bad}");+ }+ // Lists of names, as `string_list` reads them.+ assert!(parses::<PolygonParams>(json!({"lines": "l1"})) && parses::<PolygonParams>(json!({"lines": ["l1", "l2"]})));+ assert!(!parses::<PolygonParams>(json!({"lines": [1]})) && !parses::<ConstrainerParams>(json!({"entities": 5})));+ // Points: `[x, y]` or `{x, y}`.+ assert!(parses::<SnapParams>(json!({"at": [1, 2]})) && parses::<SnapParams>(json!({"at": {"x": 1, "y": 2}, "from": {"x": 0, "y": 0}})));+ assert!(!parses::<SnapParams>(json!({"at": [1, 2, 3]})) && !parses::<SnapParams>(json!({"at": [1, 1], "from": [1]})));+ // Numbers the handlers read as the default (zero, negative) are still numbers.+ assert!(+ parses::<SnapParams>(json!({"at": [1, 2], "radius": 0})) && parses::<AutoConstrainParams>(json!({"tolerance": -1, "angle_tolerance": 0}))+ );+ // `datum` and the tolerances are read by all three Auto Constrain commands.+ let p = json!({"datum": "p1", "tolerance": 1, "angle_tolerance": 2, "dimensions": false});+ assert!(parses::<AutoConstrainParams>(p.clone()) && parses::<AutoConstrainDatumParams>(p.clone()) && parses::<FinishAutoConstrainParams>(p));+}+#[test]fn toggle_diameter_reply_matches_its_schema() {let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };@@ -46,3 +248,181 @@ fn toggle_diameter_reply_matches_its_schema() {assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");}++fn matches(schema: schemars::Schema, r: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");+}++fn keys(r: &Value) -> Vec<&str> {+ r.as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default()+}++fn ids(v: &Value) -> Vec<String> {+ v.as_array().into_iter().flatten().filter_map(|x| x.as_str().map(str::to_string)).collect()+}++/// Every command, in every form its handler takes, replies as its output schema says in Warn+/// without a warning; a misspelt key still gets its warning and the reply still matches, and+/// strict refuses it.+#[test]+fn replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let run = |s: &mut Session, id: &str, p: Value| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ r+ };+ run(&mut s, "sketch.create", json!({"plane": "XY"}));+ let sketch = s.active_sketch.unwrap_or_default();+ let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0.5]]}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 5], [10, 6]]}))["curves"])[0].clone();++ // The constrainer: one line; two lines; the same again (redundant), by `sketch` as an id.+ let r = run(&mut s, "sketch.constrainer", json!({"entities": [a]}));+ matches(output_schema_for::<ConstrainerResult>(), &r);+ assert_eq!((r["type"].as_str(), keys(&r)), (Some("Horizontal"), vec!["constraint", "created", "sketch", "type"]), "{r}");+ assert!(r["sketch"]["solved"] == true && r["sketch"]["dof"].is_u64(), "{r}");+ let r = run(&mut s, "sketch.constrainer", json!({"entities": [a, b]}));+ assert_eq!(r["type"], "Parallel", "{r}");+ let r = run(&mut s, "sketch.constrainer", json!({"entities": a, "sketch": sketch}));+ matches(output_schema_for::<ConstrainerResult>(), &r);+ assert_eq!((r["redundant"].clone(), r["determined_by"].is_array()), (json!(true), true), "{r}");+ assert_eq!(keys(&r), vec!["constraint", "created", "determined_by", "redundant", "sketch", "type"], "{r}");+ let e = s.execute("sketch.constrainer", &json!({"entities": [a], "if_redundant": "Refuse"})).err().map(|e| e.to_string());+ assert!(e.is_some_and(|e| e.contains("over-constrain")));++ // Curvature continuity, and polygon.+ let l = ids(&run(&mut s, "sketch.line", json!({"points": [[-10, 0], [0, 0]], "infer": true}))["curves"])[0].clone();+ let sp =+ ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [format!("{l}.end"), [5, 2], [10, 6], [15, 15]]}))["curves"])[0].clone();+ let r = run(&mut s, "sketch.constraint.curvature", json!({"a": l, "b": sp, "if_redundant": "keep"}));+ matches(output_schema_for::<ConstraintAdded>(), &r);+ assert_eq!(keys(&r), vec!["constraint", "created", "sketch"], "{r}");+ let r = run(&mut s, "sketch.constraint.curvature", json!({"a": l, "b": sp}));+ matches(output_schema_for::<ConstraintAdded>(), &r);+ assert_eq!(r["redundant"], true, "{r}");+ let quad = ids(&run(&mut s, "sketch.line", json!({"points": [[100, 0], [111, 1], [110, 9], [99, 10]], "closed": true}))["curves"]);+ let r = run(&mut s, "sketch.constraint.polygon", json!({"lines": quad}));+ matches(output_schema_for::<PolygonResult>(), &r);+ assert_eq!((r["constraints"].as_array().map(Vec::len), keys(&r)), (Some(7), vec!["constraints", "created", "sketch"]), "{r}");++ // Glyphs, snaps.+ let g = run(&mut s, "sketch.glyphs", json!({}));+ matches(output_schema_for::<GlyphsResult>(), &g);+ assert!(g["glyphs"].as_array().is_some_and(|l| l.len() > 5) && g["glyphs"][0]["at"].is_array(), "{g}");+ assert_eq!(keys(&g["glyphs"][0]), vec!["at", "dimension", "driven", "failing", "id", "name", "param", "redundant", "value"], "{g}");+ assert_eq!(keys(&g), vec!["conflicts", "dof", "fully_constrained", "glyphs", "sketch"], "{g}");+ let g = run(&mut s, "sketch.glyphs", json!({"sketch": sketch}));+ matches(output_schema_for::<GlyphsResult>(), &g);+ for p in [+ json!({"at": [0.2, 0.1]}),+ json!({"at": {"x": 5, "y": 0.3}, "radius": 1}),+ json!({"at": [15.5, 6], "from": [0, 6.2], "radius": 2}),+ json!({"at": [3.2, 5], "from": [3, 20], "radius": 1.5}),+ json!({"at": [3, 3], "from": null}),+ ] {+ let r = run(&mut s, "sketch.snap", p.clone());+ matches(output_schema_for::<SnapResult>(), &r);+ assert_eq!(keys(&r), vec!["snaps"], "{r}");+ }+ let snaps: Vec<String> = [+ json!({"at": [0.2, 0.1]}),+ json!({"at": [5.1, 0.3]}),+ json!({"at": [3, 5.2]}),+ json!({"at": [3.4, 50], "from": [3, 51], "radius": 1}),+ json!({"at": [3.4, 50], "from": [3.9, 53], "radius": 1}),+ json!({"at": [40, 10.4], "from": [30, 10], "radius": 1}),+ ]+ .into_iter()+ .flat_map(|p| {+ let r = run(&mut s, "sketch.snap", p);+ matches(output_schema_for::<SnapResult>(), &r);+ r["snaps"].as_array().cloned().unwrap_or_default().into_iter().filter_map(|x| x["type"].as_str().map(str::to_string)).collect::<Vec<_>>()+ })+ .collect();+ for kind in ["coincident", "midpoint", "on_curve", "horizontal", "vertical"] {+ assert!(snaps.iter().any(|k| k == kind), "no {kind} in {snaps:?}");+ }+ let r = run(&mut s, "sketch.snap", json!({"at": [5.1, 0.3]}));+ assert!(r["snaps"][0]["curve"].is_string() && r["snaps"][0]["at"].is_array(), "{r}");+ // The end of `a` (made horizontal above) alone: the coincident snap names that point.+ let r = run(&mut s, "sketch.snap", json!({"at": [10.2, 0.1], "radius": 0.5}));+ let first = &r["snaps"][0];+ assert_eq!((first["type"].as_str(), first["point"].as_str()), (Some("coincident"), Some(format!("{a}.end").as_str())), "{r}");++ // A dimension, driven and driving again.+ let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": 5}))["curves"])[0].clone();+ let d = run(&mut s, "sketch.dimension", json!({"entities": [c]}));+ let g = run(&mut s, "sketch.glyphs", json!({}));+ let did = g["glyphs"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|x| x["param"] == d["param"])+ .and_then(|x| x["id"].as_str())+ .unwrap_or_default()+ .to_string();+ assert!(!did.is_empty(), "{g}");+ let dimension = g["glyphs"].as_array().into_iter().flatten().find(|x| x["id"] == json!(did)).cloned().unwrap_or_default();+ assert!(dimension["value"].is_number() && dimension["dimension"] == true, "{dimension}");+ for p in [json!({"constraint": did}), json!({"constraint": did, "driven": false}), json!({"constraint": did, "driven": true, "sketch": null})] {+ let r = run(&mut s, "sketch.toggle_driven", p);+ matches(output_schema_for::<ToggleDrivenResult>(), &r);+ assert_eq!(keys(&r), vec!["constraint", "created", "driven", "sketch"], "{r}");+ }+ let r = s.execute("sketch.toggle_driven", &json!({"constraint": did, "drivn": true})).unwrap_or_else(|e| panic!("{e}"));+ assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");+ matches(output_schema_for::<ToggleDrivenResult>(), &r);++ // Auto Constrain: with the default options, with every option, from a datum, and finishing.+ run(&mut s, "sketch.point", json!({"point": [5, 5], "id": "d"}));+ for (id, p) in [+ ("sketch.auto_constrain", json!({})),+ ("sketch.auto_constrain", json!({"tolerance": 0.05, "angle_tolerance": 2, "dimensions": false, "datum": "origin", "sketch": null})),+ ("sketch.auto_constrain_from_datum", json!({"datum": "d"})),+ ("sketch.auto_constrain_from_datum", json!({})),+ ] {+ let r = run(&mut s, id, p);+ matches(output_schema_for::<AutoConstrainResult>(), &r);+ assert_eq!(keys(&r), vec!["added", "created", "dof", "sketch"], "{r}");+ }+ let r = run(&mut s, "sketch.finish_auto_constrain", json!({"datum": "d", "tolerance": 0.02}));+ matches(output_schema_for::<AutoConstrainResult>(), &r);+ assert!(s.active_sketch.is_none() && r["dof"] == 0, "{r}");++ // More forms, still without a warning: a sketch by name, `from` as an object, `if_redundant`+ // on a constraint that is not redundant, Finish with every option.+ let mut t = editing(ParamCheck::Warn);+ let tname = t.doc.features.first().map(|f| f.name.clone()).unwrap_or_default();+ let tline = ids(&run(&mut t, "sketch.line", json!({"points": [[0, 30], [10, 30.5]]}))["curves"])[0].clone();+ run(&mut t, "sketch.glyphs", json!({"sketch": tname}));+ run(&mut t, "sketch.snap", json!({"at": [1, 1], "from": {"x": 0, "y": 1}}));+ run(&mut t, "sketch.constrainer", json!({"entities": [tline], "if_redundant": "refuse", "sketch": tname}));+ let r = run(&mut t, "sketch.finish_auto_constrain", json!({"sketch": tname, "dimensions": false, "angle_tolerance": 3}));+ matches(output_schema_for::<AutoConstrainResult>(), &r);++ // A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.+ let mut s = editing(ParamCheck::Warn);+ let p = json!({"tolerence": 0.1});+ let r = s.execute("sketch.auto_constrain", &p).unwrap_or_else(|e| panic!("{e}"));+ assert!(+ r["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|w| w.contains("did you mean `tolerance`"))),+ "{r}"+ );+ matches(output_schema_for::<AutoConstrainResult>(), &r);+ // A new line the constrainer can still act on.+ let line = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 20.5]]}))["curves"])[0].clone();+ for (id, p, reply) in [+ ("sketch.snap", json!({"at": [1, 1], "radious": 2}), output_schema_for::<SnapResult>()),+ ("sketch.glyphs", json!({"sketch_id": 1}), output_schema_for::<GlyphsResult>()),+ ("sketch.constrainer", json!({"entities": [line], "if_redundent": "refuse"}), output_schema_for::<ConstrainerResult>()),+ ] {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{id}: {r}");+ matches(reply, &r);+ }+ s.param_check = ParamCheck::Strict;+ let e = s.execute("sketch.snap", &json!({"at": [1, 1], "radious": 2})).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(e.contains("`radious`") && e.contains("`radius`"), "{e}");+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex b6c296749e..f68f1f8250 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -63,14 +63,9 @@ sheet.export_bend_tablesheet.export_dxfsheet.flat_patternsheet.path_flange-sketch.auto_constrain-sketch.auto_constrain_from_datumsketch.auto_projectsketch.break_linksketch.chain-sketch.constrainer-sketch.constraint.curvature-sketch.constraint.polygonsketch.constructionsketch.createsketch.delete@@ -80,9 +75,7 @@ sketch.dragsketch.drag_endsketch.draw.dimensionedsketch.export_dxf-sketch.finish_auto_constrainsketch.fit_curves_to_section-sketch.glyphssketch.include_3dsketch.insert_dxfsketch.insert_svg@@ -103,10 +96,8 @@ sketch.rectangle.three_pointsketch.rectangle.two_pointsketch.slot.center_to_centersketch.slot.overall-sketch.snapsketch.solvesketch.spun_profile-sketch.toggle_drivensolid.alignsolid.chamfersolid.coil