From 2fd7b6f08d78c99d0b1f2e857e68decca97f623f Mon Sep 17 00:00:00 2001 From: raykholo Date: Sat, 24 Oct 2026 21:27:36 +0000 Subject: [PATCH] Measure: a face or edge picked by its point alone (#4099) (#4114) * claim: #4099 * Measure: a face or edge picked by its point alone (#4099) inspect.measure (and the MCP measure tool) refused a face or edge item without an index ("missing field `index`"). Face and edge items are now read as body + point with an optional index: the point finds the face (the same lookup face picking uses) or the nearest edge within the pick tolerance, before the selection is built. A missing body or a point on no face or edge is a clear error. Explicit indices still work. --- crates/engine/src/cmd/inspect.rs | 2 +- crates/engine/src/cmd/measure_sel.rs | 69 +++++++++++++++-------- crates/engine/src/measure_centre_tests.rs | 37 ++++++++++++ docs/mcp.md | 2 +- 4 files changed, 85 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 5df2299d6..67c90a6df 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -13,7 +13,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("measure") .key("I") .noundo() - .params("bodies?: [names] (default all); or items: [1-2 selections] → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"), + .params("bodies?: [names] (default all); or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"), CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements)"), CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).icon("inspect").noundo().params("sketch?: id|name (default active)"), CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"), diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index c1afa3e3f..a20ebe161 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -56,15 +56,19 @@ fn densify(pts: &[Vec3]) -> Vec { out } +/// How far `point` lies from the polyline `e`. +fn polyline_dist(e: &[Vec3], point: Vec3) -> f64 { + e.windows(2).map(|w| point.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min) +} + /// The mesh edge a selection means: by index if it still passes through the point, otherwise -/// the nearest. -fn edge_index(m: &Mesh, index: usize, point: Vec3) -> Option { - let near = |e: &Vec| e.windows(2).map(|w| point.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); +/// (or with no index) the nearest. +fn edge_index(m: &Mesh, index: Option, point: Vec3) -> Option { let tol = m.bounds().diagonal().max(1.0) * 1e-6; - if m.edges.get(index).is_some_and(|e| near(e) < tol) { + if let Some(index) = index.filter(|&i| m.edges.get(i).is_some_and(|e| polyline_dist(e, point) < tol)) { return Some(index); } - m.edges.iter().enumerate().min_by(|(_, a), (_, b)| near(a).total_cmp(&near(b))).map(|(i, _)| i) + m.edges.iter().enumerate().min_by(|(_, a), (_, b)| polyline_dist(a, point).total_cmp(&polyline_dist(b, point))).map(|(i, _)| i) } fn face_tris(m: &Mesh, f: usize) -> Vec<[Vec3; 3]> { @@ -279,7 +283,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { Sel::Edge { body, index, point } => { let b = st.body(body)?; let m = b.mesh(); - let index = edge_index(&m, *index, *point)?; + let index = edge_index(&m, Some(*index), *point)?; let pts = m.edges.get(index)?; let rim = m.circular_rim(index); if rim.len() > 1 { @@ -424,6 +428,38 @@ fn corner_cos(a: Shape, b: Shape) -> Option { Some((end_a - p).normalized()?.dot((end_b - q).normalized()?)) } +/// A face or edge as `inspect.measure` takes it: the body and a point on the item; `index` is +/// optional (the point finds the item). +#[derive(serde::Deserialize)] +struct Pick { + body: String, + point: Vec3, + #[serde(default)] + index: Option, +} + +/// Resolves a face or edge pick to the [`Sel`] it means, merging the two kernel halves of one +/// visible item (a split cylinder's patches, a circle's two arcs) into one measurement target. +fn resolve_pick(st: &solidcraft_doc::ModelState, face: bool, value: &Value) -> std::result::Result { + let Pick { body, point, index } = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; + let b = st.body(&body).ok_or_else(|| format!("no body named '{body}'"))?; + let m = b.mesh(); + if face { + let index = match index { + Some(i) => i, + None => solidcraft_doc::appearance::face_index_at(b, point).ok_or_else(|| format!("no face of '{body}' at the picked point"))?, + }; + let index = m.surface_patch(index).first().copied().unwrap_or(index); + return Ok(Sel::Face { body, index, point }); + } + let resolved = edge_index(&m, index, point) + .filter(|&i| index.is_some() || m.edges.get(i).is_some_and(|e| polyline_dist(e, point) <= solidcraft_doc::appearance::pick_tolerance(b))) + .or(index) + .ok_or_else(|| format!("no edge of '{body}' at the picked point"))?; + let index = m.circular_rim(resolved).first().copied().unwrap_or(resolved); + Ok(Sel::Edge { body, index, point }) +} + /// `inspect.measure` with `items` (one or two selections). pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { let cmd = "inspect.measure"; @@ -434,23 +470,10 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { let st = s.world_state(); let mut sels = Vec::new(); for value in list { - let mut sel = serde_json::from_value::(value.clone()).map_err(|e| bad(cmd, e.to_string()))?; - // Two kernel halves of one visible item are one measurement target. - match &mut sel { - Sel::Edge { body, index, point } => { - if let Some(b) = st.body(body) { - let m = b.mesh(); - let resolved = edge_index(&m, *index, *point).unwrap_or(*index); - *index = m.circular_rim(resolved).first().copied().unwrap_or(resolved); - } - } - Sel::Face { body, index, .. } => { - if let Some(b) = st.body(body) { - *index = b.mesh().surface_patch(*index).first().copied().unwrap_or(*index); - } - } - _ => {} - } + let sel = match value.get("type").and_then(Value::as_str) { + Some(kind @ ("face" | "edge")) => resolve_pick(&st, kind == "face", value).map_err(|e| bad(cmd, e))?, + _ => serde_json::from_value::(value.clone()).map_err(|e| bad(cmd, e.to_string()))?, + }; let duplicate = sels.iter().any(|x| match (x, &sel) { (Sel::Edge { body: a, index: i, .. }, Sel::Edge { body: b, index: j, .. }) | (Sel::Face { body: a, index: i, .. }, Sel::Face { body: b, index: j, .. }) => a == b && i == j, diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index f52209186..06fd112b3 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -386,3 +386,40 @@ fn combine_cut_volume_does_not_depend_on_placement() { assert!((v - here).abs() <= 1e-6 * here, "after a move by {by:?}: {v} vs {here} at the origin"); } } + +#[test] +fn box_faces_measure_by_point_only() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 20, "body_name": "Box"})); + for (point, area) in [([5.0, 5.0, 20.0], 100.0), ([10.0, 5.0, 10.0], 200.0)] { + let pick = json!({"type": "face", "body": "Box", "point": point}); + let r = measure(&mut s, vec![pick.clone()]); + assert!(close(&r["items"][0]["area_mm2"], area, 1e-9), "{r}"); + let index = solidcraft_doc::appearance::face_index_at(s.model.state().body("Box").unwrap(), Vec3::from(point)).unwrap(); + let mut indexed = pick.clone(); + indexed["index"] = json!(index); + assert_eq!(measure(&mut s, vec![indexed.clone()]), r); + assert_eq!(measure(&mut s, vec![pick, indexed]), r); + } + for pick in [ + json!({"type": "face", "body": "Missing", "point": [5, 5, 20]}), + json!({"type": "face", "body": "Box", "point": [100, 100, 100]}), + json!({"type": "face", "body": "Box"}), + ] { + assert!(s.execute("inspect.measure", &json!({"items": [pick]})).is_err()); + } +} + +#[test] +fn box_edges_measure_by_point_only() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 15, "height": 20, "body_name": "Box"})); + for (point, length) in [([5, 0, 0], 10.0), ([10, 15, 10], 20.0)] { + let pick = json!({"type": "edge", "body": "Box", "point": point}); + let r = measure(&mut s, vec![pick]); + assert!(close(&r["items"][0]["length_mm"], length, 1e-9), "{r}"); + } + for pick in [json!({"type": "edge", "body": "Missing", "point": [5, 0, 0]}), json!({"type": "edge", "body": "Box", "point": [100, 100, 100]})] { + assert!(s.execute("inspect.measure", &json!({"items": [pick]})).is_err()); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 6787ec5dc..a21dfd55c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -209,7 +209,7 @@ The `skill_reference` tool returns these documents from the copies built into So | `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`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps: such a batch fails before anything is sent. `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), `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. | +| `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: faces and edges need only `type`, `body` and `point`; `index` is optional. 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. | | `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. |