diff --git a/Cargo.lock b/Cargo.lock index 876d0c5..741144f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -480,6 +480,17 @@ dependencies = [ "cc", ] +[[package]] +name = "benchup-tools" +version = "0.7.1" +dependencies = [ + "benchup-core", + "flate2", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "bit-set" version = "0.10.0" diff --git a/Cargo.toml b/Cargo.toml index abe9c75..2e7c487 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "crates/benchup-core", "crates/benchup-io", "crates/benchup-skp", + "crates/benchup-tools", "crates/benchup-app", ] default-members = ["crates/benchup-app"] diff --git a/crates/benchup-tools/Cargo.toml b/crates/benchup-tools/Cargo.toml new file mode 100644 index 0000000..36d2589 --- /dev/null +++ b/crates/benchup-tools/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "benchup-tools" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Shared agent operations for BenchUp: tool definitions, executor and project files" + +[dependencies] +benchup-core = { path = "../benchup-core" } +serde.workspace = true +serde_json.workspace = true +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tempfile = "3" diff --git a/crates/benchup-tools/src/files.rs b/crates/benchup-tools/src/files.rs new file mode 100644 index 0000000..0704417 --- /dev/null +++ b/crates/benchup-tools/src/files.rs @@ -0,0 +1,125 @@ +//! `.bup` project files: gzip-compressed JSON of a [`Document`]. Plain JSON +//! (older files, recovery snapshots) is accepted when reading. +use benchup_core::{Document, tr}; +use flate2::{Compression, read::MultiGzDecoder, write::GzEncoder}; +use std::io::{Read, Write}; + +/// Serialize `doc` as the app does when saving, then compress it. +pub fn encode_document(doc: &Document) -> Result, String> { + let json = serde_json::to_string(doc).map_err(|error| error.to_string())?; + encode(&json) +} + +/// Project files use gzip-compressed JSON; recovery and save snapshots stay JSON. +pub fn encode(json: &str) -> Result, String> { + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder + .write_all(json.as_bytes()) + .and_then(|_| encoder.finish()) + .map_err(|error| tr!("project_files.could_not_compress_project", error = error)) +} + +pub fn decode(bytes: &[u8]) -> Result { + // Detect the content rather than the extension so all project extensions + // accept compressed files and older, plain JSON files unchanged. + let mut decompressed = Vec::new(); + let bytes: &[u8] = if bytes.starts_with(&[0x1f, 0x8b]) { + MultiGzDecoder::new(bytes) + .read_to_end(&mut decompressed) + .map_err(|error| tr!("project_files.could_not_decompress_project", error = error))?; + &decompressed + } else { + bytes + }; + let json = std::str::from_utf8(bytes).map_err(|_| tr!("project_files.the_project_is_not_utf_8_text"))?; + Document::from_json(json) +} + +/// Write `bytes` to `path` through a temporary file next to the real file and +/// a rename, so a crash never leaves a half-written project. A symlink is +/// followed (the link stays, its target is replaced) and an existing file's +/// permissions are kept. +#[cfg(not(target_arch = "wasm32"))] +pub fn save_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { + let existed = path.exists(); + let real = if existed { path.canonicalize().map_err(|e| e.to_string())? } else { path.to_path_buf() }; + let parent = real + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(std::path::Path::new(".")); + let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?; + temporary + .write_all(bytes) + .and_then(|_| temporary.as_file().sync_all()) + .map_err(|e| e.to_string())?; + if existed { + let permissions = std::fs::metadata(&real).map_err(|e| e.to_string())?.permissions(); + std::fs::set_permissions(temporary.path(), permissions).map_err(|e| e.to_string())?; + } else { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(temporary.path(), std::fs::Permissions::from_mode(0o644)) + .map_err(|e| e.to_string())?; + } + } + temporary.persist(&real).map_err(|e| e.to_string())?; + #[cfg(unix)] + if let Ok(dir) = std::fs::File::open(parent) { + let _ = dir.sync_all(); + } + Ok(()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn documents_round_trip_compressed_and_plain() { + let mut doc = Document::default(); + doc.name = "Bench".into(); + let bytes = encode_document(&doc).unwrap(); + assert!(bytes.starts_with(&[0x1f, 0x8b])); + assert_eq!(decode(&bytes).unwrap().name, "Bench"); + let plain = serde_json::to_vec(&doc).unwrap(); + assert_eq!(decode(&plain).unwrap().name, "Bench"); + } + + #[test] + fn corrupt_input_is_an_error_not_a_panic() { + assert!(decode(&[0x1f, 0x8b, 1, 2, 3]).is_err()); + assert!(decode(&[0xff, 0xfe]).is_err()); + assert!(decode(b"{}").is_err()); + } + + #[test] + fn save_atomic_replaces_the_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.bup"); + save_atomic(&path, b"one").unwrap(); + save_atomic(&path, b"two").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"two"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn save_atomic_follows_symlinks_and_keeps_mode() { + use std::os::unix::fs::{PermissionsExt, symlink}; + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real.bup"); + std::fs::write(&real, b"old").unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o640)).unwrap(); + let link = dir.path().join("link.bup"); + symlink(&real, &link).unwrap(); + save_atomic(&link, b"new").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&real).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&real).unwrap().permissions().mode() & 0o777, 0o640); + let fresh = dir.path().join("fresh.bup"); + save_atomic(&fresh, b"x").unwrap(); + assert_eq!(std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777, 0o644); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 3); + } +} diff --git a/crates/benchup-tools/src/lib.rs b/crates/benchup-tools/src/lib.rs new file mode 100644 index 0000000..bb61765 --- /dev/null +++ b/crates/benchup-tools/src/lib.rs @@ -0,0 +1,21 @@ +//! The operation layer shared by the in-app assistant and the MCP server. +//! +//! * [`ops`] defines the tools an agent may call and executes them against a +//! [`benchup_core::Model`]. Lengths are millimetres at the boundary and +//! metres inside the document; conversion happens in one place. Every +//! failure (bad arguments, unknown ids, limits, read-only or lease +//! violations) is returned as structured data so the caller can correct +//! itself, and a failed call never changes the model. +//! * [`scene`] describes the model compactly (summary, references, per-object +//! detail) for an agent to read. +//! * [`files`] reads and writes `.bup` project files (gzip-compressed JSON). +//! +//! The crate has no network or UI dependencies and builds for `wasm32`. +pub mod files; +pub mod ops; +pub mod scene; + +pub use ops::{ + Call, ToolDefinition, ToolEnv, ToolOutcome, definitions, execute, is_known, is_mutating, mcp_tools, + openai_tools, +}; diff --git a/crates/benchup-tools/src/ops.rs b/crates/benchup-tools/src/ops.rs new file mode 100644 index 0000000..14a41c5 --- /dev/null +++ b/crates/benchup-tools/src/ops.rs @@ -0,0 +1,1222 @@ +//! Tools an agent may call, and the executor that applies them to a `Model`. +//! Lengths are millimetres on the wire and metres in the document; conversion +//! happens only in `point`/`length` below. Every failure is reported as +//! structured data so the model can correct itself within the same turn. +use crate::scene::{self, from_mm}; +use benchup_core::{ + Axis, DVec3, MaterialId, Model, StockMaterial, + connections::{Connection, ConnectionOperation}, + inference::AxisConstraint, + joinery::{JointKind, JointSettings}, +}; +use serde::{Deserialize, de::DeserializeOwned}; +use serde_json::{Map, Value, json}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Per call; `entities` enforces it for every tool that takes an id list. +const MAX_IDS: usize = 500; +const MAX_POINTS: usize = 1000; +const MAX_TEXT_CHARS: usize = 500; +/// Input positions and sizes: |coordinate| <= 100 m. +const MAX_COORDINATE_MM: f64 = 1.0e5; +/// Results may add up (move after move), but must stay finite and within 1 km. +const MAX_RESULT_M: f64 = 1000.; +/// Longest tag name core accepts (`Model::add_tag` counts bytes). +const MAX_TAG_BYTES: usize = 128; +const MIN_SCALE: f64 = 1.0e-3; +const MAX_SCALE: f64 = 1.0e3; + +/// State shared by the tool calls of one turn. +#[derive(Default)] +pub struct ToolEnv { + /// Mutating tools refuse to run (shared project without edit access). + pub read_only: bool, + /// Current selection; the `select` tool rewrites it. + pub selection: BTreeSet, + /// The designer turned off "Include selection": `get_scene` and + /// `get_selection` must not reveal `selection`. + pub hide_selection: bool, + /// Purchasing catalog the model may assign. + pub catalog: BTreeMap, + /// Model as it was before the first successful mutating call. + pub before: Option, + /// Shared project: the edit lease this user holds. Mutating tools refuse + /// entities outside it. `None` means no restriction (not a shared project). + pub lease: Option>, + /// Entities this turn created (or released from a group it dissolved); + /// they are not held by anyone else, so they are exempt from the lease. + pub created: BTreeSet, +} + +pub struct ToolOutcome { + /// JSON text of this is sent back to the model. + pub result: Value, + pub ok: bool, + /// The scene (not just the editing scope or selection) changed. + pub mutated: bool, + pub created: Vec, + pub modified: Vec, + pub erased: Vec, + pub joints: Vec, +} + +struct Fail { + error: String, + hint: Option, +} +impl From<&str> for Fail { + fn from(error: &str) -> Self { + Self { error: error.into(), hint: None } + } +} +impl From for Fail { + fn from(error: String) -> Self { + Self { error, hint: None } + } +} +fn fail(error: impl Into, hint: impl Into) -> Fail { + Fail { error: error.into(), hint: Some(hint.into()) } +} + +#[derive(Default)] +struct Done { + created: Vec, + modified: Vec, + erased: Vec, + joints: Vec, + extra: Map, +} +type Res = Result; + +fn modified(ids: &BTreeSet) -> Done { + Done { modified: ids.iter().copied().collect(), ..Default::default() } +} + +/// (name, mutating) +const TOOLS: &[(&str, bool)] = &[ + ("get_scene", false), + ("find_objects", false), + ("get_object", false), + ("get_selection", false), + ("list_stock_materials", false), + ("create_board", true), + ("create_copy", true), + ("draw_polyline", true), + ("move", true), + ("rotate", true), + ("scale", true), + ("resize_board", true), + ("push_pull", true), + ("rename", true), + ("set_material", true), + ("set_grain", true), + ("group", true), + ("ungroup", true), + ("tag", true), + ("paint", true), + ("erase", true), + ("add_joint", true), + ("add_dimension", true), + ("add_text", true), + ("select", false), + ("enter_object", false), + ("exit_to_root", false), +]; + +pub fn is_mutating(name: &str) -> bool { + TOOLS.iter().any(|(n, mutating)| *n == name && *mutating) +} +pub fn is_known(name: &str) -> bool { + TOOLS.iter().any(|(n, _)| *n == name) +} + +// ---------------------------------------------------------------- schemas + +fn vec3() -> Value { + json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}) +} +fn ids() -> Value { + json!({"type": "array", "items": {"type": "integer"}, "minItems": 1}) +} +fn id() -> Value { + json!({"type": "integer"}) +} +fn text() -> Value { + json!({"type": "string"}) +} +fn number() -> Value { + json!({"type": "number"}) +} +/// A tag name: core rejects names over 128 bytes, so the schema says so. +fn tag_name(nullable: bool) -> Value { + let kind = if nullable { json!(["string", "null"]) } else { json!("string") }; + json!({"type": kind, "maxLength": MAX_TAG_BYTES, + "description": format!("At most {MAX_TAG_BYTES} bytes (UTF-8); not \"Untagged\".")}) +} +fn axis_enum() -> Value { + json!({"type": "string", "enum": ["x", "y", "z"]}) +} +fn def(name: &str, description: &str, properties: Value, required: &[&str]) -> ToolDefinition { + ToolDefinition { + name: name.into(), + description: description.into(), + input_schema: json!({ + "type": "object", + "properties": properties, + "required": required, + "additionalProperties": false, + }), + } +} + +/// A tool as offered to an agent, independent of any wire format. +#[derive(Clone, Debug, PartialEq)] +pub struct ToolDefinition { + pub name: String, + pub description: String, + /// JSON Schema of the arguments (always an object, no extra fields). + pub input_schema: Value, +} + +/// One tool invocation. Arguments are a JSON value (lengths in millimetres). +#[derive(Clone, Debug, PartialEq)] +pub struct Call { + pub id: String, + pub name: String, + pub arguments: Value, + /// Argument text that was not valid JSON; `execute` reports it exactly as + /// it reports any other malformed arguments. + raw: Option, +} +impl Call { + pub fn new(id: impl Into, name: impl Into, arguments: Value) -> Self { + Self { id: id.into(), name: name.into(), arguments, raw: None } + } + /// Arguments as the text a model produced. Empty text means `{}`; text + /// that is not JSON is kept and fails with the structured + /// `invalid arguments: ...` error when executed. + pub fn from_text(id: impl Into, name: impl Into, arguments: &str) -> Self { + let text = if arguments.trim().is_empty() { "{}" } else { arguments }; + match serde_json::from_str::(text) { + Ok(value) => Self::new(id, name, value), + Err(_) => Self { raw: Some(arguments.to_owned()), ..Self::new(id, name, Value::Null) }, + } + } +} + +/// OpenAI-compatible `tools` array (`{"type": "function", "function": {..}}`). +pub fn openai_tools() -> Vec { + definitions() + .into_iter() + .map(|d| json!({"type": "function", "function": { + "name": d.name, "description": d.description, "parameters": d.input_schema}})) + .collect() +} + +/// MCP `tools/list` entries (`{name, description, inputSchema}`). +pub fn mcp_tools() -> Vec { + definitions() + .into_iter() + .map(|d| json!({"name": d.name, "description": d.description, "inputSchema": d.input_schema})) + .collect() +} + +pub fn definitions() -> Vec { + let joint_kinds = json!(["mortise_tenon", "half_lap", "tongue_groove", "rabbet", "dovetail", "finger"]); + vec![ + def("get_scene", "Return the whole scene summary again (objects, selection, stock, joints). Lengths are in mm.", json!({}), &[]), + def("find_objects", "Search objects by name, tag, material, kind (group/component) or id. Use when the scene summary was truncated.", + json!({"query": text(), "limit": {"type": "integer", "minimum": 1, "maximum": 100}}), &["query"]), + def("get_object", "Details of one entity, including its faces (id, normal, center, area) for push_pull. Face normals point out of the part; a positive push_pull distance moves a face outward.", + json!({"id": id()}), &["id"]), + def("get_selection", "Entities currently selected in the editor.", json!({}), &[]), + def("list_stock_materials", "Stock materials that can be assigned to boards.", json!({}), &[]), + def("create_board", "Create one rectangular board as a named group. origin_mm is the minimum corner; size_mm is [x, y, z] extents. Prefer this over drawing.", + json!({"name": text(), "origin_mm": vec3(), "size_mm": vec3(), + "material_id": {"type": "string", "description": "id from list_stock_materials"}, + "grain_axis": axis_enum(), "tag": tag_name(false)}), + &["name", "origin_mm", "size_mm"]), + def("create_copy", "Copy an object or group, shifted by offset_mm. Returns the new ids.", + json!({"id": id(), "offset_mm": vec3()}), &["id", "offset_mm"]), + def("draw_polyline", "Draw loose connected edges through points; a closed loop makes a face. Not grouped.", + json!({"points_mm": {"type": "array", "items": vec3(), "minItems": 2}, "close": {"type": "boolean"}}), &["points_mm"]), + def("move", "Translate objects by delta_mm.", json!({"ids": ids(), "delta_mm": vec3()}), &["ids", "delta_mm"]), + def("rotate", "Rotate objects about an axis through pivot_mm.", + json!({"ids": ids(), "pivot_mm": vec3(), "axis": axis_enum(), "degrees": number()}), &["ids", "pivot_mm", "axis", "degrees"]), + def("scale", "Uniformly scale objects about center_mm.", + json!({"ids": ids(), "center_mm": vec3(), "factor": {"type": "number", "minimum": MIN_SCALE, "maximum": MAX_SCALE}}), &["ids", "center_mm", "factor"]), + def("resize_board", "Resize a board to size_mm (world-axis extents), keeping its minimum corner fixed.", + json!({"id": id(), "size_mm": vec3()}), &["id", "size_mm"]), + def("push_pull", "Extrude a face outward by distance_mm (see get_object for face ids). Negative cuts into the part.", + json!({"face_id": id(), "distance_mm": number()}), &["face_id", "distance_mm"]), + def("rename", "Rename an object.", json!({"id": id(), "name": text()}), &["id", "name"]), + def("set_material", "Assign a stock material to objects, or null to clear.", + json!({"ids": ids(), "material_id": {"type": ["string", "null"]}}), &["ids", "material_id"]), + def("set_grain", "Set the grain direction of an object along a world axis, or null to clear.", + json!({"id": id(), "axis": {"type": ["string", "null"], "enum": ["x", "y", "z", null]}}), &["id", "axis"]), + def("group", "Group objects, or make them a component (linked copies). Member ids change; see the result.", + json!({"ids": ids(), "name": text(), "component": {"type": "boolean"}}), &["ids", "name", "component"]), + def("ungroup", "Dissolve groups/components one level.", json!({"ids": ids()}), &["ids"]), + def("tag", "Assign a tag by name (created if missing), or null to clear.", + json!({"ids": ids(), "tag": tag_name(true)}), &["ids", "tag"]), + def("paint", "Paint objects or faces with an RGB color.", + json!({"ids": ids(), "rgb": {"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": 255}, "minItems": 3, "maxItems": 3}}), &["ids", "rgb"]), + def("erase", "Delete entities.", json!({"ids": ids()}), &["ids"]), + def("add_joint", "Add a wood joint between two boards. The boards must already overlap where they meet (the overlap sets the joint depth). Optional params tune the joint (ratios 0-1, clearance in mm).", + json!({"a": id(), "b": id(), "kind": {"type": "string", "enum": joint_kinds}, + "params": {"type": "object", "properties": { + "width_ratio": number(), "height_ratio": number(), + "fingers": {"type": "integer"}, "dovetails": {"type": "integer"}, + "taper_degrees": number(), "clearance_mm": number(), + "depth_axis": {"type": "integer", "minimum": 0, "maximum": 2}, + "width_axis": {"type": "integer", "minimum": 0, "maximum": 2}}, + "additionalProperties": false}}), + &["a", "b", "kind"]), + def("add_dimension", "Add a dimension annotation between two points, drawn offset_mm away.", + json!({"start_mm": vec3(), "end_mm": vec3(), "offset_mm": vec3()}), &["start_mm", "end_mm", "offset_mm"]), + def("add_text", "Add a text note anchored at point_mm.", + json!({"point_mm": vec3(), "offset_mm": vec3(), "text": text()}), &["point_mm", "offset_mm", "text"]), + def("select", "Select entities in the editor so the designer sees them.", json!({"ids": ids()}), &["ids"]), + def("enter_object", "Open a group/component for editing its inner parts.", json!({"id": id()}), &["id"]), + def("exit_to_root", "Leave any open group and edit the top level again.", json!({}), &[]), + ] +} + +// ---------------------------------------------------------------- arguments + +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum AxisArg { + X, + Y, + Z, +} +impl AxisArg { + fn axis(&self) -> Axis { + match self { + Self::X => Axis::X, + Self::Y => Axis::Y, + Self::Z => Axis::Z, + } + } +} +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum JointArg { + MortiseTenon, + HalfLap, + TongueGroove, + Rabbet, + Dovetail, + Finger, +} +impl JointArg { + fn kind(&self) -> JointKind { + match self { + Self::MortiseTenon => JointKind::MortiseTenon, + Self::HalfLap => JointKind::HalfLap, + Self::TongueGroove => JointKind::TongueGroove, + Self::Rabbet => JointKind::Rabbet, + Self::Dovetail => JointKind::Dovetail, + Self::Finger => JointKind::Finger, + } + } +} + +type V3 = [f64; 3]; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Empty {} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FindArgs { + query: String, + limit: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct IdArg { + id: u64, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct IdsArg { + ids: Vec, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CreateBoardArgs { + name: String, + origin_mm: V3, + size_mm: V3, + material_id: Option, + grain_axis: Option, + tag: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CopyArgs { + id: u64, + offset_mm: V3, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolylineArgs { + points_mm: Vec, + close: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct MoveArgs { + ids: Vec, + delta_mm: V3, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RotateArgs { + ids: Vec, + pivot_mm: V3, + axis: AxisArg, + degrees: f64, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ScaleArgs { + ids: Vec, + center_mm: V3, + factor: f64, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResizeArgs { + id: u64, + size_mm: V3, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PushPullArgs { + face_id: u64, + distance_mm: f64, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RenameArgs { + id: u64, + name: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct MaterialArgs { + ids: Vec, + material_id: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct GrainArgs { + id: u64, + axis: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct GroupArgs { + ids: Vec, + name: String, + component: bool, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TagArgs { + ids: Vec, + tag: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PaintArgs { + ids: Vec, + rgb: [u8; 3], +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct JointParams { + width_ratio: Option, + height_ratio: Option, + fingers: Option, + dovetails: Option, + taper_degrees: Option, + clearance_mm: Option, + depth_axis: Option, + width_axis: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct JointArgs { + a: u64, + b: u64, + kind: JointArg, + params: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DimensionArgs { + start_mm: V3, + end_mm: V3, + offset_mm: V3, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TextArgs { + point_mm: V3, + offset_mm: V3, + text: String, +} + +fn parse(arguments: &str) -> Result { + let text = if arguments.trim().is_empty() { "{}" } else { arguments }; + serde_json::from_str(text).map_err(|e| { + fail( + format!("invalid arguments: {e}"), + "Send a JSON object that matches the tool schema exactly: required fields, no extra fields, lengths in mm.", + ) + }) +} +/// Millimetres on the wire to a metre vector in the document. +fn point(v: V3) -> Result { + if v.iter().any(|x| !x.is_finite() || x.abs() > MAX_COORDINATE_MM) { + return Err(fail("coordinate out of range", "Use finite values within 100 m (100000 mm) of the origin, in millimetres.")); + } + Ok(DVec3::new(from_mm(v[0]), from_mm(v[1]), from_mm(v[2]))) +} +fn finite(value: f64, what: &str) -> Result { + value.is_finite().then_some(value).ok_or_else(|| Fail::from(format!("{what} must be a finite number"))) +} + +// ---------------------------------------------------------------- id checks + +fn unreachable_hint(model: &Model, id: u64) -> String { + match model.parent(id) { + Some(parent) if model.objects.contains_key(&parent) => { + format!("{id} is inside object {parent}: call enter_object{{id:{parent}}} first, or exit_to_root to edit the top level.") + } + _ => "Call exit_to_root, then retry.".into(), + } +} + +/// Resolve ids that must exist and be visible; mutating use also needs them +/// unlocked and selectable in the current editing scope. +fn entities(model: &Model, ids: &[u64], mutating: bool) -> Result, Fail> { + if ids.is_empty() { + return Err(fail("ids must not be empty", "Pass at least one entity id from get_scene.")); + } + if ids.len() > MAX_IDS { + return Err(fail("too many ids", format!("Pass at most {MAX_IDS} ids per call."))); + } + for id in ids { + if !model.contains_entity(id) { + return Err(fail(format!("unknown id {id}"), "Call get_scene or find_objects to see valid ids.")); + } + if model.is_hidden(*id) { + return Err(fail(format!("entity {id} is hidden"), "Hidden entities cannot be used.")); + } + if mutating { + if model.is_locked(*id) { + return Err(fail(format!("entity {id} is locked"), "Locked entities cannot be changed; tell the designer to unlock it.")); + } + if model.entity_in_context(*id) != Some(*id) { + return Err(fail(format!("entity {id} is not editable in the current scope"), unreachable_hint(model, *id))); + } + } + } + Ok(ids.iter().copied().collect()) +} +fn objects(model: &Model, ids: &[u64], mutating: bool) -> Result, Fail> { + let set = entities(model, ids, mutating)?; + if let Some(id) = set.iter().find(|id| !model.objects.contains_key(id)) { + return Err(fail(format!("{id} is not a group or component"), "Use ids of objects listed under objects in get_scene.")); + } + Ok(set) +} +fn one_object(model: &Model, id: u64) -> Result { + objects(model, &[id], true).map(|_| id) +} + +fn find_material(model: &Model, env: &ToolEnv, id: MaterialId) -> Result { + env.catalog + .get(&id) + .or_else(|| model.stock_materials.get(&id)) + .cloned() + .ok_or_else(|| fail(format!("unknown material_id {id}"), "Call list_stock_materials for valid ids.")) +} +fn assign_material(model: &mut Model, env: &ToolEnv, object: u64, material: Option) -> Result<(), Fail> { + let definition = material.map(|id| find_material(model, env, id)).transpose()?; + if let (Some(id), Some(definition)) = (material, definition) { + model.stock_materials.insert(id, definition); + } + let target = model.objects.get_mut(&object).ok_or("missing object")?; + target.stock_material_id = material; + target.stock_material = None; + Ok(()) +} +fn tag_named(model: &mut Model, name: &str) -> Result { + let name = name.trim(); + if name.len() > MAX_TAG_BYTES { + return Err(fail("tag name too long", format!("Use at most {MAX_TAG_BYTES} bytes (UTF-8)."))); + } + let folded = name.to_lowercase(); + if let Some(tag) = model.tags.values().find(|t| t.name.to_lowercase() == folded) { + return Ok(tag.id); + } + Ok(model.add_tag(name)?) +} +fn checked_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > 128 { + return Err(fail("name must be 1-128 characters", "Choose a short descriptive name.")); + } + Ok(name.to_owned()) +} + +// ---------------------------------------------------------------- tools + +fn read(value: Value) -> Res { + let mut done = Done::default(); + if let Value::Object(map) = value { + done.extra = map; + } + Ok(done) +} + +fn create_board(model: &mut Model, env: &ToolEnv, a: CreateBoardArgs) -> Res { + let name = checked_name(&a.name)?; + let origin = point(a.origin_mm)?; + let size = point(a.size_mm)?; + if size.min_element() < 1.0e-4 || size.max_element() > 100. { + return Err(fail("size_mm out of range", "Each extent must be between 0.1 mm and 100000 mm.")); + } + let material = a.material_id; + if let Some(id) = material { + find_material(model, env, id)?; + } + let mut drawing = Model::default(); + let corners = [ + origin, + origin + DVec3::X * size.x, + origin + DVec3::new(size.x, size.y, 0.), + origin + DVec3::Y * size.y, + origin, + ]; + drawing.draw_polyline(&corners, false)?; + let face = drawing.faces.keys().next().copied().ok_or("the base rectangle did not form a face")?; + drawing.push_pull_along(face, DVec3::Z * size.z)?; + let roots = model.paste_entities(&drawing, DVec3::ZERO); + let object = model + .make_object(&roots, false, &name) + .ok_or_else(|| fail("the board could not be created", "The current editing scope may be locked; try exit_to_root."))?; + if material.is_some() { + assign_material(model, env, object, material)?; + } + if let Some(axis) = a.grain_axis { + model.set_grain_direction(object, Some(axis.axis().vector()))?; + } + if let Some(tag) = a.tag.as_deref().filter(|t| !t.trim().is_empty()) { + let tag = tag_named(model, tag)?; + model.assign_tag(&BTreeSet::from([object]), Some(tag))?; + } + Ok(Done { created: vec![object], ..Default::default() }) +} + +fn create_copy(model: &mut Model, a: CopyArgs) -> Res { + let source = entities(model, &[a.id], false)?; + let offset = point(a.offset_mm)?; + let copy = model.copy_entities(&source); + let before: BTreeSet = model.root_entities(); + let pasted = model.paste_entities(©, offset); + let created: Vec = if pasted.is_empty() { Vec::new() } else { pasted.difference(&before).copied().collect() }; + if created.is_empty() { + return Err("nothing was copied".into()); + } + Ok(Done { created, ..Default::default() }) +} + +fn draw_polyline(model: &mut Model, a: PolylineArgs) -> Res { + if a.points_mm.len() < 2 { + return Err(fail("points_mm needs at least 2 points", "Give the corners in order.")); + } + if a.points_mm.len() > MAX_POINTS { + return Err(fail("too many points", format!("Pass at most {MAX_POINTS} points per call."))); + } + let mut points = a.points_mm.into_iter().map(point).collect::, _>>()?; + if a.close.unwrap_or(false) + && let Some(first) = points.first().copied() + { + points.push(first); + } + let known = |m: &Model| -> BTreeSet { m.edges.keys().chain(m.faces.keys()).copied().collect() }; + let before = known(model); + model.draw_polyline(&points, false)?; + let created: Vec = known(model).difference(&before).copied().collect(); + Ok(Done { created, ..Default::default() }) +} + +fn move_objects(model: &mut Model, a: MoveArgs) -> Res { + let set = entities(model, &a.ids, true)?; + model.move_selection(&set, point(a.delta_mm)?)?; + Ok(modified(&set)) +} +fn rotate(model: &mut Model, a: RotateArgs) -> Res { + let set = entities(model, &a.ids, true)?; + let degrees = finite(a.degrees, "degrees")?; + model.rotate_selection(&set, point(a.pivot_mm)?, a.axis.axis().vector(), degrees)?; + Ok(modified(&set)) +} +fn scale(model: &mut Model, a: ScaleArgs) -> Res { + let set = entities(model, &a.ids, true)?; + let factor = finite(a.factor, "factor")?; + if !(MIN_SCALE..=MAX_SCALE).contains(&factor) { + return Err(fail("factor out of range", format!("Use a factor between {MIN_SCALE} and {MAX_SCALE}; scale in several steps if needed."))); + } + model.scale_selection(&set, point(a.center_mm)?, factor)?; + Ok(modified(&set)) +} +fn resize_board(model: &mut Model, a: ResizeArgs) -> Res { + let id = one_object(model, a.id)?; + let set = BTreeSet::from([id]); + let target = point(a.size_mm)?; + if target.min_element() < 1.0e-4 { + return Err(fail("size_mm out of range", "Each extent must be at least 0.1 mm.")); + } + let (lo, hi) = model.selection_bounds(&set).ok_or("the object has no geometry")?; + let current = hi - lo; + for axis in [Axis::X, Axis::Y, Axis::Z] { + let (old, new) = (current.dot(axis.vector()), target.dot(axis.vector())); + if (new - old).abs() < 1.0e-9 { + continue; + } + if old < 1.0e-9 { + return Err("the object is flat along that axis and cannot be resized".into()); + } + model.scale_selection_constrained(&set, lo, new / old, Some(AxisConstraint::Axis(axis)))?; + } + Ok(modified(&set)) +} +fn push_pull(model: &mut Model, a: PushPullArgs) -> Res { + let face = a.face_id; + if !model.faces.contains_key(&face) { + return Err(fail(format!("{face} is not a face"), "Use a face id from get_object.")); + } + if model.is_hidden(face) || model.is_locked(face) { + return Err(fail(format!("face {face} is hidden or locked"), "Pick another face.")); + } + // The edit scope is switched to the face's owner below, so check here, with + // the same rules as the other tools, that the owner chain may be edited. + let top = model.entity_in_context(face).ok_or_else(|| { + fail(format!("face {face} is not editable in the current scope"), unreachable_hint(model, face)) + })?; + entities(model, &[top], true)?; + let mut ancestor = model.parent(face); + while let Some(owner) = ancestor { + if model.is_hidden(owner) || model.is_locked(owner) { + return Err(fail(format!("face {face} is inside hidden or locked object {owner}"), "Locked entities cannot be changed; tell the designer to unlock it.")); + } + ancestor = model.parent(owner); + } + let distance = from_mm(finite(a.distance_mm, "distance_mm")?) * scene::outward_sign(model, face); + let owner = model.parent(face); + let saved = model.edit_context; + // Faces inside an object are edited through that object's scope. + let result = match owner { + Some(owner) if saved != Some(owner) => { + model.edit_context = Some(owner); + let result = model.push_pull(face, distance); + model.edit_context = saved; + result + } + _ => model.push_pull(face, distance), + }; + let new_face = result?; + let mut done = Done::default(); + if let Some(owner) = owner.filter(|o| model.objects.contains_key(o)) { + done.modified.push(owner); + } + if model.faces.contains_key(&new_face) { + done.extra.insert("new_face_id".into(), json!(new_face)); + } + Ok(done) +} +fn rename(model: &mut Model, a: RenameArgs) -> Res { + let id = one_object(model, a.id)?; + let name = checked_name(&a.name)?; + model.objects.get_mut(&id).ok_or("missing object")?.name = name; + Ok(modified(&BTreeSet::from([id]))) +} +fn set_material(model: &mut Model, env: &ToolEnv, a: MaterialArgs) -> Res { + let set = objects(model, &a.ids, true)?; + if let Some(id) = a.material_id { + find_material(model, env, id)?; + } + for id in &set { + assign_material(model, env, *id, a.material_id)?; + } + Ok(modified(&set)) +} +fn set_grain(model: &mut Model, a: GrainArgs) -> Res { + let id = one_object(model, a.id)?; + model.set_grain_direction(id, a.axis.map(|axis| axis.axis().vector()))?; + Ok(modified(&BTreeSet::from([id]))) +} +fn group(model: &mut Model, a: GroupArgs) -> Res { + let set = entities(model, &a.ids, true)?; + let name = checked_name(&a.name)?; + let group = model + .make_object(&set, a.component, &name) + .ok_or_else(|| fail("the selection could not be grouped", "Locked or empty selections cannot be grouped."))?; + let members: BTreeSet = model.objects[&group].entities.clone(); + let mut done = Done { + created: vec![group], + erased: set.iter().copied().filter(|id| !model.contains_entity(id)).collect(), + ..Default::default() + }; + done.extra.insert( + "members".into(), + Value::Array(members.iter().filter_map(|id| scene::object_entry(model, *id)).collect()), + ); + done.extra.insert("note".into(), json!("Member ids may have changed; use the ids in members.")); + Ok(done) +} +fn ungroup(model: &mut Model, a: IdsArg) -> Res { + let set = objects(model, &a.ids, true)?; + let released = model.dissolve_objects(&set, false); + Ok(Done { + modified: released.into_iter().filter(|id| model.contains_entity(id)).collect(), + erased: set.iter().copied().filter(|id| !model.contains_entity(id)).collect(), + ..Default::default() + }) +} +fn tag(model: &mut Model, a: TagArgs) -> Res { + let set = entities(model, &a.ids, true)?; + let tag = match a.tag.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + Some(name) => Some(tag_named(model, name)?), + None => None, + }; + model.assign_tag(&set, tag)?; + let mut done = modified(&set); + done.extra.insert("tag_id".into(), json!(tag)); + Ok(done) +} +fn paint(model: &mut Model, a: PaintArgs) -> Res { + let set = entities(model, &a.ids, true)?; + for id in &set { + if model.objects.contains_key(id) { + model.paint_object(*id, a.rgb)?; + } else if model.faces.contains_key(id) { + model.paint_face(*id, a.rgb)?; + } else { + return Err(fail(format!("{id} cannot be painted"), "Paint objects or faces.")); + } + } + Ok(modified(&set)) +} +fn erase(model: &mut Model, a: IdsArg) -> Res { + let set = entities(model, &a.ids, true)?; + model.erase(&set); + let erased: Vec = set.iter().copied().filter(|id| !model.contains_entity(id)).collect(); + if erased.is_empty() { + return Err("nothing was erased".into()); + } + Ok(Done { erased, ..Default::default() }) +} +fn add_joint(model: &mut Model, a: JointArgs) -> Res { + if a.a == a.b { + return Err(fail("a and b must differ", "A joint connects two different boards.")); + } + let set = objects(model, &[a.a, a.b], true)?; + let mut settings = JointSettings { kind: a.kind.kind(), ..Default::default() }; + if let Some(p) = a.params { + let ratio = |value: Option, what: &str| -> Result, Fail> { + value + .map(|v| { + (v.is_finite() && v > 0. && v <= 1.) + .then_some(v) + .ok_or_else(|| Fail::from(format!("{what} must be between 0 and 1"))) + }) + .transpose() + }; + if let Some(v) = ratio(p.width_ratio, "width_ratio")? { + settings.width_ratio = v; + } + if let Some(v) = ratio(p.height_ratio, "height_ratio")? { + settings.height_ratio = v; + } + if let Some(v) = p.fingers { + settings.fingers = v.clamp(1, 64); + } + if let Some(v) = p.dovetails { + settings.dovetails = v.clamp(1, 64); + } + if let Some(v) = p.taper_degrees { + settings.taper_degrees = finite(v, "taper_degrees")?.clamp(0., 30.); + } + if let Some(v) = p.clearance_mm { + settings.clearance = from_mm(finite(v, "clearance_mm")?.clamp(0., 5.)); + } + for (axis, slot) in [(p.depth_axis, &mut settings.depth_axis), (p.width_axis, &mut settings.width_axis)] { + if let Some(axis) = axis { + if axis > 2 { + return Err("axis indexes are 0, 1 or 2".into()); + } + *slot = axis; + } + } + } + let joint = model.add_connection(Connection { + members: [a.a, a.b], + entry_face: None, + operation: ConnectionOperation::Joinery(settings), + })?; + let mut done = modified(&set); + done.joints.push(joint); + done.extra.insert("joint_id".into(), json!(joint)); + Ok(done) +} +fn add_dimension(model: &mut Model, a: DimensionArgs) -> Res { + let id = model.add_dimension(point(a.start_mm)?, point(a.end_mm)?, point(a.offset_mm)?)?; + Ok(Done { created: vec![id], ..Default::default() }) +} +fn add_text(model: &mut Model, a: TextArgs) -> Res { + if a.text.chars().count() > MAX_TEXT_CHARS { + return Err(fail("text too long", format!("Use at most {MAX_TEXT_CHARS} characters."))); + } + let id = model.add_text(point(a.point_mm)?, point(a.offset_mm)?, &a.text)?; + Ok(Done { created: vec![id], ..Default::default() }) +} + +fn find_objects(model: &Model, a: FindArgs) -> Res { + let query = a.query.trim().to_lowercase(); + let limit = a.limit.unwrap_or(40).clamp(1, 100); + let matches = |id: u64| -> bool { + let Some(object) = model.objects.get(&id) else { return false }; + query.is_empty() + || id.to_string() == query + || object.name.to_lowercase().contains(&query) + || scene::kind_of(model, id) == query + || model.inherited_tag(id).is_some_and(|t| t.name.to_lowercase().contains(&query)) + || model + .object_stock_material(object) + .is_some_and(|m| m.name.to_lowercase().contains(&query)) + }; + let found: Vec = model.objects.keys().copied().filter(|id| matches(*id)).collect(); + read(json!({ + "total": found.len(), + "objects": found.iter().take(limit).filter_map(|id| scene::object_entry(model, *id)).collect::>(), + })) +} + +fn run(model: &mut Model, env: &mut ToolEnv, name: &str, arguments: &str) -> Res { + match name { + "get_scene" => { + parse::(arguments)?; + let shared = if env.hide_selection { BTreeSet::new() } else { env.selection.clone() }; + read(scene::summary(model, &shared, &env.catalog, scene::SCENE_BUDGET)) + } + "find_objects" => find_objects(model, parse(arguments)?), + "get_object" => { + let a: IdArg = parse(arguments)?; + read(scene::describe(model, a.id).ok_or_else(|| fail(format!("unknown id {}", a.id), "Call get_scene or find_objects."))?) + } + "get_selection" => { + parse::(arguments)?; + if env.hide_selection { + return read(json!({"selection": [], "note": "The designer has turned off sharing their selection."})); + } + let live: Vec = env.selection.iter().copied().filter(|id| model.contains_entity(id)).collect(); + read(json!({ + "selection": live, + "objects": live.iter().filter_map(|id| scene::object_entry(model, *id)).collect::>(), + })) + } + "list_stock_materials" => { + parse::(arguments)?; + read(json!({"materials": scene::stock_list(model, &env.catalog)})) + } + "create_board" => create_board(model, env, parse(arguments)?), + "create_copy" => create_copy(model, parse(arguments)?), + "draw_polyline" => draw_polyline(model, parse(arguments)?), + "move" => move_objects(model, parse(arguments)?), + "rotate" => rotate(model, parse(arguments)?), + "scale" => scale(model, parse(arguments)?), + "resize_board" => resize_board(model, parse(arguments)?), + "push_pull" => push_pull(model, parse(arguments)?), + "rename" => rename(model, parse(arguments)?), + "set_material" => set_material(model, env, parse(arguments)?), + "set_grain" => set_grain(model, parse(arguments)?), + "group" => group(model, parse(arguments)?), + "ungroup" => ungroup(model, parse(arguments)?), + "tag" => tag(model, parse(arguments)?), + "paint" => paint(model, parse(arguments)?), + "erase" => erase(model, parse(arguments)?), + "add_joint" => add_joint(model, parse(arguments)?), + "add_dimension" => add_dimension(model, parse(arguments)?), + "add_text" => add_text(model, parse(arguments)?), + "select" => { + let a: IdsArg = parse(arguments)?; + let chosen = entities(model, &a.ids, false)?; + // Shared project: only what this designer may edit can be selected. + if let Some(id) = chosen.iter().find(|id| !leased(model, env, **id)) { + return Err(fail( + format!("entity {id} is not in your edit lease"), + "Only entities you hold the edit lease on (or created this turn) can be selected.", + )); + } + env.selection = chosen; + read(json!({"selection": env.selection})) + } + "enter_object" => { + let a: IdArg = parse(arguments)?; + // Shared project: entering a group the designer does not hold would + // let later creating tools place geometry inside it. + if model.contains_entity(&a.id) && !leased(model, env, a.id) { + return Err(fail("not-leased", "select it first so you hold the edit lease")); + } + if !model.enter_object(a.id) { + return Err(fail( + format!("cannot open {}", a.id), + "It must be an unlocked, visible group or component in the current scope.", + )); + } + read(json!({"edit_path": model.edit_path()})) + } + "exit_to_root" => { + parse::(arguments)?; + model.edit_context = None; + read(json!({"edit_path": model.edit_path()})) + } + _ => Err(Fail::from("unknown tool")), + } +} + +fn error_outcome(error: String, hint: Option) -> ToolOutcome { + let mut result = json!({"ok": false, "error": error}); + if let Some(hint) = hint { + result["hint"] = json!(hint); + } + ToolOutcome { + result, + ok: false, + mutated: false, + created: Vec::new(), + modified: Vec::new(), + erased: Vec::new(), + joints: Vec::new(), + } +} + +/// Tools that only add new entities: nothing existing is touched, so there is +/// nothing to lease. (`create_copy` reads its source without changing it.) +const CREATING: &[&str] = &["create_board", "create_copy", "draw_polyline", "add_dimension", "add_text"]; + +/// Existing entities a mutating call names, read from the raw arguments. +fn target_ids(name: &str, arguments: &str) -> Vec { + if CREATING.contains(&name) { + return Vec::new(); + } + let Ok(Value::Object(map)) = serde_json::from_str::(arguments) else { return Vec::new() }; + let mut ids: Vec = map.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect(); + ids.extend(["id", "face_id", "a", "b"].iter().filter_map(|key| map.get(*key)?.as_u64())); + ids +} + +/// An entity is leased when it, or an object containing it, is in the lease +/// (or was created by this turn). Always true outside shared projects. +fn leased(model: &Model, env: &ToolEnv, id: u64) -> bool { + let Some(lease) = &env.lease else { return true }; + let mut current = Some(id); + for _ in 0..256 { + let Some(c) = current else { break }; + if lease.contains(&c) || env.created.contains(&c) { + return true; + } + current = model.parent(c); + } + false +} + +/// Safety net for shared projects: after a mutating call, every entity that +/// existed before and was changed or removed must have been leased (or created +/// this turn). Ownership is read from the pre-call model. Loose root geometry +/// has no owner, so it is never covered. +fn lease_respected(before: &Model, after: &Model, env: &ToolEnv) -> bool { + let Some(lease) = &env.lease else { return true }; + let mut parent: BTreeMap = BTreeMap::new(); + for object in before.objects.values() { + for child in &object.entities { + parent.insert(*child, object.id); + } + } + let covered = |id: u64| -> bool { + let mut current = Some(id); + for _ in 0..256 { + let Some(c) = current else { break }; + if lease.contains(&c) || env.created.contains(&c) { + return true; + } + current = parent.get(&c).copied(); + } + false + }; + fn changed(old: &BTreeMap, new: &BTreeMap) -> Vec { + old.iter().filter(|(id, value)| new.get(id) != Some(*value)).map(|(id, _)| *id).collect() + } + let entity_ids = changed(&before.objects, &after.objects) + .into_iter() + .chain(changed(&before.faces, &after.faces)) + .chain(changed(&before.edges, &after.edges)) + .chain(changed(&before.dimensions, &after.dimensions)) + .chain(changed(&before.texts, &after.texts)) + .chain(changed(&before.guides, &after.guides)) + .chain(changed(&before.face_colors, &after.face_colors)) + .chain(changed(&before.entity_tags, &after.entity_tags)); + if !entity_ids.into_iter().all(&covered) { + return false; + } + // Hidden / locked flags on existing entities. + let flags = before.hidden.symmetric_difference(&after.hidden).chain(before.locked.symmetric_difference(&after.locked)); + if !flags.filter(|id| before.contains_entity(id)).all(|id| covered(*id)) { + return false; + } + // A vertex is covered only when everything that uses it is. + let moved: BTreeSet = changed(&before.vertices, &after.vertices).into_iter().collect(); + if !moved.is_empty() { + let mut users: BTreeMap> = BTreeMap::new(); + for edge in before.edges.values() { + users.entry(edge.a).or_default().push(edge.id); + users.entry(edge.b).or_default().push(edge.id); + } + for face in before.faces.values() { + for v in face.vertices.iter().chain(face.holes.iter().flatten()) { + users.entry(*v).or_default().push(face.id); + } + } + for v in moved { + match users.get(&v) { + Some(list) if list.iter().all(|u| covered(*u)) => {} + _ => return false, + } + } + } + changed(&before.connections, &after.connections) + .into_iter() + .all(|id| before.connections[&id].members.iter().all(|m| covered(*m))) +} + +fn out_of_range(model: &Model, done: &Done) -> bool { + let touched: BTreeSet = done.created.iter().chain(&done.modified).copied().filter(|id| model.contains_entity(id)).collect(); + model + .selection_bounds(&touched) + .is_some_and(|(lo, hi)| [lo, hi].iter().any(|p| p.to_array().iter().any(|v| !v.is_finite() || v.abs() > MAX_RESULT_M))) +} + +/// Apply one tool call. A failed or panicking mutating call leaves the model +/// exactly as it was; a successful one records the turn's `before` snapshot. +pub fn execute(model: &mut Model, call: &Call, env: &mut ToolEnv) -> ToolOutcome { + let name = call.name.as_str(); + if !is_known(name) { + let names: Vec<_> = TOOLS.iter().map(|(n, _)| *n).collect(); + return error_outcome(format!("unknown tool {name}"), Some(format!("Available tools: {}", names.join(", ")))); + } + let mutating = is_mutating(name); + if mutating && env.read_only { + return error_outcome( + "read-only".into(), + Some("This project is read-only for the designer; describe what you would change instead.".into()), + ); + } + let text = call.raw.clone().unwrap_or_else(|| call.arguments.to_string()); + let arguments = text.as_str(); + if mutating + && target_ids(name, arguments).into_iter().any(|id| model.contains_entity(&id) && !leased(model, env, id)) + { + return error_outcome("not-leased".into(), Some("select it first so you hold the edit lease".into())); + } + // Creating tools write into the open group; it must be one the designer holds. + if mutating + && env.lease.is_some() + && CREATING.contains(&name) + && model.edit_context.is_some_and(|context| !leased(model, env, context)) + { + return error_outcome("not-leased".into(), Some("select it first so you hold the edit lease".into())); + } + let backup = mutating.then(|| model.clone()); + // `catch_unwind` cannot help on wasm32, where a panic aborts. Every tool + // therefore validates its arguments (counts, ranges, lengths) before it + // touches the model, and the result is range-checked below. + let attempt = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(model, env, name, arguments))); + let result = match attempt { + Ok(result) => result, + Err(_) => Err(Fail::from("internal error while applying the tool")), + }; + match result { + Err(failure) => { + if let Some(backup) = backup { + *model = backup; + } + error_outcome(failure.error, failure.hint) + } + Ok(_) if backup.as_ref().is_some_and(|b| env.lease.is_some() && !lease_respected(b, model, env)) => { + *model = backup.unwrap_or_default(); + error_outcome("not-leased".into(), Some("select it first so you hold the edit lease".into())) + } + Ok(done) if backup.is_some() && out_of_range(model, &done) => { + *model = backup.unwrap_or_default(); + error_outcome( + "result out of range".into(), + Some("The result would be non-finite or beyond 1 km from the origin; use smaller values.".into()), + ) + } + Ok(done) => { + env.created.extend(&done.created); + if name == "ungroup" { + // Released parts have no leased container any more. + env.created.extend(&done.modified); + } + let mut mutated = false; + if let Some(backup) = backup { + mutated = !backup.same_scene(model); + if mutated && env.before.is_none() { + env.before = Some(backup); + } + } + let mut result = Value::Object(done.extra); + result["ok"] = json!(true); + if mutating { + let live = |ids: &[u64]| -> Vec { ids.iter().copied().filter(|id| model.contains_entity(id)).collect() }; + let (created, changed) = (live(&done.created), live(&done.modified)); + let touched: BTreeSet = created.iter().chain(&changed).copied().collect(); + result["created"] = json!(created); + result["modified"] = json!(changed); + if !done.erased.is_empty() { + result["erased"] = json!(done.erased); + } + if let Some(bounds) = scene::bounds_json(model, &touched) { + result["bounds_mm"] = bounds; + } + let summaries: Vec = touched.iter().take(20).filter_map(|id| scene::object_entry(model, *id)).collect(); + if !summaries.is_empty() { + result["objects"] = Value::Array(summaries); + } + } + ToolOutcome { + result, + ok: true, + mutated, + created: done.created, + modified: done.modified, + erased: done.erased, + joints: done.joints, + } + } + } +} + +#[cfg(test)] +#[path = "ops_tests.rs"] +mod tests; diff --git a/crates/benchup-tools/src/ops_tests.rs b/crates/benchup-tools/src/ops_tests.rs new file mode 100644 index 0000000..fa2b9b6 --- /dev/null +++ b/crates/benchup-tools/src/ops_tests.rs @@ -0,0 +1,574 @@ +use super::*; +use serde_json::{Value, json}; + +pub fn call(name: &str, args: Value) -> Call { + Call::new("t1", name, args) +} +pub fn run(model: &mut Model, env: &mut ToolEnv, name: &str, args: Value) -> ToolOutcome { + execute(model, &call(name, args), env) +} +fn ok(model: &mut Model, env: &mut ToolEnv, name: &str, args: Value) -> ToolOutcome { + let outcome = run(model, env, name, args); + assert!(outcome.ok, "{name} failed: {}", outcome.result); + outcome +} +fn err(model: &mut Model, env: &mut ToolEnv, name: &str, args: Value) -> String { + let before = model.clone(); + let outcome = run(model, env, name, args); + assert!(!outcome.ok, "{name} unexpectedly succeeded: {}", outcome.result); + assert_eq!(outcome.result["ok"], false); + assert!(!outcome.mutated); + assert_eq!(*model, before, "{name} must leave the model untouched on error"); + outcome.result["error"].as_str().unwrap().to_owned() +} +pub fn board(model: &mut Model, env: &mut ToolEnv, name: &str, origin: [f64; 3], size: [f64; 3]) -> u64 { + ok(model, env, "create_board", json!({"name": name, "origin_mm": origin, "size_mm": size})).created[0] +} +fn bounds(model: &Model, id: u64) -> (DVec3, DVec3) { + model.selection_bounds(&BTreeSet::from([id])).unwrap() +} +fn near(a: DVec3, b: [f64; 3]) { + assert!(a.distance(DVec3::from(b)) < 1e-6, "{a:?} != {b:?}"); +} + +#[test] +fn create_board_converts_millimetres_to_metres() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let outcome = ok(&mut model, &mut env, "create_board", json!({ + "name": "Top", "origin_mm": [100, 200, 300], "size_mm": [600, 400, 19]})); + let id = outcome.created[0]; + assert_eq!(model.objects[&id].name, "Top"); + let (lo, hi) = bounds(&model, id); + near(lo, [0.1, 0.2, 0.3]); + near(hi, [0.7, 0.6, 0.319]); + assert_eq!(outcome.result["bounds_mm"]["size"], json!([600.0, 400.0, 19.0])); + assert_eq!(outcome.result["created"], json!([id])); + assert!(outcome.mutated); + assert!(env.before.is_some(), "first mutation snapshots the model"); + // It is a closed solid: six faces. + let faces = model.expand_entities(&BTreeSet::from([id])).iter().filter(|f| model.faces.contains_key(f)).count(); + assert_eq!(faces, 6); +} + +#[test] +fn create_board_applies_material_grain_and_tag() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let material = benchup_core::MaterialId::new_v4(); + env.catalog.insert(material, StockMaterial { name: "Oak 19".into(), dimensions: [190, 890, 24400] }); + let id = ok(&mut model, &mut env, "create_board", json!({ + "name": "Leg", "origin_mm": [0, 0, 0], "size_mm": [40, 40, 700], + "material_id": material.to_string(), "grain_axis": "z", "tag": "Legs"})).created[0]; + assert_eq!(model.objects[&id].stock_material_id, Some(material)); + assert!(model.stock_materials.contains_key(&material)); + assert!(model.objects[&id].grain_axis().unwrap().z.abs() > 0.99); + assert_eq!(model.inherited_tag(id).unwrap().name, "Legs"); + let again = ok(&mut model, &mut env, "create_board", json!({ + "name": "Leg 2", "origin_mm": [100, 0, 0], "size_mm": [40, 40, 700], "tag": "legs"})).created[0]; + assert_eq!(model.tags.len(), 1, "tag names match case-insensitively"); + assert_eq!(model.inherited_tag(again).unwrap().name, "Legs"); + err(&mut model, &mut env, "create_board", json!({ + "name": "X", "origin_mm": [0, 0, 0], "size_mm": [1, 1, 1], "material_id": benchup_core::MaterialId::new_v4().to_string()})); +} + +#[test] +fn argument_and_id_errors_are_structured_and_harmless() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let leg = board(&mut model, &mut env, "Leg", [0., 0., 0.], [40., 40., 700.]); + assert!(err(&mut model, &mut env, "nope", json!({})).contains("unknown tool")); + assert!(err(&mut model, &mut env, "move", json!({"ids": [leg]})).contains("invalid arguments")); + assert!(err(&mut model, &mut env, "move", json!({"ids": [leg], "delta_mm": [1, 2, 3], "extra": 1})).contains("invalid arguments")); + assert!(err(&mut model, &mut env, "move", json!({"ids": "a", "delta_mm": [1, 2, 3]})).contains("invalid arguments")); + assert!(err(&mut model, &mut env, "move", json!({"ids": [9999], "delta_mm": [1, 2, 3]})).contains("unknown id")); + assert!(err(&mut model, &mut env, "move", json!({"ids": [], "delta_mm": [1, 2, 3]})).contains("empty")); + assert!(err(&mut model, &mut env, "move", json!({"ids": [leg], "delta_mm": [1e12, 0, 0]})).contains("out of range")); + assert!(err(&mut model, &mut env, "create_board", json!({"name": "", "origin_mm": [0,0,0], "size_mm": [1,1,1]})).contains("name")); + assert!(err(&mut model, &mut env, "create_board", json!({"name": "a", "origin_mm": [0,0,0], "size_mm": [0,1,1]})).contains("size")); + assert!(err(&mut model, &mut env, "get_object", json!({"id": 424242})).contains("unknown id")); + // Malformed text never panics. + let outcome = execute(&mut model, &Call::from_text("x", "move", "{not json"), &mut env); + assert!(!outcome.ok); + let hint = run(&mut model, &mut env, "move", json!({"ids": [9999], "delta_mm": [1, 2, 3]})); + assert!(hint.result["hint"].is_string()); +} + +#[test] +fn locked_hidden_and_read_only_are_refused() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 100.]); + let b = board(&mut model, &mut env, "B", [500., 0., 0.], [100., 100., 100.]); + model.locked.insert(a); + assert!(err(&mut model, &mut env, "move", json!({"ids": [a], "delta_mm": [1, 0, 0]})).contains("locked")); + assert!(err(&mut model, &mut env, "rename", json!({"id": a, "name": "Z"})).contains("locked")); + assert!(err(&mut model, &mut env, "erase", json!({"ids": [a]})).contains("locked")); + assert!(err(&mut model, &mut env, "add_joint", json!({"a": a, "b": b, "kind": "half_lap"})).contains("locked")); + // Locked entities can still be read. + ok(&mut model, &mut env, "get_object", json!({"id": a})); + model.hidden.insert(b); + assert!(err(&mut model, &mut env, "move", json!({"ids": [b], "delta_mm": [1, 0, 0]})).contains("hidden")); + model.hidden.clear(); + env.read_only = true; + assert_eq!(err(&mut model, &mut env, "move", json!({"ids": [b], "delta_mm": [1, 0, 0]})), "read-only"); + assert_eq!(err(&mut model, &mut env, "create_board", json!({"name":"x","origin_mm":[0,0,0],"size_mm":[1,1,1]})), "read-only"); + // Reads still work when read-only. + ok(&mut model, &mut env, "get_scene", json!({})); +} + +#[test] +fn read_tools_report_scene_objects_and_faces() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let top = board(&mut model, &mut env, "Table top", [0., 0., 700.], [600., 400., 20.]); + let leg = board(&mut model, &mut env, "Left leg", [0., 0., 0.], [40., 40., 700.]); + env.selection = BTreeSet::from([leg]); + let scene = ok(&mut model, &mut env, "get_scene", json!({})).result; + assert_eq!(scene["units"], "mm"); + assert_eq!(scene["objects"].as_array().unwrap().len(), 2); + assert_eq!(scene["selection"], json!([leg])); + assert_eq!(scene["objects"][0]["id"], leg, "selected objects come first"); + let found = ok(&mut model, &mut env, "find_objects", json!({"query": "LEG"})).result; + assert_eq!(found["total"], 1); + assert_eq!(found["objects"][0]["id"], leg); + assert_eq!(ok(&mut model, &mut env, "find_objects", json!({"query": "group"})).result["total"], 2); + let object = ok(&mut model, &mut env, "get_object", json!({"id": top})).result; + assert_eq!(object["size_mm"], json!([600.0, 400.0, 20.0])); + let faces = object["faces"].as_array().unwrap(); + assert_eq!(faces.len(), 6); + let facings: BTreeSet<&str> = faces.iter().filter_map(|f| f["facing"].as_str()).collect(); + assert_eq!(facings, BTreeSet::from(["+x", "-x", "+y", "-y", "+z", "-z"])); + let top_face = faces.iter().find(|f| f["facing"] == "+z").unwrap(); + assert_eq!(top_face["center_mm"][2], 720.0); + assert_eq!(top_face["area_mm2"], 240_000.0); + let selection = ok(&mut model, &mut env, "get_selection", json!({})).result; + assert_eq!(selection["selection"], json!([leg])); + let materials = ok(&mut model, &mut env, "list_stock_materials", json!({})).result; + assert_eq!(materials["materials"], json!([])); +} + +#[test] +fn transform_tools_move_rotate_scale_and_resize() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let id = board(&mut model, &mut env, "Rail", [0., 0., 0.], [100., 50., 20.]); + let outcome = ok(&mut model, &mut env, "move", json!({"ids": [id], "delta_mm": [10, 20, 30]})); + assert_eq!(outcome.modified, [id]); + near(bounds(&model, id).0, [0.01, 0.02, 0.03]); + ok(&mut model, &mut env, "rotate", json!({"ids": [id], "pivot_mm": [10, 20, 30], "axis": "z", "degrees": 90})); + let (lo, hi) = bounds(&model, id); + near(hi - lo, [0.05, 0.1, 0.02]); + ok(&mut model, &mut env, "scale", json!({"ids": [id], "center_mm": [10, 20, 30], "factor": 2})); + let (lo, hi) = bounds(&model, id); + near(hi - lo, [0.1, 0.2, 0.04]); + near(lo, [-0.09, 0.02, 0.03]); + let outcome = ok(&mut model, &mut env, "resize_board", json!({"id": id, "size_mm": [100, 200, 60]})); + let (lo2, hi2) = bounds(&model, id); + near(hi2 - lo2, [0.1, 0.2, 0.06]); + near(lo2, lo.to_array()); + assert_eq!(outcome.result["bounds_mm"]["size"], json!([100.0, 200.0, 60.0])); + assert!(err(&mut model, &mut env, "scale", json!({"ids": [id], "center_mm": [0,0,0], "factor": -1})).len() > 3); + assert!(err(&mut model, &mut env, "resize_board", json!({"id": id, "size_mm": [0, 10, 10]})).contains("size_mm")); +} + +#[test] +fn push_pull_extrudes_a_face_of_a_board() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let id = board(&mut model, &mut env, "Block", [0., 0., 0.], [100., 100., 100.]); + let object = ok(&mut model, &mut env, "get_object", json!({"id": id})).result; + let top = object["faces"].as_array().unwrap().iter().find(|f| f["facing"] == "+z").unwrap()["id"].as_u64().unwrap(); + let outcome = ok(&mut model, &mut env, "push_pull", json!({"face_id": top, "distance_mm": 50})); + assert_eq!(outcome.modified, [id]); + near(bounds(&model, id).1, [0.1, 0.1, 0.15]); + assert_eq!(model.edit_context, None, "scope is restored"); + assert!(err(&mut model, &mut env, "push_pull", json!({"face_id": id, "distance_mm": 5})).contains("not a face")); + assert!(err(&mut model, &mut env, "push_pull", json!({"face_id": top, "distance_mm": 0})).len() > 3); +} + +#[test] +fn naming_material_grain_tag_paint_and_erase() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 20.]); + let b = board(&mut model, &mut env, "B", [200., 0., 0.], [100., 100., 20.]); + ok(&mut model, &mut env, "rename", json!({"id": a, "name": " Shelf "})); + assert_eq!(model.objects[&a].name, "Shelf"); + assert!(err(&mut model, &mut env, "rename", json!({"id": a, "name": " "})).contains("name")); + let material = benchup_core::MaterialId::new_v4(); + env.catalog.insert(material, StockMaterial { name: "Pine".into(), dimensions: [190, 890, 24400] }); + ok(&mut model, &mut env, "set_material", json!({"ids": [a, b], "material_id": material.to_string()})); + assert_eq!(model.objects[&b].stock_material_id, Some(material)); + let listed = ok(&mut model, &mut env, "list_stock_materials", json!({})).result; + assert_eq!(listed["materials"][0]["thickness_mm"], 19.0); + ok(&mut model, &mut env, "set_material", json!({"ids": [a], "material_id": null})); + assert_eq!(model.objects[&a].stock_material_id, None); + ok(&mut model, &mut env, "set_grain", json!({"id": a, "axis": "x"})); + assert!(model.objects[&a].grain_axis().is_some()); + ok(&mut model, &mut env, "set_grain", json!({"id": a, "axis": null})); + assert!(model.objects[&a].grain_axis().is_none()); + let tagged = ok(&mut model, &mut env, "tag", json!({"ids": [a, b], "tag": "Shelves"})); + assert!(tagged.result["tag_id"].is_u64()); + assert_eq!(model.inherited_tag(b).unwrap().name, "Shelves"); + ok(&mut model, &mut env, "tag", json!({"ids": [a], "tag": null})); + assert!(model.inherited_tag(a).is_none()); + ok(&mut model, &mut env, "paint", json!({"ids": [a], "rgb": [200, 10, 10]})); + assert!(!model.face_colors.is_empty()); + assert!(err(&mut model, &mut env, "paint", json!({"ids": [a], "rgb": [300, 0, 0]})).contains("invalid arguments")); + let erased = ok(&mut model, &mut env, "erase", json!({"ids": [b]})); + assert_eq!(erased.erased, [b]); + assert!(!model.objects.contains_key(&b)); + assert_eq!(erased.result["erased"], json!([b])); +} + +#[test] +fn copy_group_ungroup_and_selection_scope() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 20.]); + let b = board(&mut model, &mut env, "B", [200., 0., 0.], [100., 100., 20.]); + let copy = ok(&mut model, &mut env, "create_copy", json!({"id": a, "offset_mm": [0, 500, 0]})); + assert_eq!(copy.created.len(), 1); + near(bounds(&model, copy.created[0]).0, [0., 0.5, 0.]); + let grouped = ok(&mut model, &mut env, "group", json!({"ids": [a, b], "name": "Pair", "component": false})); + let group = grouped.created[0]; + assert_eq!(model.objects[&group].name, "Pair"); + assert_eq!(grouped.result["members"].as_array().unwrap().len(), 2); + // Parts are now inside the group: editing one needs its scope open. + let inner = grouped.result["members"][0]["id"].as_u64().unwrap(); + let message = err(&mut model, &mut env, "rename", json!({"id": inner, "name": "Inner"})); + assert!(message.contains("not editable"), "{message}"); + ok(&mut model, &mut env, "enter_object", json!({"id": group})); + assert_eq!(model.edit_context, Some(group)); + ok(&mut model, &mut env, "rename", json!({"id": inner, "name": "Inner"})); + assert!(err(&mut model, &mut env, "enter_object", json!({"id": 99999})).contains("cannot open")); + ok(&mut model, &mut env, "exit_to_root", json!({})); + assert_eq!(model.edit_context, None); + let freed = ok(&mut model, &mut env, "ungroup", json!({"ids": [group]})); + assert!(!model.objects.contains_key(&group)); + assert_eq!(freed.erased, [group]); + assert_eq!(model.objects.values().filter(|o| o.name == "Inner").count(), 1); + let any = *model.objects.keys().next().unwrap(); + let selected = ok(&mut model, &mut env, "select", json!({"ids": [any]})); + assert!(!selected.mutated); + assert_eq!(env.selection, BTreeSet::from([any])); +} + +#[test] +fn drawing_and_annotation_tools() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let outcome = ok(&mut model, &mut env, "draw_polyline", json!({ + "points_mm": [[0, 0, 0], [100, 0, 0], [100, 100, 0], [0, 100, 0]], "close": true})); + assert!(outcome.created.len() >= 5, "four edges and a face: {:?}", outcome.created); + assert_eq!(model.faces.len(), 1); + assert!(err(&mut model, &mut env, "draw_polyline", json!({"points_mm": [[0, 0, 0]], "close": false})).contains("at least 2")); + let dim = ok(&mut model, &mut env, "add_dimension", json!({"start_mm": [0, 0, 0], "end_mm": [100, 0, 0], "offset_mm": [0, -50, 0]})); + assert!(model.dimensions.contains_key(&dim.created[0])); + err(&mut model, &mut env, "add_dimension", json!({"start_mm": [0, 0, 0], "end_mm": [0, 0, 0], "offset_mm": [0, -50, 0]})); + let text = ok(&mut model, &mut env, "add_text", json!({"point_mm": [0, 0, 0], "offset_mm": [0, 0, 100], "text": "Front"})); + assert_eq!(model.texts[&text.created[0]].text, "Front"); + err(&mut model, &mut env, "add_text", json!({"point_mm": [0, 0, 0], "offset_mm": [0, 0, 100], "text": ""})); +} + +#[test] +fn joints_connect_two_boards() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let leg = board(&mut model, &mut env, "Leg", [0., 0., 0.], [40., 40., 700.]); + let apron = board(&mut model, &mut env, "Apron", [20., 0., 500.], [300., 40., 80.]); + let outcome = ok(&mut model, &mut env, "add_joint", json!({ + "a": apron, "b": leg, "kind": "mortise_tenon", "params": {"width_ratio": 0.6, "clearance_mm": 0.2}})); + assert_eq!(outcome.joints.len(), 1); + assert_eq!(model.connections.len(), 1); + match &model.connections[&outcome.joints[0]].operation { + benchup_core::connections::ConnectionOperation::Joinery(s) => { + assert_eq!(s.kind, benchup_core::joinery::JointKind::MortiseTenon); + assert_eq!(s.width_ratio, 0.6); + assert!((s.clearance - 0.0002).abs() < 1e-12); + } + other => panic!("{other:?}"), + } + let scene = ok(&mut model, &mut env, "get_scene", json!({})).result; + assert_eq!(scene["joints"][0]["kind"], "MortiseTenon"); + // A second joint between the same boards is refused by the core. + err(&mut model, &mut env, "add_joint", json!({"a": leg, "b": apron, "kind": "half_lap"})); + err(&mut model, &mut env, "add_joint", json!({"a": leg, "b": leg, "kind": "half_lap"})); + err(&mut model, &mut env, "add_joint", json!({"a": leg, "b": apron, "kind": "bogus"})); + err(&mut model, &mut env, "add_joint", json!({"a": leg, "b": apron, "kind": "finger", "params": {"width_ratio": 3}})); +} + +#[test] +fn failed_calls_do_not_set_the_turn_snapshot() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + err(&mut model, &mut env, "move", json!({"ids": [1], "delta_mm": [1, 0, 0]})); + assert!(env.before.is_none()); + let id = board(&mut model, &mut env, "A", [0., 0., 0.], [10., 10., 10.]); + let first = env.before.clone().unwrap(); + assert!(first.objects.is_empty()); + ok(&mut model, &mut env, "move", json!({"ids": [id], "delta_mm": [1, 0, 0]})); + assert_eq!(env.before.as_ref().unwrap(), &first, "snapshot stays at the first change"); +} + +#[test] +fn tool_definitions_are_strict_and_match_the_executor() { + let definitions = definitions(); + assert_eq!(definitions.len(), TOOLS.len()); + for definition in &definitions { + let name = definition.name.as_str(); + assert!(is_known(name), "{name}"); + assert!(!definition.description.is_empty()); + let parameters = &definition.input_schema; + assert_eq!(parameters["type"], "object"); + assert_eq!(parameters["additionalProperties"], false, "{name}"); + let properties = parameters["properties"].as_object().unwrap(); + for required in parameters["required"].as_array().unwrap() { + assert!(properties.contains_key(required.as_str().unwrap()), "{name}.{required}"); + } + // Every tool accepts the empty object or reports a clean argument error. + let outcome = run(&mut Model::default(), &mut ToolEnv::default(), name, json!({"__unexpected": 1})); + assert!(!outcome.ok, "{name} must reject unknown fields"); + } +} + +fn first_face(model: &Model, object: u64) -> u64 { + model.expand_entities(&BTreeSet::from([object])).into_iter().find(|f| model.faces.contains_key(f)).unwrap() +} + +#[test] +fn shared_lease_refuses_entities_outside_it() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let mine = board(&mut model, &mut env, "Mine", [0., 0., 0.], [100., 100., 100.]); + let theirs = board(&mut model, &mut env, "Theirs", [500., 0., 0.], [100., 100., 100.]); + // Not shared: no restriction. + ok(&mut model, &mut env, "move", json!({"ids": [theirs], "delta_mm": [1, 0, 0]})); + env.created.clear(); + env.lease = Some(BTreeSet::from([mine])); + let refused = run(&mut model, &mut env, "move", json!({"ids": [mine, theirs], "delta_mm": [1, 0, 0]})); + assert!(!refused.ok && !refused.mutated); + assert_eq!(refused.result["error"], "not-leased"); + assert_eq!(refused.result["hint"], "select it first so you hold the edit lease"); + let face = first_face(&model, theirs); + let attempts = [ + ("rename", json!({"id": theirs, "name": "X"})), + ("erase", json!({"ids": [theirs]})), + ("tag", json!({"ids": [theirs], "tag": "t"})), + ("add_joint", json!({"a": mine, "b": theirs, "kind": "half_lap"})), + ("push_pull", json!({"face_id": face, "distance_mm": 5})), + ("resize_board", json!({"id": theirs, "size_mm": [10, 10, 10]})), + ]; + for (name, args) in attempts { + assert_eq!(err(&mut model, &mut env, name, args), "not-leased", "{name}"); + } + // Leased entities, their faces, and reads remain available. + ok(&mut model, &mut env, "move", json!({"ids": [mine], "delta_mm": [1, 0, 0]})); + let own_face = first_face(&model, mine); + ok(&mut model, &mut env, "push_pull", json!({"face_id": own_face, "distance_mm": 5})); + ok(&mut model, &mut env, "get_object", json!({"id": theirs})); + // New entities are free to create, and then to edit within the same turn. + let fresh = board(&mut model, &mut env, "Fresh", [900., 0., 0.], [50., 50., 50.]); + ok(&mut model, &mut env, "move", json!({"ids": [fresh], "delta_mm": [1, 0, 0]})); + let copy = ok(&mut model, &mut env, "create_copy", json!({"id": theirs, "offset_mm": [0, 500, 0]})).created[0]; + ok(&mut model, &mut env, "rename", json!({"id": copy, "name": "Copy"})); + let group = ok(&mut model, &mut env, "group", json!({"ids": [fresh, copy], "name": "G", "component": false})).created[0]; + ok(&mut model, &mut env, "rename", json!({"id": group, "name": "G2"})); + assert_eq!(model.objects[&theirs].name, "Theirs"); +} + +#[test] +fn model_output_is_bounded() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [2000., 100., 100.]); + let points: Vec<[f64; 3]> = (0..1001).map(|i| [i as f64, 0., 0.]).collect(); + assert!(err(&mut model, &mut env, "draw_polyline", json!({"points_mm": points})).contains("too many points")); + let ids: Vec = vec![a; 501]; + assert!(err(&mut model, &mut env, "move", json!({"ids": ids, "delta_mm": [1, 0, 0]})).contains("too many ids")); + // Scale factor bounds. + for factor in [0.0, 0.0009, 1001.0, -2.0] { + let error = err(&mut model, &mut env, "scale", json!({"ids": [a], "center_mm": [0, 0, 0], "factor": factor})); + assert!(error.contains("factor"), "{factor}: {error}"); + } + ok(&mut model, &mut env, "scale", json!({"ids": [a], "center_mm": [0, 0, 0], "factor": 1.5})); + // In range but the result leaves the sane absolute range: restored. + assert_eq!( + err(&mut model, &mut env, "scale", json!({"ids": [a], "center_mm": [0, 0, 0], "factor": 1000.0})), + "result out of range" + ); + for _ in 0..9 { + ok(&mut model, &mut env, "move", json!({"ids": [a], "delta_mm": [100_000, 0, 0]})); + } + assert_eq!(err(&mut model, &mut env, "move", json!({"ids": [a], "delta_mm": [100_000, 0, 0]})), "result out of range"); + // Inputs: |coordinate| <= 100 m, size >= 0.1 mm, strings <= 500 chars. + assert!(err(&mut model, &mut env, "create_board", json!({"name": "x", "origin_mm": [100_001, 0, 0], "size_mm": [1, 1, 1]})).contains("out of range")); + assert!(err(&mut model, &mut env, "create_board", json!({"name": "x", "origin_mm": [0, 0, 0], "size_mm": [0.05, 1, 1]})).contains("out of range")); + let long = "t".repeat(501); + assert!(err(&mut model, &mut env, "add_text", json!({"point_mm": [0, 0, 0], "offset_mm": [0, 0, 0], "text": long})).contains("too long")); + assert!(err(&mut model, &mut env, "rename", json!({"id": a, "name": long})).contains("name")); + assert!(err(&mut model, &mut env, "tag", json!({"ids": [a], "tag": long})).contains("too long")); +} + +#[test] +fn push_pull_requires_the_whole_owner_chain_to_be_editable() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 100.]); + let b = board(&mut model, &mut env, "B", [500., 0., 0.], [100., 100., 100.]); + let outer = ok(&mut model, &mut env, "group", json!({"ids": [a], "name": "Outer", "component": false})).created[0]; + let inner = *model.objects[&outer].entities.iter().next().unwrap(); + let face = first_face(&model, inner); + // A locked ancestor, however far up, blocks the edit. + model.locked.insert(outer); + assert!(err(&mut model, &mut env, "push_pull", json!({"face_id": face, "distance_mm": 5})).contains("locked")); + model.locked.clear(); + ok(&mut model, &mut env, "push_pull", json!({"face_id": face, "distance_mm": 5})); + // A face outside the open editing scope cannot be reached through its owner. + assert!(model.enter_object(outer)); + let other = first_face(&model, b); + assert!(err(&mut model, &mut env, "push_pull", json!({"face_id": other, "distance_mm": 5})).contains("scope")); + ok(&mut model, &mut env, "push_pull", json!({"face_id": face, "distance_mm": 5})); +} + +#[test] +fn hidden_selection_is_not_revealed_by_get_scene_or_get_selection() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 20.]); + env.selection = BTreeSet::from([a]); + let shown = ok(&mut model, &mut env, "get_selection", json!({})).result; + assert_eq!(shown["selection"], json!([a])); + assert_eq!(ok(&mut model, &mut env, "get_scene", json!({})).result["selection"], json!([a])); + env.hide_selection = true; + let hidden = ok(&mut model, &mut env, "get_selection", json!({})).result; + assert_eq!(hidden, json!({"ok": true, "selection": [], "note": "The designer has turned off sharing their selection."})); + let scene = ok(&mut model, &mut env, "get_scene", json!({})).result; + assert_eq!(scene["selection"], json!([])); + assert!(scene.get("selection_total").is_none_or(|n| n == 0)); +} + +#[test] +fn tag_names_follow_the_core_limit_in_the_tool_and_the_schema() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 20.]); + ok(&mut model, &mut env, "tag", json!({"ids": [a], "tag": "x".repeat(128)})); + for long in ["x".repeat(129), "é".repeat(65)] { + assert!(err(&mut model, &mut env, "tag", json!({"ids": [a], "tag": long})).contains("too long")); + } + let board_with_long_tag = err(&mut model, &mut env, "create_board", json!({ + "name": "B", "origin_mm": [0, 0, 0], "size_mm": [1, 1, 1], "tag": "y".repeat(129)})); + assert!(board_with_long_tag.contains("too long")); + let definitions = definitions(); + let property = |tool: &str, name: &str| { + definitions.iter().find(|d| d.name == tool).unwrap().input_schema["properties"][name].clone() + }; + assert_eq!(property("tag", "tag")["maxLength"], 128); + assert_eq!(property("create_board", "tag")["maxLength"], 128); +} + +#[test] +fn the_scale_schema_states_the_range_the_executor_enforces() { + let definitions = definitions(); + let scale = definitions.iter().find(|d| d.name == "scale").unwrap(); + let factor = &scale.input_schema["properties"]["factor"]; + assert_eq!(factor["minimum"], MIN_SCALE); + assert_eq!(factor["maximum"], MAX_SCALE); + assert!(factor.get("exclusiveMinimum").is_none()); + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let a = board(&mut model, &mut env, "A", [0., 0., 0.], [100., 100., 20.]); + ok(&mut model, &mut env, "scale", json!({"ids": [a], "center_mm": [0, 0, 0], "factor": MIN_SCALE})); + assert!(err(&mut model, &mut env, "scale", json!({"ids": [a], "center_mm": [0, 0, 0], "factor": MAX_SCALE * 2.})).contains("out of range")); +} + +#[test] +fn select_is_limited_to_the_lease_in_shared_projects() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let mine = board(&mut model, &mut env, "Mine", [0., 0., 0.], [100., 100., 100.]); + let theirs = board(&mut model, &mut env, "Theirs", [500., 0., 0.], [100., 100., 100.]); + // Not shared: unchanged behaviour. + ok(&mut model, &mut env, "select", json!({"ids": [theirs]})); + env.created.clear(); + env.lease = Some(BTreeSet::from([mine])); + env.selection.clear(); + let message = err(&mut model, &mut env, "select", json!({"ids": [mine, theirs]})); + assert!(message.contains("lease"), "{message}"); + assert!(env.selection.is_empty(), "a refused select changes nothing"); + ok(&mut model, &mut env, "select", json!({"ids": [mine]})); + assert_eq!(env.selection, BTreeSet::from([mine])); + let fresh = board(&mut model, &mut env, "Fresh", [900., 0., 0.], [50., 50., 50.]); + ok(&mut model, &mut env, "select", json!({"ids": [fresh]})); +} + +#[test] +fn openai_and_mcp_adapters_keep_the_wire_shapes() { + let (openai, mcp, neutral) = (openai_tools(), mcp_tools(), definitions()); + assert_eq!(openai.len(), neutral.len()); + assert_eq!(mcp.len(), neutral.len()); + for (i, d) in neutral.iter().enumerate() { + assert_eq!(openai[i]["type"], "function"); + assert_eq!(openai[i]["function"]["name"], d.name.as_str()); + assert_eq!(openai[i]["function"]["description"], d.description.as_str()); + assert_eq!(openai[i]["function"]["parameters"], d.input_schema); + assert_eq!(openai[i].as_object().unwrap().len(), 2); + assert_eq!(openai[i]["function"].as_object().unwrap().len(), 3); + assert_eq!(mcp[i]["name"], d.name.as_str()); + assert_eq!(mcp[i]["inputSchema"], d.input_schema); + assert_eq!(mcp[i].as_object().unwrap().len(), 3); + } +} + +#[test] +fn text_arguments_behave_like_the_app_did() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + // Empty text means no arguments. + assert!(execute(&mut model, &Call::from_text("1", "get_selection", " "), &mut env).ok); + // Valid JSON text equals a JSON value. + let a = Call::from_text("1", "get_object", "{\"id\": 5}"); + assert_eq!(a.arguments, json!({"id": 5})); + // Not JSON: structured error, no panic, model untouched. + let bad = execute(&mut model, &Call::from_text("1", "get_object", "{oops"), &mut env); + assert!(!bad.ok); + assert!(bad.result["error"].as_str().unwrap().starts_with("invalid arguments: ")); + assert!(bad.result["hint"].is_string()); +} + +#[test] +fn lease_blocks_entering_and_creating_inside_foreign_groups() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + let mine = board(&mut model, &mut env, "Mine", [0., 0., 0.], [100., 100., 100.]); + let theirs = board(&mut model, &mut env, "Theirs", [500., 0., 0.], [100., 100., 100.]); + let theirs_group = ok(&mut model, &mut env, "group", json!({"ids": [theirs], "name": "TG", "component": false})).created[0]; + let my_group = ok(&mut model, &mut env, "group", json!({"ids": [mine], "name": "MG", "component": false})).created[0]; + env.created.clear(); + env.lease = Some(BTreeSet::from([my_group])); + + assert_eq!(err(&mut model, &mut env, "enter_object", json!({"id": theirs_group})), "not-leased"); + assert_eq!(model.edit_context, None); + + // Scoped inside a group someone else holds: nothing may be created. + model.edit_context = Some(theirs_group); + for (name, args) in [ + ("create_board", json!({"name": "X", "origin_mm": [0, 0, 0], "size_mm": [10, 10, 10]})), + ("draw_polyline", json!({"points_mm": [[0, 0, 0], [10, 0, 0]]})), + ("add_text", json!({"text": "hi", "position_mm": [0, 0, 0]})), + ] { + assert_eq!(err(&mut model, &mut env, name, args), "not-leased", "{name}"); + } + model.edit_context = None; + + // The leased group can be entered and created in. + ok(&mut model, &mut env, "enter_object", json!({"id": my_group})); + ok(&mut model, &mut env, "create_board", json!({"name": "In", "origin_mm": [0, 0, 0], "size_mm": [10, 10, 10]})); + ok(&mut model, &mut env, "exit_to_root", json!({})); + // Root creation still works. + board(&mut model, &mut env, "Fresh", [900., 0., 0.], [50., 50., 50.]); +} + +#[test] +fn lease_rolls_back_calls_that_alter_foreign_loose_geometry() { + let (mut model, mut env) = (Model::default(), ToolEnv::default()); + ok(&mut model, &mut env, "draw_polyline", json!({"points_mm": [[0, 0, 0], [1000, 0, 0]]})); + let mine = board(&mut model, &mut env, "Mine", [0., 500., 0.], [100., 100., 100.]); + env.created.clear(); + let edges_before = model.edges.len(); + + // Without a lease the crossing line splits the loose edge. + let mut free = model.clone(); + ok(&mut free, &mut ToolEnv::default(), "draw_polyline", json!({"points_mm": [[500, 0, 0], [500, 300, 0]]})); + assert!(free.edges.len() > edges_before + 1, "crossing should split the loose edge"); + + env.lease = Some(BTreeSet::from([mine])); + assert_eq!( + err(&mut model, &mut env, "draw_polyline", json!({"points_mm": [[500, 0, 0], [500, 300, 0]]})), + "not-leased" + ); + assert_eq!(model.edges.len(), edges_before); + // Geometry that touches nothing existing is fine. + ok(&mut model, &mut env, "draw_polyline", json!({"points_mm": [[0, 5000, 0], [100, 5000, 0]]})); +} diff --git a/crates/benchup-tools/src/scene.rs b/crates/benchup-tools/src/scene.rs new file mode 100644 index 0000000..21b40f9 --- /dev/null +++ b/crates/benchup-tools/src/scene.rs @@ -0,0 +1,270 @@ +//! Compact scene description sent to the model. Geometry in the document is in +//! metres; everything the model sees or sends is in millimetres. +use benchup_core::{ + DVec3, MaterialId, Model, ObjectKind, StockMaterial, connections::ConnectionOperation, faces, +}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; + +pub const SCENE_BUDGET: usize = 24_000; +const MAX_FACES: usize = 80; +const MAX_LISTED_SELECTION: usize = 200; +const MAX_LISTED_TAGS: usize = 100; + +/// Metres to millimetres, rounded to 0.1 mm. +pub fn mm(metres: f64) -> f64 { + (metres * 10_000.).round() / 10. +} +pub fn from_mm(millimetres: f64) -> f64 { + millimetres / 1000. +} +pub fn point_mm(p: DVec3) -> Value { + json!([mm(p.x), mm(p.y), mm(p.z)]) +} +fn unit(v: DVec3) -> Value { + let r = |x: f64| (x * 1000.).round() / 1000.; + json!([r(v.x), r(v.y), r(v.z)]) +} + +pub fn kind_of(model: &Model, id: u64) -> &'static str { + if let Some(object) = model.objects.get(&id) { + match object.kind { + ObjectKind::Group => "group", + ObjectKind::Component { .. } => "component", + } + } else if model.faces.contains_key(&id) { + "face" + } else if model.edges.contains_key(&id) { + "edge" + } else if model.dimensions.contains_key(&id) { + "dimension" + } else if model.texts.contains_key(&id) { + "text" + } else if model.guides.contains_key(&id) { + "guide" + } else if model.connections.contains_key(&id) { + "joint" + } else { + "missing" + } +} + +pub fn bounds_json(model: &Model, ids: &BTreeSet) -> Option { + let (lo, hi) = model.selection_bounds(ids)?; + Some(json!({"min": point_mm(lo), "max": point_mm(hi), "size": point_mm(hi - lo)})) +} + +fn axis_name(v: DVec3) -> Value { + for (name, axis) in [("x", DVec3::X), ("y", DVec3::Y), ("z", DVec3::Z)] { + if v.dot(axis).abs() > 0.999 { + return json!(name); + } + } + unit(v) +} + +fn material_json(model: &Model, object: &benchup_core::Object) -> Option { + let stock = model.object_stock_material(object)?; + Some(json!({"id": object.stock_material_id, "name": stock.name})) +} + +pub fn object_entry(model: &Model, id: u64) -> Option { + let object = model.objects.get(&id)?; + let mut entry = json!({ + "id": id, + "name": object.name, + "kind": kind_of(model, id), + }); + let map = entry.as_object_mut()?; + if let Some(parent) = model.parent(id) { + map.insert("parent".into(), json!(parent)); + } + if let Some(tag) = model.inherited_tag(id) { + map.insert("tag".into(), json!(tag.name)); + } + if let Some(bounds) = bounds_json(model, &BTreeSet::from([id])) { + map.insert("bounds_mm".into(), json!({"min": bounds["min"], "max": bounds["max"]})); + map.insert("size_mm".into(), bounds["size"].clone()); + } + if let Some(material) = material_json(model, object) { + map.insert("material".into(), material); + } + if let Some(grain) = object.world_grain_axis() { + map.insert("grain".into(), axis_name(grain)); + } + if model.is_hidden(id) { + map.insert("hidden".into(), json!(true)); + } + if model.is_locked(id) { + map.insert("locked".into(), json!(true)); + } + Some(entry) +} + +pub fn stock_list( + model: &Model, + catalog: &BTreeMap, +) -> Vec { + let mut all: BTreeMap = model.stock_materials.iter().map(|(k, v)| (*k, v)).collect(); + all.extend(catalog.iter().map(|(k, v)| (*k, v))); + all.into_iter() + .map(|(id, stock)| { + let [t, w, l] = stock.dimensions.map(|tenths| tenths as f64 / 10.); + json!({"id": id, "name": stock.name, "thickness_mm": t, "width_mm": w, "length_mm": l}) + }) + .collect() +} + +fn joint_json(model: &Model, id: u64) -> Option { + let connection = model.connections.get(&id)?; + let kind = match &connection.operation { + ConnectionOperation::Joinery(settings) => json!(format!("{:?}", settings.kind)), + ConnectionOperation::Fasteners(_) => json!("Fasteners"), + }; + Some(json!({"id": id, "a": connection.members[0], "b": connection.members[1], "kind": kind})) +} + +/// Everything the model needs to plan an edit, within `budget` characters. +/// Selected objects and those in the current editing scope are listed first. +pub fn summary( + model: &Model, + selection: &BTreeSet, + catalog: &BTreeMap, + budget: usize, +) -> Value { + let stock = stock_list(model, catalog); + let joints: Vec<_> = model.connections.keys().take(100).filter_map(|id| joint_json(model, *id)).collect(); + let mut out = json!({ + "units": "mm", + "up_axis": "z", + "edit_path": model.edit_path(), + "selection": selection.iter().take(MAX_LISTED_SELECTION).collect::>(), + "tags": model.tags.values().take(MAX_LISTED_TAGS).map(|t| json!({"id": t.id, "name": t.name, "visible": t.visible})).collect::>(), + "stock_catalog": stock.iter().take(40).collect::>(), + "joints": joints, + "loose_geometry": { + "edges": model.root_entities().iter().filter(|id| model.edges.contains_key(id)).count(), + "faces": model.root_entities().iter().filter(|id| model.faces.contains_key(id)).count(), + }, + "object_count": model.objects.len(), + }); + let in_scope: BTreeSet = model.selectable_entities(); + let mut order: Vec = Vec::with_capacity(model.objects.len()); + order.extend(selection.iter().filter(|id| model.objects.contains_key(id))); + order.extend(model.objects.keys().filter(|id| in_scope.contains(id) && !selection.contains(id))); + order.extend(model.objects.keys().filter(|id| !in_scope.contains(id) && !selection.contains(id))); + let mut used = out.to_string().len() + 160; + let mut objects = Vec::new(); + for id in &order { + let Some(entry) = object_entry(model, *id) else { continue }; + let cost = entry.to_string().len() + 1; + if used + cost > budget { + break; + } + used += cost; + objects.push(entry); + } + if selection.len() > MAX_LISTED_SELECTION { + out["selection_total"] = json!(selection.len()); + } + let omitted = order.len() - objects.len(); + out["objects"] = Value::Array(objects); + if omitted > 0 { + out["omitted"] = json!(omitted); + out["hint"] = json!("Scene truncated: use find_objects{query} or get_object{id} to inspect omitted objects."); + } + out +} + +/// Face normals follow drawing winding, so a closed part can have inward ones. +/// Report and extrude along the outward direction: away from the owning +/// part's center. Returns the factor (1 or -1) that maps the stored normal to +/// the outward one. +pub fn outward_sign(model: &Model, face_id: u64) -> f64 { + let outward = || -> Option { + let face = model.faces.get(&face_id)?; + let normal = faces::plane(model, &face.vertices)?.normal; + let owner = model.parent(face_id)?; + let center = model.selection_center(&BTreeSet::from([owner]))?; + let toward_face = model.face_center(face)? - center; + Some(if toward_face.dot(normal) < -1e-9 { -1. } else { 1. }) + }; + outward().unwrap_or(1.) +} + +fn face_json(model: &Model, id: u64) -> Option { + let face = model.faces.get(&id)?; + let n = faces::plane(model, &face.vertices)?.normal * outward_sign(model, id); + let facing = [(DVec3::X, "x"), (DVec3::Y, "y"), (DVec3::Z, "z")] + .into_iter() + .find(|(axis, _)| n.dot(*axis).abs() > 0.999) + .map(|(axis, name)| format!("{}{name}", if n.dot(axis) > 0. { '+' } else { '-' })); + let mut entry = json!({ + "id": id, + "normal": unit(n), + "area_mm2": (model.face_area(face) * 1.0e6).round(), + }); + if let Some(center) = model.face_center(face) { + entry["center_mm"] = point_mm(center); + } + if let Some(facing) = facing { + entry["facing"] = json!(facing); + } + Some(entry) +} + +/// One entity in detail. Objects list their faces so `push_pull` can target one. +pub fn describe(model: &Model, id: u64) -> Option { + if let Some(mut entry) = object_entry(model, id) { + let object = &model.objects[&id]; + entry["children"] = json!(object.entities); + let mut all: Vec = model + .expand_entities(&BTreeSet::from([id])) + .into_iter() + .filter(|f| model.faces.contains_key(f)) + .collect(); + let total = all.len(); + all.truncate(MAX_FACES); + entry["faces"] = Value::Array(all.iter().filter_map(|f| face_json(model, *f)).collect()); + if total > MAX_FACES { + entry["faces_omitted"] = json!(total - MAX_FACES); + } + return Some(entry); + } + if let Some(face) = face_json(model, id) { + let mut face = face; + face["kind"] = json!("face"); + if let Some(parent) = model.parent(id) { + face["parent"] = json!(parent); + } + return Some(face); + } + if let Some(joint) = joint_json(model, id) { + return Some(joint); + } + if model.contains_entity(&id) { + let mut entry = json!({"id": id, "kind": kind_of(model, id)}); + if let Some(bounds) = bounds_json(model, &BTreeSet::from([id])) { + entry["bounds_mm"] = json!({"min": bounds["min"], "max": bounds["max"]}); + } + return Some(entry); + } + None +} + +/// Details for entities the prompt names, keyed by id, within `budget` +/// characters; the rest are counted under `omitted` (use get_object for them). +pub fn references(model: &Model, ids: &BTreeSet, budget: usize) -> Value { + let mut out = serde_json::Map::new(); + let mut used = 0; + for (index, id) in ids.iter().enumerate() { + let entry = describe(model, *id).unwrap_or_else(|| json!({"id": id, "kind": "missing"})); + used += entry.to_string().len() + 8; + if used > budget && index > 0 { + out.insert("omitted".into(), json!(ids.len() - index)); + break; + } + out.insert(id.to_string(), entry); + } + Value::Object(out) +}