Skip to content

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

Typed schemas for the standard views and Normal To (#10898) (#10899)

austin62jakefa1eb57e3b3d
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 8699e592fe..e9b4a84eb9 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -58,6 +58,7 @@ pub use sketch_create::{tangent_arc_preview, tangent_arc_starts_at};
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
+pub(crate) use view_navigation::camera_form;
pub use view_navigation::standard_view;
mod component_link;
pub use component_link::resolve_design_links;
diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs
index a068f6a7fc..1a9ec38c1b 100644
--- a/crates/engine/src/cmd/view_navigation.rs
+++ b/crates/engine/src/cmd/view_navigation.rs
@@ -4,13 +4,17 @@ use solidcraft_render::{Camera, StandardView};
use super::CommandSpec;
use crate::params::{bad, num, req_vec2, req_vec3, vec3};
-use crate::schema::view_navigation::{RenderBrowser, RenderFocus, RenderSelect, TabStep, TabStepParams};
+use crate::schema::view_navigation::{
+ CameraReply, NormalToParams, RenderBrowser, RenderFocus, RenderSelect, StandardViewParams, TabStep, TabStepParams,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Sel, Session};
const FOCUS_CONTRACT: TypedContract<RenderFocus> = TypedContract::new();
const BROWSER_CONTRACT: TypedContract<RenderBrowserRequest> = TypedContract::new();
const TAB_STEP_CONTRACT: TypedContract<TabStepParams> = TypedContract::new();
+const STANDARD_VIEW_CONTRACT: TypedContract<StandardViewParams> = TypedContract::new();
+const NORMAL_TO_CONTRACT: TypedContract<NormalToParams> = TypedContract::new();
// Both existing request forms share the Browser command and its published schema.
#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
@@ -107,18 +111,20 @@ CommandSpec::new("view.navigate", "Navigate View", navigate)
.noundo()
.doc_only()
.params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90), fit?: bool (frame the whole model from the new direction as well, as home does; default false); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), free_orbit?: bool (orbit through poles, default false), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?"),
-CommandSpec::new("view.normal_to", "Normal to Selection", normal_to)
+CommandSpec::new("view.normal_to", "Normal to Selection", crate::checked!("view.normal_to", normal_to))
.icon("camera")
.noundo()
.enabled(|s| normal_target(s).map(|_| ()).ok_or_else(|| "select a planar face or plane".into()))
+ .contract(&NORMAL_TO_CONTRACT)
+ .output(output_schema_for::<CameraReply>)
.params("camera?: Camera (default: current session camera or home view) → camera; Look At the first selected planar face or plane, centered on the picked point; repeat while aligned to flip the side; preserves scale and projection"),
-CommandSpec::new("view.front", "Front View", front).icon("camera").noundo().key("Ctrl+1").params(STANDARD_PARAMS),
-CommandSpec::new("view.back", "Back View", back).icon("camera").noundo().key("Ctrl+2").params(STANDARD_PARAMS),
-CommandSpec::new("view.left", "Left View", left).icon("camera").noundo().key("Ctrl+3").params(STANDARD_PARAMS),
-CommandSpec::new("view.right", "Right View", right).icon("camera").noundo().key("Ctrl+4").params(STANDARD_PARAMS),
-CommandSpec::new("view.top", "Top View", top).icon("camera").noundo().key("Ctrl+5").params(STANDARD_PARAMS),
-CommandSpec::new("view.bottom", "Bottom View", bottom).icon("camera").noundo().key("Ctrl+6").params(STANDARD_PARAMS),
-CommandSpec::new("view.isometric", "Isometric View", isometric).icon("camera").noundo().key("Ctrl+7").params(STANDARD_PARAMS),
+CommandSpec::new("view.front", "Front View", crate::checked!("view.front", front)).icon("camera").noundo().key("Ctrl+1").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.back", "Back View", crate::checked!("view.back", back)).icon("camera").noundo().key("Ctrl+2").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.left", "Left View", crate::checked!("view.left", left)).icon("camera").noundo().key("Ctrl+3").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.right", "Right View", crate::checked!("view.right", right)).icon("camera").noundo().key("Ctrl+4").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.top", "Top View", crate::checked!("view.top", top)).icon("camera").noundo().key("Ctrl+5").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.bottom", "Bottom View", crate::checked!("view.bottom", bottom)).icon("camera").noundo().key("Ctrl+6").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
+CommandSpec::new("view.isometric", "Isometric View", crate::checked!("view.isometric", isometric)).icon("camera").noundo().key("Ctrl+7").contract(&STANDARD_VIEW_CONTRACT).output(output_schema_for::<CameraReply>).params(STANDARD_PARAMS),
CommandSpec::new("view.next_tab", "Next Tab", crate::checked!("view.next_tab", next_tab))
.icon("chevron_right").noundo().doc_only().key("Ctrl+Tab").contract(&TAB_STEP_CONTRACT).output(output_schema_for::<TabStep>)
.params("no parameters → step: 1; the window shows the design tab to the right of the shown one (after the last, the first); never edits the design or opens a dialog"),
@@ -164,18 +170,36 @@ fn isometric(s: &mut Session, p: &Value) -> Result<Value> {
turn_to(s, p, "view.isometric")
}
+/// A view command's `camera` as its handler reads it: a [`Camera`] with finite fields, a positive
+/// distance and a field of view in [0, π). None for anything else, which the handlers refuse as
+/// "invalid camera" (and `CameraParam`, its contract type, too).
+pub(crate) fn camera_form(v: &Value) -> Option<Camera> {
+ serde_json::from_value::<Camera>(v.clone()).ok().filter(usable_camera)
+}
+
+fn usable_camera(cam: &Camera) -> bool {
+ cam.is_valid() && cam.fov.is_finite() && (0.0..std::f64::consts::PI).contains(&cam.fov)
+}
+
+/// The camera a view command turns: the one given, else the session's, else the home view.
+fn given_camera(s: &Session, p: &Value) -> Option<Camera> {
+ match p.get("camera") {
+ Some(value) => camera_form(value),
+ None => Some(s.camera.unwrap_or_else(|| crate::view::home_camera(s))).filter(usable_camera),
+ }
+}
+
+/// The reply of a view command that turned the camera to `camera`.
+fn camera_reply(cmd: &str, camera: Camera) -> Result<Value> {
+ serde_json::to_value(CameraReply { camera, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
+}
+
fn turn_to(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let view = standard_view(cmd).ok_or_else(|| bad(cmd, "not a standard view"))?;
- let mut cam: Camera = match p.get("camera") {
- Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "invalid camera"))?,
- None => s.camera.unwrap_or_else(|| crate::view::home_camera(s)),
- };
- if !cam.is_valid() || !cam.fov.is_finite() || !(0.0..std::f64::consts::PI).contains(&cam.fov) {
- return Err(bad(cmd, "invalid camera"));
- }
+ let mut cam = given_camera(s, p).ok_or_else(|| bad(cmd, "invalid camera"))?;
cam.set_view(view);
s.camera = Some(cam);
- Ok(json!({"camera": cam}))
+ camera_reply(cmd, cam)
}
fn normal_target(s: &Session) -> Option<(solidcraft_geom::Vec3, solidcraft_geom::Vec3)> {
@@ -210,25 +234,15 @@ fn status_details(s: &mut Session, p: &Value) -> Result<Value> {
fn normal_to(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "view.normal_to";
let (point, normal) = normal_target(s).ok_or_else(|| bad(cmd, "select a planar face or plane"))?;
- let cam: Camera = match p.get("camera") {
- Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "invalid camera"))?,
- None => s.camera.unwrap_or_else(|| crate::view::home_camera(s)),
- };
- if !cam.is_valid()
- || !cam.fov.is_finite()
- || !(0.0..std::f64::consts::PI).contains(&cam.fov)
- || cam.yaw.abs() > 1e6
- || cam.roll.abs() > 1e6
- || cam.pitch.abs() > std::f64::consts::FRAC_PI_2
- {
- return Err(bad(cmd, "invalid camera"));
- }
+ let cam = given_camera(s, p)
+ .filter(|cam| cam.yaw.abs() <= 1e6 && cam.roll.abs() <= 1e6 && cam.pitch.abs() <= std::f64::consts::FRAC_PI_2)
+ .ok_or_else(|| bad(cmd, "invalid camera"))?;
// Promoted from viewport::look_at_selection: asking again from the normal side flips it.
let direction = if cam.back().dot(normal) > 0.999 { -normal } else { normal };
let mut to = cam.looking_from(direction);
to.target = point;
s.camera = Some(to);
- Ok(json!({"camera": to}))
+ camera_reply(cmd, to)
}
// UI-owned settings follow the layout command: validate here, apply in the UI adapter.
diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs
index 43c9402f97..2964b4ba38 100644
--- a/crates/engine/src/schema/types.rs
+++ b/crates/engine/src/schema/types.rs
@@ -268,6 +268,40 @@ impl JsonSchema for AxisDir {
}
}
+/// A camera, as the view commands read it (`cmd::view_navigation::camera_form`): the render
+/// `Camera`, with finite fields, a positive distance and a field of view in [0, π), and the
+/// handlers' message, "invalid camera", for anything else (#10898).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CameraParam(pub solidcraft_render::Camera);
+
+impl<'de> Deserialize<'de> for CameraParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::camera_form(&Value::deserialize(d)?).map(CameraParam).ok_or_else(|| D::Error::custom(whole("invalid camera")))
+ }
+}
+
+impl JsonSchema for CameraParam {
+ fn schema_name() -> Cow<'static, str> {
+ "Camera".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A camera orbiting a target point, as the view commands give it back. Angles are in radians, measured in the frame of the up axis.",
+ "type": "object",
+ "properties": {
+ "target": {"description": "The point the camera looks at, in mm: [x, y, z].", "type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3},
+ "yaw": {"description": "Turn about the up axis; 0 looks along +Y, from the front.", "type": "number"},
+ "pitch": {"description": "Elevation above the ground plane, from -π/2 (looking up) to π/2 (looking down).", "type": "number"},
+ "roll": {"description": "Turn about the viewing direction; 0 keeps the up axis upright. Default: 0.", "type": "number", "default": 0.0},
+ "distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0},
+ "fov": {"description": "Vertical field of view; 0 is orthographic.", "type": "number", "minimum": 0, "exclusiveMaximum": std::f64::consts::PI},
+ "up": {"description": "The world's up axis. Default: z.", "enum": ["z", "y"], "default": "z"}
+ },
+ "required": ["target", "yaw", "pitch", "distance", "fov"]
+ })
+ }
+}
+
/// A sketch point in mm: `[x, y]` or `{x, y}` of finite numbers (read by `params::vec2`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Point2(pub Vec2);
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 8f1b9eaf48..c85ab61a9e 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -376,19 +376,11 @@ timeline.suppress
timeline.ungroup
view.ambient_occlusion
view.apply
-view.back
-view.bottom
view.delete
-view.front
view.graphics_preset
view.history_layout
-view.isometric
view.layout
-view.left
view.list
view.navigate
-view.normal_to
view.rename
-view.right
view.save
-view.top
diff --git a/crates/engine/src/schema/view_navigation.rs b/crates/engine/src/schema/view_navigation.rs
index 978e96760f..599426030b 100644
--- a/crates/engine/src/schema/view_navigation.rs
+++ b/crates/engine/src/schema/view_navigation.rs
@@ -4,6 +4,8 @@ use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::borrow::Cow;
+use super::types::{CameraParam, present};
+
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RenderDock {
@@ -74,6 +76,44 @@ pub struct AngleReadoutResult {
pub param_warnings: Vec<String>,
}
+/// Turn the view to the command's standard orientation (front, back, left, right, top, bottom
+/// or isometric), as the view cube does, keeping the camera's target, distance, projection and
+/// up axis. Display only: the design isn't changed and nothing is added to undo.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct StandardViewParams {
+ /// The camera to turn. Default: the session's camera, or the home view when there is none.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CameraParam")]
+ pub camera: Option<CameraParam>,
+}
+
+/// Look straight at the first selected planar face or plane, centred on the point it was picked
+/// at (a plane: its origin); asked again while already facing it, look from the other side.
+/// Keeps the camera's distance, projection and up axis. Needs a planar face or plane in the
+/// selection. Display only: the design isn't changed and nothing is added to undo.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct NormalToParams {
+ /// The camera to turn. Default: the session's camera, or the home view when there is none.
+ /// Its yaw and roll must also be within ±1e6 and its pitch within ±π/2.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CameraParam")]
+ pub camera: Option<CameraParam>,
+}
+
+/// What the standard views and `view.normal_to` return: the camera after the turn, which the
+/// session keeps as its view.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CameraReply {
+ /// The camera now.
+ #[schemars(with = "CameraParam")]
+ pub camera: solidcraft_render::Camera,
+ /// 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>,
+}
+
/// `view.next_tab` and `view.previous_tab` take no parameters (#8565).
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
diff --git a/crates/engine/src/schema/view_navigation_tests.rs b/crates/engine/src/schema/view_navigation_tests.rs
index 1abe2043f8..63de8d4bfc 100644
--- a/crates/engine/src/schema/view_navigation_tests.rs
+++ b/crates/engine/src/schema/view_navigation_tests.rs
@@ -1,13 +1,128 @@
use serde_json::{Value, json};
-use super::{AngleReadoutParams, TabStep, TabStepParams};
+use super::{AngleReadoutParams, CameraReply, NormalToParams, StandardViewParams, TabStep, TabStepParams};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::types::CameraParam;
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<AngleReadoutParams>(), &["enabled"]);
+ assert_keys(input_schema_for::<StandardViewParams>(), &["camera"]);
+ assert_keys(input_schema_for::<NormalToParams>(), &["camera"]);
+}
+
+const STANDARD_VIEWS: [&str; 7] = ["view.front", "view.back", "view.left", "view.right", "view.top", "view.bottom", "view.isometric"];
+
+/// A camera the view commands take, with `change` merged into it.
+fn camera(change: Value) -> Value {
+ let mut c = json!({"target": [1, 2, 3], "yaw": 0.3, "pitch": 0.4, "roll": 0, "distance": 150, "fov": 0, "up": "z"});
+ if let (Some(c), Some(change)) = (c.as_object_mut(), change.as_object()) {
+ c.extend(change.clone());
+ }
+ c
+}
+
+/// #10898: the camera type takes what the view commands' own reader takes, and its schema says
+/// the same.
+#[test]
+fn the_camera_type_matches_the_view_commands_reader() {
+ let schema = input_schema_for::<CameraParam>();
+ let schema = schema.as_value();
+ let without = |key: &str| {
+ let mut c = camera(json!({}));
+ c.as_object_mut().map(|o| o.remove(key));
+ c
+ };
+ for v in [
+ camera(json!({})),
+ camera(json!({"up": "y", "fov": 0.8})),
+ camera(json!({"pitch": -1.5, "yaw": 12.0, "roll": -3.0})),
+ camera(json!({"target": [0.5, -2, 1e6]})),
+ without("roll"),
+ without("up"),
+ camera(json!({"distance": 0})),
+ camera(json!({"distance": -5})),
+ camera(json!({"fov": std::f64::consts::PI})),
+ camera(json!({"fov": -0.1})),
+ camera(json!({"up": "x"})),
+ camera(json!({"up": "Z"})),
+ camera(json!({"target": [1, 2]})),
+ camera(json!({"target": {"x": 1, "y": 2, "z": 3}})),
+ camera(json!({"yaw": "0.3"})),
+ without("target"),
+ without("distance"),
+ without("fov"),
+ json!(null),
+ json!(5),
+ json!("front"),
+ json!([1, 2, 3]),
+ ] {
+ let read = crate::cmd::camera_form(&v).is_some();
+ assert_eq!(serde_json::from_value::<CameraParam>(v.clone()).is_ok(), read, "{v}");
+ assert_eq!(conforms(schema, schema, &v), read, "{v}");
+ }
+}
+
+#[test]
+fn standard_views_keep_todays_errors() {
+ let mut cases = Vec::new();
+ for id in STANDARD_VIEWS {
+ for c in [json!(5), json!(null), json!("top"), camera(json!({"distance": 0})), camera(json!({"fov": 4})), camera(json!({"up": "x"}))] {
+ cases.push((id, json!({ "camera": c })));
+ }
+ }
+ assert_strict_keeps_todays_errors(&cases);
+}
+
+/// A box with its top face selected, for Normal To.
+fn top_face_selected(check: ParamCheck) -> Session {
+ let mut s = Session { param_check: check, ..Session::default() };
+ s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("select.set", &json!({"items": [{"type": "face", "body": "Body1", "index": 1, "point": [20, 15, 20]}]}))
+ .unwrap_or_else(|e| panic!("{e}"));
+ s
+}
+
+/// #10898: every standard view and Normal To reply with the camera their output schema
+/// describes, with or without a camera given, and refuse in strict what they refuse anyway.
+#[test]
+fn camera_commands_reply_with_the_camera_schema() {
+ let schema = output_schema_for::<CameraReply>();
+ let schema = schema.as_value();
+ let check = |id: &str, r: &Value, warned: bool| {
+ assert!(conforms(schema, schema, r), "{id}: {r} doesn't match {schema}");
+ assert_eq!(r.get("param_warnings").is_some(), warned, "{id}: {r}");
+ assert!(crate::cmd::camera_form(&r["camera"]).is_some(), "{id}: the reply's camera is one the commands take: {r}");
+ };
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ for id in STANDARD_VIEWS {
+ for p in [json!({}), json!({"camera": camera(json!({}))}), json!({"camera": camera(json!({"up": "y", "fov": 0.6}))})] {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ check(id, &r, false);
+ if let Some(up) = p["camera"].get("up") {
+ assert_eq!(&r["camera"]["up"], up, "{id} keeps the up axis");
+ }
+ }
+ let r = s.execute(id, &json!({"camera": camera(json!({})), "zoom": 2})).unwrap_or_else(|e| panic!("{id}: {e}"));
+ check(id, &r, true);
+ }
+ let mut s = top_face_selected(ParamCheck::Warn);
+ for p in [json!({}), json!({"camera": camera(json!({}))})] {
+ let r = s.execute("view.normal_to", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ check("view.normal_to", &r, false);
+ }
+ let r = s.execute("view.normal_to", &json!({"zoom": 2})).unwrap_or_else(|e| panic!("{e}"));
+ check("view.normal_to", &r, true);
+ // Strict refuses what the handler refuses, with its message: a camera of the wrong form,
+ // and (the handler's own check) one whose angles are out of Normal To's bounds.
+ for c in [json!(5), json!(null), camera(json!({"distance": 0})), camera(json!({"yaw": 2e6})), camera(json!({"pitch": 2.0}))] {
+ let p = json!({ "camera": c });
+ let off = top_face_selected(ParamCheck::Off).execute("view.normal_to", &p).err().map(|e| e.to_string());
+ assert!(off.as_deref().is_some_and(|e| e.contains("invalid camera")), "{p}: {off:?}");
+ assert_eq!(top_face_selected(ParamCheck::Strict).execute("view.normal_to", &p).err().map(|e| e.to_string()), off, "{p}");
+ }
}
#[test]