joint.inspect: show agents what each joint is attached to (#3453)
* joint.inspect: what each joint is attached to, for agents
A read-only `joint.inspect {joint?}` gives each joint's definition: for each
side the occurrence, its component and path, the snap as saved, and what
each persistent face/edge name refers to (the feature that made it, and the
sketch and curve a swept side came from), whether the origin resolves and
why not; plus kind, offset, angle, flip, values with limits, expressions,
the motion links it is in, and its solve errors and conflicts. Its id ends
in `.inspect`, so agent gates treat it as reading only.
MCP `inspect_design` includes the definitions when the design has joints
(`joints: false` leaves them out). joint.list and joint.inspect share the
motion-link JSON.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* i18n: catalog entries for Inspect Joint (en, ja, zh)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -455,6 +455,7 @@
|
||||
"cmd.joint_drive": "Drive Joints",
|
||||
"cmd.joint_edit": "Edit Joint",
|
||||
"cmd.joint_gear": "Gear",
|
||||
"cmd.joint_inspect": "Inspect Joint",
|
||||
"cmd.joint_limits": "Joint Limits",
|
||||
"cmd.joint_list": "List Joints",
|
||||
"cmd.joint_motion_link": "Motion Link",
|
||||
|
||||
@@ -455,6 +455,7 @@
|
||||
"cmd.joint_drive": "ジョイントを駆動",
|
||||
"cmd.joint_edit": "ジョイントを編集",
|
||||
"cmd.joint_gear": "ギア",
|
||||
"cmd.joint_inspect": "ジョイントを検査",
|
||||
"cmd.joint_limits": "ジョイントの制限",
|
||||
"cmd.joint_list": "ジョイントを一覧表示",
|
||||
"cmd.joint_motion_link": "モーション リンク",
|
||||
|
||||
@@ -455,6 +455,7 @@
|
||||
"cmd.joint_drive": "驱动接头",
|
||||
"cmd.joint_edit": "编辑接头",
|
||||
"cmd.joint_gear": "齿轮",
|
||||
"cmd.joint_inspect": "检查接头",
|
||||
"cmd.joint_limits": "接头限制",
|
||||
"cmd.joint_list": "列出接头",
|
||||
"cmd.joint_motion_link": "运动关联",
|
||||
|
||||
@@ -15,6 +15,9 @@ use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, num, str_, vec3};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[path = "joints_inspect.rs"]
|
||||
mod inspect;
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params(
|
||||
"name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",
|
||||
@@ -80,6 +83,15 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \
|
||||
(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",
|
||||
),
|
||||
CommandSpec::new("joint.inspect", "Inspect Joint", inspect::inspect).icon("inspect").noundo().params(
|
||||
"joint?: id|name (default: every joint) → joints: [{id, name, type, suppressed, visible, flip, offset (mm), angle (deg), values: as joint.list \
|
||||
gives them, dofs, expressions?: {offset?, angle?, values?}, a, b: {occurrence, occurrence_name, component, component_name, path \
|
||||
(occurrence names from the top, `/` between), snap (as saved: type, pick, face, end, edge, corner, x, point, z, in the component's \
|
||||
coordinates), references: [{role: face|end|x|edge|corner, name, role_in_feature?: (top, side:c1…), feature?: {id, name, type} (the feature that made the face; \
|
||||
error when it is gone), sketch?: {id, name, curve, curve_type} (a face swept from a sketch curve), faces?: [an edge's two faces], \
|
||||
unverified?: a name saved before exact names}], resolves, frame?: {origin, z, x} in the world, error?: why the origin is lost}, \
|
||||
links: [{index, role: driver|driven, …as joint.list}], errors, conflicts}] (reads only: nothing changes)",
|
||||
),
|
||||
CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),
|
||||
CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params(
|
||||
"bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms",
|
||||
@@ -1319,33 +1331,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
let links: Vec<Value> = s
|
||||
.doc
|
||||
.assembly
|
||||
.links
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let angle = is_angle(s, l.b, l.ib);
|
||||
let offset = if angle { l.offset.to_degrees() } else { l.offset };
|
||||
let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);
|
||||
let mut v =
|
||||
json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});
|
||||
if let Some(c) = &l.coupling {
|
||||
v["coupling"] = json!(c);
|
||||
if let Some(Err(e)) = joints::coupling_values(&s.doc, &st, l) {
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
}
|
||||
// A cam's follower follows its table, not a ratio: its travel instead.
|
||||
if matches!(l.coupling, Some(Coupling::Cam(_)))
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.remove("ratio");
|
||||
o.insert("lift".into(), lift_json(l, angle));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let links: Vec<Value> = s.doc.assembly.links.iter().map(|l| link_json(s, &st, l)).collect();
|
||||
let origins: Vec<Value> = s.doc.assembly.origins.iter().map(|o| json!({"name": o.name, "occurrence": o.origin.occurrence})).collect();
|
||||
let mut out = sol_json(&sol, p);
|
||||
out["joints"] = json!(js);
|
||||
@@ -1355,6 +1341,29 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A motion link as `joint.list` and `joint.inspect` give it: ratio per degree, offset in b's
|
||||
/// units, a coupling's definition (and why it can't be worked out), a cam's lift in place of a ratio.
|
||||
fn link_json(s: &Session, st: &solidcraft_doc::ModelState, l: &MotionLink) -> Value {
|
||||
let angle = is_angle(s, l.b, l.ib);
|
||||
let offset = if angle { l.offset.to_degrees() } else { l.offset };
|
||||
let ratio = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);
|
||||
let mut v = json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});
|
||||
if let Some(c) = &l.coupling {
|
||||
v["coupling"] = json!(c);
|
||||
if let Some(Err(e)) = joints::coupling_values(&s.doc, st, l) {
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
}
|
||||
// A cam's follower follows its table, not a ratio: its travel instead.
|
||||
if matches!(l.coupling, Some(Coupling::Cam(_)))
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.remove("ratio");
|
||||
o.insert("lift".into(), lift_json(l, angle));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sol = resolve(s);
|
||||
Ok(sol_json(&sol, p))
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Inspect Joint (`joint.inspect`): what each joint is defined by and attached to — its two
|
||||
//! origins (the occurrence, the snap as saved, and the feature, face, edge or sketch curve each
|
||||
//! persistent name refers to), whether each origin is found today and why not, its kind, offset,
|
||||
//! angle, flip, limits, values, expressions and the motion links it takes part in. Reads only.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef};
|
||||
use solidcraft_doc::naming::{legacy_name, strip_piece};
|
||||
use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState};
|
||||
|
||||
use super::{component_of, joint_id, link_json, named_values, occurrence_name};
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "joint.inspect";
|
||||
let ids: Vec<u64> = match p.get("joint") {
|
||||
None | Some(Value::Null) => s.doc.assembly.joints.iter().map(|j| j.id).collect(),
|
||||
v => vec![joint_id(s, v, cmd)?],
|
||||
};
|
||||
let st = s.model.state();
|
||||
let sol = joints::solve(&s.doc, &st);
|
||||
let vals = joints::joint_values(&s.doc.assembly);
|
||||
let out: Vec<Value> = ids
|
||||
.iter()
|
||||
.filter_map(|id| s.doc.assembly.joints.iter().find(|j| j.id == *id))
|
||||
.map(|j| {
|
||||
let q = vals.get(&j.id).map(Vec::as_slice).unwrap_or(&j.values);
|
||||
joint_json(s, &st, &sol, j, q)
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "joints": out }))
|
||||
}
|
||||
|
||||
fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> Value {
|
||||
let links: Vec<Value> = s
|
||||
.doc
|
||||
.assembly
|
||||
.links
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, l)| l.a == j.id || l.b == j.id)
|
||||
.map(|(i, l)| {
|
||||
let mut v = link_json(s, st, l);
|
||||
v["index"] = json!(i);
|
||||
v["role"] = json!(if l.b == j.id { "driven" } else { "driver" });
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let why = |list: &[(u64, String, String)]| list.iter().filter(|(id, ..)| *id == j.id).map(|(.., why)| why.clone()).collect::<Vec<_>>();
|
||||
let mut v = json!({
|
||||
"id": j.id,
|
||||
"name": j.name,
|
||||
"type": j.kind,
|
||||
"suppressed": j.suppressed,
|
||||
"visible": s.joint_visible(j.id),
|
||||
"flip": j.flip,
|
||||
"offset": j.offset,
|
||||
"angle": j.angle.to_degrees(),
|
||||
"values": named_values(j, q),
|
||||
"dofs": j.kind.dofs(),
|
||||
"a": side_json(s, st, &j.a),
|
||||
"b": side_json(s, st, &j.b),
|
||||
"links": links,
|
||||
"errors": why(&sol.errors),
|
||||
"conflicts": why(&sol.conflicts),
|
||||
});
|
||||
if !j.exprs.is_empty() {
|
||||
v["expressions"] = json!(j.exprs);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// One of a joint's origins: what it sits on, what it refers to, and where it is now.
|
||||
fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value {
|
||||
let component = component_of(s, o.occurrence);
|
||||
let component_name = if component == 0 {
|
||||
"root".to_string()
|
||||
} else {
|
||||
s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default()
|
||||
};
|
||||
let occurrence_name = if o.occurrence == 0 { "root".to_string() } else { occurrence_name(s, o.occurrence) };
|
||||
let mut v = json!({
|
||||
"occurrence": o.occurrence,
|
||||
"occurrence_name": occurrence_name,
|
||||
"component": component,
|
||||
"component_name": component_name,
|
||||
"path": occurrence_path(&s.doc, o.occurrence),
|
||||
"snap": o.snap,
|
||||
"references": references(&s.doc, &o.snap),
|
||||
});
|
||||
match s.doc.origin_world(st, o) {
|
||||
Ok(m) => {
|
||||
v["resolves"] = json!(true);
|
||||
v["frame"] = json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]], "x": [m[0][0], m[0][1], m[0][2]]});
|
||||
}
|
||||
Err(e) => {
|
||||
v["resolves"] = json!(false);
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The occurrence names from the top of the assembly down to `occurrence` (`/` between); a
|
||||
/// nested component's parent is taken at its first placement. Empty for the root.
|
||||
fn occurrence_path(doc: &Document, occurrence: u64) -> String {
|
||||
let mut names = Vec::new();
|
||||
let mut id = occurrence;
|
||||
for _ in 0..=MAX_PLACEMENT_DEPTH {
|
||||
let Some(o) = doc.occurrences.iter().find(|o| o.id == id) else { break };
|
||||
names.push(o.name.as_str());
|
||||
let Some(parent) = (o.parent != 0).then(|| doc.occurrence_of(o.parent)).flatten() else { break };
|
||||
id = parent.id;
|
||||
}
|
||||
names.reverse();
|
||||
names.join("/")
|
||||
}
|
||||
|
||||
/// Every persistent name the snap holds, with what it refers to.
|
||||
fn references(doc: &Document, snap: &Snap) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
let mut face = |role: &str, name: &Option<String>| {
|
||||
if let Some(n) = name {
|
||||
out.push(with_role(role, face_ref(doc, n)));
|
||||
}
|
||||
};
|
||||
match snap {
|
||||
Snap::FaceCenter { face: f, x, .. } => {
|
||||
face("face", f);
|
||||
if let Some(XRef::Face { face: n, .. }) = x {
|
||||
face("x", &Some(n.clone()));
|
||||
}
|
||||
}
|
||||
Snap::CircleCenter { face: f, end, x, .. } => {
|
||||
face("face", f);
|
||||
face("end", end);
|
||||
if let Some(XRef::Face { face: n, .. }) = x {
|
||||
face("x", &Some(n.clone()));
|
||||
}
|
||||
}
|
||||
Snap::Edge { edge, face: f, corner, .. } => {
|
||||
if let Some(e) = edge {
|
||||
out.push(with_role("edge", edge_ref(doc, e)));
|
||||
}
|
||||
if let Some(n) = f {
|
||||
out.push(with_role("face", face_ref(doc, n)));
|
||||
}
|
||||
if let Some(e) = corner {
|
||||
out.push(with_role("corner", edge_ref(doc, e)));
|
||||
}
|
||||
}
|
||||
Snap::Frame { .. } | Snap::Point { .. } => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn with_role(role: &str, mut v: Value) -> Value {
|
||||
v["role"] = json!(role);
|
||||
v
|
||||
}
|
||||
|
||||
/// What a face's persistent name refers to: `F<feature>:<role>` names the feature that made the
|
||||
/// face, and a side `side:<curve>` (or a later profile's `side:s<k>.<curve>`) the sketch curve
|
||||
/// it was swept from. Names of another form are given as they are.
|
||||
fn face_ref(doc: &Document, name: &str) -> Value {
|
||||
let mut v = json!({ "name": name });
|
||||
let bare = match legacy_name(name) {
|
||||
Some(n) => {
|
||||
v["unverified"] = json!(true);
|
||||
n
|
||||
}
|
||||
None => name,
|
||||
};
|
||||
let stem = strip_piece(bare);
|
||||
let Some((fid, role)) = stem.strip_prefix('F').and_then(|r| r.split_once(':')).and_then(|(id, role)| Some((id.parse::<u64>().ok()?, role)))
|
||||
else {
|
||||
return v;
|
||||
};
|
||||
v["role_in_feature"] = json!(role);
|
||||
let Some(f) = doc.feature(fid) else {
|
||||
v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")});
|
||||
return v;
|
||||
};
|
||||
v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()});
|
||||
if let Some(curve) = role.strip_prefix("side:") {
|
||||
// A later profile's side is `s<k>.<curve>`.
|
||||
let curve = curve
|
||||
.split_once('.')
|
||||
.filter(|(k, _)| k.strip_prefix('s').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
|
||||
.map_or(curve, |(_, c)| c);
|
||||
let found = f.kind.input_sketches().into_iter().find_map(|id| {
|
||||
let sk = doc.sketch(id).ok()?;
|
||||
let c = sk.curves.iter().find(|c| c.id == curve)?;
|
||||
let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null);
|
||||
let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type}))
|
||||
});
|
||||
v["sketch"] = found.unwrap_or_else(|| json!({"curve": curve, "error": format!("no sketch of {} has a curve `{curve}`", f.name)}));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// An edge's persistent name (`<face A>|<face B>`, `~k` for one of several between them) with
|
||||
/// what each of its faces refers to.
|
||||
fn edge_ref(doc: &Document, name: &str) -> Value {
|
||||
let bare = legacy_name(name).unwrap_or(name);
|
||||
let bare = bare.rsplit_once('~').filter(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())).map_or(bare, |(e, _)| e);
|
||||
// Split at the `|` outside a piece's `#[…]`.
|
||||
let mut depth = 0i32;
|
||||
let split = bare.char_indices().find(|(_, c)| {
|
||||
match c {
|
||||
'[' => depth += 1,
|
||||
']' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
*c == '|' && depth == 0
|
||||
});
|
||||
let faces: Vec<Value> = match split {
|
||||
Some((i, _)) => [bare.get(..i), bare.get(i + 1..)].into_iter().flatten().map(|f| face_ref(doc, f)).collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let mut v = json!({"name": name, "faces": faces});
|
||||
if legacy_name(name).is_some() {
|
||||
v["unverified"] = json!(true);
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -1523,3 +1523,122 @@ fn interference_of_a_headed_pin_made_before_its_plate() {
|
||||
let got = i["interferences"][0]["volume_mm3"].as_f64().unwrap_or(0.0);
|
||||
assert!((got - want).abs() < 1e-6 * want, "{got} against {want}: {i}");
|
||||
}
|
||||
|
||||
/// A grounded Base (a 40 x 40 x 10 box), a Pin extruded 20 mm from the sketch circle `c1` of
|
||||
/// `PinSketch` (r5 at x = 100) and a Cap box; a revolute Hinge from the Base's top to the Pin's
|
||||
/// top rim, its offset the parameter `gap`, and a rigid Fix between two points of Base and Cap.
|
||||
fn hinge_and_fix() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "gap", "expression": "2 mm"}));
|
||||
run(&mut s, "component.create", json!({"name": "Base"}));
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [0, 0, 0]}));
|
||||
let base = occ(&s, "Base");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Pin"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "PinSketch"}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c1"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": 20}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Cap"}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "corner": [200, 0, 0]}));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({"type": "revolute", "name": "Hinge", "offset": "gap", "limits": [[-90, 90]],
|
||||
"a": {"occurrence": "Base", "face": [20, 20, 10]}, "b": {"occurrence": "Pin", "circle": [105, 0, 20]}}),
|
||||
);
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({"type": "rigid", "name": "Fix", "a": {"occurrence": "Base", "point": [0, 0, 0]}, "b": {"occurrence": "Cap", "point": [200, 0, 0]}}),
|
||||
);
|
||||
s
|
||||
}
|
||||
|
||||
/// The reference of `role` on side `side` of an inspected joint.
|
||||
fn reference<'a>(j: &'a Value, side: &str, role: &str) -> &'a Value {
|
||||
j[side]["references"].as_array().and_then(|r| r.iter().find(|r| r["role"] == role)).unwrap_or(&Value::Null)
|
||||
}
|
||||
|
||||
/// `joint.inspect` gives each joint's definition: its kind, offset (and the expression it
|
||||
/// follows), limits and values, and for each side the occurrence and component, the snap as
|
||||
/// saved, and what its face names refer to: a circle's wall back to the extrude and the sketch
|
||||
/// curve it was swept from.
|
||||
#[test]
|
||||
fn joint_inspect_gives_what_each_joint_is_attached_to() {
|
||||
let mut s = hinge_and_fix();
|
||||
let all = run(&mut s, "joint.inspect", json!({}));
|
||||
let joints = all["joints"].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(joints.iter().map(|j| j["name"].clone()).collect::<Vec<_>>(), [json!("Hinge"), json!("Fix")], "{all}");
|
||||
|
||||
let hinge = run(&mut s, "joint.inspect", json!({"joint": "Hinge"}))["joints"][0].clone();
|
||||
assert_eq!((&hinge["type"], &hinge["offset"], &hinge["expressions"]["offset"]), (&json!("revolute"), &json!(2.0), &json!("gap")), "{hinge}");
|
||||
assert_eq!(hinge["values"][0]["limits"], json!([-90.0, 90.0]), "{hinge}");
|
||||
assert_eq!(hinge["dofs"], json!(["angle"]));
|
||||
assert_eq!((&hinge["a"]["occurrence_name"], &hinge["a"]["component_name"]), (&json!("Base:1"), &json!("Base")), "{hinge}");
|
||||
assert_eq!(hinge["a"]["path"], hinge["a"]["occurrence_name"]);
|
||||
assert_eq!((&hinge["a"]["snap"]["type"], &hinge["b"]["snap"]["type"]), (&json!("face_center"), &json!("circle_center")), "{hinge}");
|
||||
assert_eq!((&hinge["a"]["resolves"], &hinge["b"]["resolves"]), (&json!(true), &json!(true)), "{hinge}");
|
||||
assert_eq!(hinge["b"]["component_name"], "Pin");
|
||||
// The Pin's wall: the extrude's side swept from PinSketch's c1.
|
||||
let wall = reference(&hinge, "b", "face");
|
||||
assert_eq!(wall["feature"]["type"], "ExtrudeFeature", "{hinge}");
|
||||
assert_eq!(
|
||||
(&wall["sketch"]["name"], &wall["sketch"]["curve"], &wall["sketch"]["curve_type"]),
|
||||
(&json!("PinSketch"), &json!("c1"), &json!("circle")),
|
||||
"{hinge}"
|
||||
);
|
||||
assert_eq!(wall["name"].as_str().map(|n| n.contains(":side:c1")), Some(true), "{hinge}");
|
||||
// The rim's end face is the extrude's top.
|
||||
assert_eq!(reference(&hinge, "b", "end")["feature"], wall["feature"], "{hinge}");
|
||||
// The Base's top: a face of its box, no sketch.
|
||||
assert!(reference(&hinge, "a", "face")["feature"]["id"].is_u64() && reference(&hinge, "a", "face")["sketch"].is_null(), "{hinge}");
|
||||
|
||||
let fix = &joints[1];
|
||||
assert_eq!((&fix["type"], &fix["values"], &fix["dofs"]), (&json!("rigid"), &json!([]), &json!([])), "{fix}");
|
||||
assert_eq!((&fix["b"]["snap"]["type"], &fix["b"]["snap"]["point"]), (&json!("point"), &json!([200.0, 0.0, 0.0])), "{fix}");
|
||||
assert_eq!(fix["b"]["references"], json!([]));
|
||||
assert!(fix.get("expressions").is_none(), "{fix}");
|
||||
|
||||
// A joint that isn't there is an error.
|
||||
assert!(s.execute("joint.inspect", &json!({"joint": "Nope"})).is_err());
|
||||
}
|
||||
|
||||
/// A joint whose sketch circle is replaced: its origin's face is gone, so it no longer
|
||||
/// resolves; the inspection says why and that its curve is no longer in the sketch.
|
||||
#[test]
|
||||
fn joint_inspect_reports_a_lost_origin() {
|
||||
let mut s = hinge_and_fix();
|
||||
run(&mut s, "sketch.edit", json!({"sketch": "PinSketch"}));
|
||||
run(&mut s, "sketch.delete", json!({"entities": ["c1"]}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [100, 0], "radius": 5, "id": "c2"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let hinge = run(&mut s, "joint.inspect", json!({"joint": "Hinge"}))["joints"][0].clone();
|
||||
assert_eq!(hinge["b"]["resolves"], false, "{hinge}");
|
||||
let wall = reference(&hinge, "b", "face");
|
||||
let name = wall["name"].as_str().unwrap_or_default();
|
||||
assert!(hinge["b"]["error"].as_str().is_some_and(|e| e.contains(name)), "{hinge}");
|
||||
assert_eq!(wall["sketch"]["curve"], "c1", "{hinge}");
|
||||
assert!(wall["sketch"]["error"].is_string(), "{hinge}");
|
||||
assert!(!hinge["errors"].as_array().is_none_or(Vec::is_empty), "the solve says so too: {hinge}");
|
||||
// The Base side is still found.
|
||||
assert_eq!(hinge["a"]["resolves"], true);
|
||||
}
|
||||
|
||||
/// `joint.inspect` reads only: no undo step, the design unchanged, and the id agents' gates
|
||||
/// treat as reading (`*.inspect`).
|
||||
#[test]
|
||||
fn joint_inspect_reads_only() {
|
||||
let mut s = hinge_and_fix();
|
||||
let spec = crate::cmd::command_specs().into_iter().find(|c| c.id == "joint.inspect");
|
||||
assert!(spec.is_some_and(|c| !c.undoable && c.tab.is_empty()));
|
||||
let undo = run(&mut s, "document.inspect", json!({}))["undo"].clone();
|
||||
let before = serde_json::to_value(&s.doc).unwrap_or_default();
|
||||
run(&mut s, "joint.inspect", json!({}));
|
||||
run(&mut s, "joint.inspect", json!({"joint": "Fix"}));
|
||||
assert_eq!(run(&mut s, "document.inspect", json!({}))["undo"], undo);
|
||||
assert_eq!(serde_json::to_value(&s.doc).unwrap_or_default(), before);
|
||||
}
|
||||
|
||||
@@ -294,6 +294,31 @@ fn parameters_drive_the_design() {
|
||||
assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 50.0), "{d}");
|
||||
}
|
||||
|
||||
/// `inspect_design` gives each joint's definition (as `joint.inspect`) when the design has
|
||||
/// joints, leaves the key out when it has none, and `joints: false` leaves them out.
|
||||
#[test]
|
||||
fn inspect_design_lists_joint_definitions() {
|
||||
let mut s = server();
|
||||
let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
|
||||
assert!(d.get("joints").is_none(), "{d}");
|
||||
for (name, corner) in [("A", [0, 0, 0]), ("B", [20, 0, 0])] {
|
||||
tool(&mut s, "execute", json!({"command": "component.activate", "params": {"component": "root"}}));
|
||||
tool(&mut s, "execute", json!({"command": "component.create", "params": {"name": name}}));
|
||||
tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": corner}}));
|
||||
}
|
||||
tool(
|
||||
&mut s,
|
||||
"execute",
|
||||
json!({"command": "joint.create", "params": {"type": "rigid", "name": "Glue", "a": {"occurrence": "A:1", "face": [5, 5, 10]}, "b": {"occurrence": "B:1", "face": [25, 5, 0]}}}),
|
||||
);
|
||||
let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));
|
||||
assert_eq!(d["joints"][0]["name"], "Glue", "{d}");
|
||||
assert_eq!(d["joints"][0]["a"]["snap"]["type"], "face_center", "{d}");
|
||||
assert_eq!(d["joints"][0]["b"]["resolves"], true, "{d}");
|
||||
let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false, "joints": false}));
|
||||
assert!(d.get("joints").is_none(), "{d}");
|
||||
}
|
||||
|
||||
/// `set_parameter` takes the new value as `value` or as `expression` (the name parameters.change
|
||||
/// uses), which it used to refuse instead of forwarding.
|
||||
#[test]
|
||||
|
||||
+11
-1
@@ -132,11 +132,14 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"The whole design: user parameters (expression, value, errors), the timeline (features with type, suppressed, \
|
||||
rolled back, error, warning, timing), bodies (volume, area, centre of mass, bounding box, face/edge/vertex \
|
||||
counts), sketches (curves with ids and coordinates, points, constraints, profiles, degrees of freedom, solve \
|
||||
status), the active sketch, selection and undo depth.",
|
||||
status), assembly joints (what each origin is attached to: occurrence, the feature, face, edge or sketch \
|
||||
curve its face names refer to, whether it resolves and why not; `execute` `joint.inspect {joint}` gives one), \
|
||||
the active sketch, selection and undo depth.",
|
||||
obj(
|
||||
json!({
|
||||
"measure": {"type": "boolean", "description": "Measure bodies (default true)"},
|
||||
"sketches": {"type": "boolean", "description": "Full sketch contents (default true; false = summary only)"},
|
||||
"joints": {"type": "boolean", "description": "Joint definitions as joint.inspect gives them, when the design has joints (default true)"},
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
@@ -416,6 +419,13 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map<String, Value>) -> Result<V
|
||||
.collect();
|
||||
d["sketches"] = Value::Array(full);
|
||||
}
|
||||
// Joints: what each is attached to (left out when there are none, or the app is older).
|
||||
if a.get("joints").and_then(Value::as_bool).unwrap_or(true)
|
||||
&& let Ok(j) = exec(b, "joint.inspect", json!({}))
|
||||
&& j["joints"].as_array().is_some_and(|v| !v.is_empty())
|
||||
{
|
||||
d["joints"] = j["joints"].clone();
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
"measure" => {
|
||||
|
||||
@@ -76,7 +76,7 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho
|
||||
| `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error |
|
||||
| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s |
|
||||
| `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled |
|
||||
| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection |
|
||||
| `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) |
|
||||
|
||||
Commands never open dialogs when run this way. `solidcraft-cli commands` prints the same registry.
|
||||
|
||||
|
||||
+1
-1
@@ -156,7 +156,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t
|
||||
| `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (`solid.box`, `solid.extrude` and `engine.describe` so far), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. |
|
||||
| `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. |
|
||||
| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`) and every result before it. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. |
|
||||
| `inspect_design` | `measure?` (default true), `sketches?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
|
||||
| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
|
||||
| `measure` | `body?` or `items?` | Volume (mm³), area (mm²), centre of mass, bbox and topology counts per body, with totals. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: see below. |
|
||||
| `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). |
|
||||
| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. |
|
||||
|
||||
Reference in New Issue
Block a user