diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 762eadb55..89ee1e357 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -9,7 +9,7 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_geom::mesh_distance::box_gap; use solidcraft_geom::prelude::*; use solidcraft_geom::{Aabb3, Mesh}; @@ -17,9 +17,20 @@ use solidcraft_kernel::{BodyDistance, DistanceShape}; use super::CommandSpec; use crate::params::{bad, num, str_, string_list}; +use crate::schema::clearance::{ + Clearance as ClearanceReply, ClearanceParams, MAX_CLEARANCE, MAX_NEAREST, NearPair, Neighbour, Overlap, OverlapBounds, Unchecked, +}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", clearance).icon("interference").noundo().params( +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", crate::checked!("inspect.clearance", clearance)) + .icon("interference") + .noundo() + .contract(&CONTRACT) + .output(output_schema_for::) + .params( "bodies?: [names] (default: every solid body, in world placement, but those in `against`; mesh bodies are not measured); against?: [names] (only pairs with one body in `bodies` and the other here); \ min_volume?: mm³ (default 0.01: smaller overlaps count as contact); clearance?: mm (default 0: report pairs closer than this); \ nearest?: n (each body of `bodies` gets its n nearest others); skip_within?: \"occurrence\" (pairs of bodies of one occurrence) | \ @@ -34,10 +45,6 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "C const MAX_BODIES: usize = 20_000; /// Most pairs whose grown boxes meet that one call measures. const MAX_PAIRS: usize = 200_000; -/// Most neighbours a body's `nearest` list holds. -const MAX_NEAREST: usize = 1000; -/// Largest clearance (mm). -const MAX_CLEARANCE: f64 = 1e6; #[derive(Clone, Copy, PartialEq, Eq)] enum SkipWithin { @@ -261,48 +268,56 @@ fn clearance(s: &mut Session, p: &Value) -> Result { for k in ["bodies", "against"] { asked.extend(string_list(cmd, p, k)?); } - let mut unchecked: Vec = mesh_bodies + let mut unchecked: Vec = mesh_bodies .iter() .filter(|b| p.get("bodies").is_none_or(Value::is_null) || asked.contains(&b.name)) - .map(|b| json!({"a": b.name, "b": null, "reason": super::interference::MESH_NOT_CHECKED})) + .map(|b| Unchecked { a: b.name.clone(), b: None, reason: super::interference::MESH_NOT_CHECKED.to_string() }) .collect(); let name = |i: usize| solid.get(i).map_or("", |b| b.name.as_str()); + let pair = |i: usize, j: usize, reason: String| Unchecked { a: name(i).to_string(), b: Some(name(j).to_string()), reason }; for (&(i, j), r) in close.iter().zip(results) { let r = match r { Ok(r) => r, Err(e) => { - unchecked.push(json!({"a": name(i), "b": name(j), "reason": e.to_string()})); + unchecked.push(pair(i, j, e.to_string())); continue; } }; if let Some(reason) = r.unchecked { - unchecked.push(json!({"a": name(i), "b": name(j), "reason": reason})); + unchecked.push(pair(i, j, reason)); continue; } if let Some((volume, area, bbox, center)) = r.overlap && volume >= min_volume { - overlaps.push(json!({"a": name(i), "b": name(j), "volume_mm3": volume, "area_mm2": area, - "bbox": {"min": bbox.min, "max": bbox.max}, "center": center})); + overlaps.push(Overlap { + a: name(i).to_string(), + b: name(j).to_string(), + volume_mm3: volume, + area_mm2: area, + bbox: OverlapBounds { min: bbox.min.into(), max: bbox.max.into() }, + center: center.into(), + }); known.insert((i, j), 0.0); continue; } let Some(d) = r.distance else { continue }; known.insert((i, j), d.distance); if d.distance < gap { - let mut e = json!({"a": name(i), "b": name(j), "distance_mm": d.distance, "from": d.from, "to": d.to}); - if let Some((v, ..)) = r.overlap.filter(|o| o.0 > 0.0) { - e["overlap_mm3"] = json!(v); - } - if !d.exact { - e["exact"] = json!(false); - } - near.push(e); + near.push(NearPair { + a: name(i).to_string(), + b: name(j).to_string(), + distance_mm: d.distance, + from: d.from.into(), + to: d.to.into(), + overlap_mm3: r.overlap.filter(|o| o.0 > 0.0).map(|o| o.0), + exact: (!d.exact).then_some(false), + }); } } - near.sort_by(|x, y| x["distance_mm"].as_f64().unwrap_or(0.0).total_cmp(&y["distance_mm"].as_f64().unwrap_or(0.0))); + near.sort_by(|x, y| x.distance_mm.total_cmp(&y.distance_mm)); - let mut nearest_out = serde_json::Map::new(); + let mut nearest_out = BTreeMap::new(); if nearest > 0 { let lists = nearest_lists(&subjects, n, nearest, &boxes, &allowed, &mut known, |pairs| { solidcraft_kernel::map_with_local_pools(pairs, usize::MAX, |&(i, j)| { @@ -311,23 +326,25 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }) }); for (i, list) in lists { - let rows: Vec = list.iter().map(|&(j, d)| json!({"body": name(j), "distance_mm": d})).collect(); - nearest_out.insert(name(i).to_string(), Value::Array(rows)); + let rows = list.iter().map(|&(j, d)| Neighbour { body: name(j).to_string(), distance_mm: d }).collect(); + nearest_out.insert(name(i).to_string(), rows); } } - Ok(json!({ - "overlaps": overlaps, - "near": near, - "nearest": nearest_out, - "unchecked": unchecked, - "bodies": subjects.len(), - "pairs_checked": close.len(), - "pairs_reused": reused, - "pairs_pruned": total.saturating_sub(close.len()), - "truncated": truncated > 0, - "ms": started.elapsed().as_secs_f64() * 1000.0, - })) + let reply = ClearanceReply { + overlaps, + near, + nearest: nearest_out, + unchecked, + bodies: subjects.len(), + pairs_checked: close.len(), + pairs_reused: reused, + pairs_pruned: total.saturating_sub(close.len()), + truncated: truncated > 0, + ms: started.elapsed().as_secs_f64() * 1000.0, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } /// One pair: its overlap when the meshes meet or one holds the other, otherwise its distance diff --git a/crates/engine/src/schema/clearance.rs b/crates/engine/src/schema/clearance.rs new file mode 100644 index 000000000..f5e8ca186 --- /dev/null +++ b/crates/engine/src/schema/clearance.rs @@ -0,0 +1,197 @@ +//! Contract and result types for `inspect.clearance` in `cmd/clearance.rs` (#11051). + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use super::check::whole; +use super::types::StringList; +use crate::params; + +/// Most neighbours a body's `nearest` list holds. +pub const MAX_NEAREST: usize = 1000; +/// Largest clearance (mm). +pub const MAX_CLEARANCE: f64 = 1e6; + +/// Find the solid bodies that overlap, and those closer than `clearance`, in world placement. +/// Distances are measured on the exact faces and edges; the meshes only rule pairs out. Mesh +/// bodies aren't measured: each is listed in `unchecked`. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ClearanceParams { + /// The bodies to check (default: every solid body but those in `against`). + #[serde(default)] + pub bodies: Option, + /// Only pairs with one body in `bodies` and the other here. + #[serde(default)] + pub against: Option, + /// Smaller overlaps count as contact, in mm³ (default 0.01). + #[serde(default, deserialize_with = "min_volume")] + #[schemars(schema_with = "min_volume_schema")] + pub min_volume: Option, + /// Report pairs closer than this, in mm: 0 to 1 000 000 (default 0). + #[serde(default, deserialize_with = "clearance")] + #[schemars(schema_with = "clearance_schema")] + pub clearance: Option, + /// A gap below this is contact, 0, in mm: 0 to 1 (default 1e-6). + #[serde(default, deserialize_with = "tolerance")] + #[schemars(schema_with = "tolerance_schema")] + pub tolerance: Option, + /// Each body of `bodies` gets its this many nearest others, 0 to 1000 (default 0); a + /// fraction is rounded down. + #[serde(default, deserialize_with = "nearest")] + #[schemars(schema_with = "nearest_schema")] + pub nearest: Option, + #[serde(default)] + pub skip_within: Option, +} + +/// A number from 0 to `max`, read as the handler reads it (`params::num`: finite, under 1e9 in +/// size), with its message; `null` is the default. +macro_rules! up_to { + ($read:ident, $schema:ident, $key:literal, $max:expr) => { + fn $read<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + v => v + .as_f64() + .and_then(params::finite) + .filter(|x| (0.0..=$max).contains(x)) + .map(Some) + .ok_or_else(|| D::Error::custom(whole(format!("`{}` must be a number from 0 to {}", $key, $max)))), + } + } + + fn $schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["number", "null"], "minimum": 0, "maximum": f64::min($max, 1e9), "exclusiveMaximum": 1e9}) + } + }; +} + +up_to!(min_volume, min_volume_schema, "min_volume", f64::MAX); +up_to!(clearance, clearance_schema, "clearance", MAX_CLEARANCE); +up_to!(tolerance, tolerance_schema, "tolerance", 1.0); +up_to!(nearest, nearest_schema, "nearest", MAX_NEAREST as f64); + +/// Pairs not to check: of bodies of one occurrence (`occurrence`), or inside one placed +/// component, its subcomponents included (`component`). `null` checks every pair. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SkipWithin { + Occurrence, + Component, +} + +impl<'de> Deserialize<'de> for SkipWithin { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)?.as_str() { + Some("occurrence") => Ok(SkipWithin::Occurrence), + Some("component") => Ok(SkipWithin::Component), + _ => Err(D::Error::custom(whole("`skip_within` must be \"occurrence\", \"component\" or null"))), + } + } +} + +impl JsonSchema for SkipWithin { + fn schema_name() -> Cow<'static, str> { + "SkipWithin".into() + } + fn inline_schema() -> bool { + true + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "Pairs not to check: of bodies of one occurrence (`occurrence`), or inside one placed component, its subcomponents included (`component`). null checks every pair.", + "enum": ["occurrence", "component", null] + }) + } +} + +/// What `inspect.clearance` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Clearance { + /// Pairs that share at least `min_volume`. + pub overlaps: Vec, + /// Pairs closer than `clearance`, nearest first; a pair in contact is at 0. + pub near: Vec, + /// With `nearest`: each body of `bodies`, with its nearest others. + pub nearest: BTreeMap>, + /// Pairs whose overlap couldn't be worked out, and each mesh body, which isn't measured + /// (`b` is then `null`). + pub unchecked: Vec, + /// How many solid bodies were checked. + pub bodies: usize, + pub pairs_checked: usize, + /// Of those, the pairs measured by an earlier call: neither body changed or moved since. + pub pairs_reused: usize, + /// Pairs ruled out by their boxes. + pub pairs_pruned: usize, + /// Whether there were more pairs than one call measures. + pub truncated: bool, + /// How long it took (ms). + pub ms: f64, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Two bodies that overlap. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Overlap { + pub a: String, + pub b: String, + /// The volume they share (mm³). + pub volume_mm3: f64, + /// The area of the shared volume's surface (mm²). + pub area_mm2: f64, + pub bbox: OverlapBounds, + pub center: [f64; 3], +} + +/// A box, by its corners. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OverlapBounds { + pub min: [f64; 3], + pub max: [f64; 3], +} + +/// Two bodies closer than `clearance`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct NearPair { + pub a: String, + pub b: String, + pub distance_mm: f64, + /// The nearest point on `a`. + pub from: [f64; 3], + /// The nearest point on `b`. + pub to: [f64; 3], + /// For a contact: the volume they share, below `min_volume` (mm³). + #[serde(skip_serializing_if = "Option::is_none")] + pub overlap_mm3: Option, + /// `false` when measured on the meshes; absent when measured on the exact faces and edges. + #[serde(skip_serializing_if = "Option::is_none")] + pub exact: Option, +} + +/// One of a body's nearest others. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Neighbour { + pub body: String, + pub distance_mm: f64, +} + +/// A pair, or a mesh body, that wasn't measured. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Unchecked { + pub a: String, + /// The other body; `null` for a mesh body. + pub b: Option, + pub reason: String, +} + +#[cfg(test)] +#[path = "clearance_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/clearance_tests.rs b/crates/engine/src/schema/clearance_tests.rs new file mode 100644 index 000000000..edce0c205 --- /dev/null +++ b/crates/engine/src/schema/clearance_tests.rs @@ -0,0 +1,62 @@ +use serde_json::{Value, json}; + +use super::{Clearance, ClearanceParams}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["against", "bodies", "clearance", "min_volume", "nearest", "skip_within", "tolerance"]); +} + +/// The handler reads the numbers and `skip_within` before the bodies, so each of these fails +/// the same way on a design with no bodies. +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("inspect.clearance", json!({"min_volume": -1})), + ("inspect.clearance", json!({"min_volume": "x"})), + ("inspect.clearance", json!({"min_volume": 2e9})), + ("inspect.clearance", json!({"clearance": 2e6})), + ("inspect.clearance", json!({"tolerance": 2})), + ("inspect.clearance", json!({"nearest": 1001})), + ("inspect.clearance", json!({"skip_within": "x"})), + ("inspect.clearance", json!({"skip_within": 5})), + ("inspect.clearance", json!({"bodies": ["Nope"]})), + ("inspect.clearance", json!({"against": "Nope"})), + ]); +} + +/// #11051: a clearance check replies as its output schema says, in Warn without warnings for +/// good calls and with them for a misspelt key: two overlapping boxes and a third 2 mm away, +/// checked with every key, and with `against` alone. +#[test] +fn a_clearance_check_replies_with_its_schema() { + let schema = output_schema_for::(); + let matches = |r: &Value, warned: bool| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert_eq!(r.get("param_warnings").is_some(), warned, "{r}"); + }; + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 5, 5], "body_name": "B", "operation": "new"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [12, -20, 0], "body_name": "C", "operation": "new"})); + let r = run(&mut s, "inspect.clearance", json!({})); + matches(&r, false); + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(1), "{r}"); + let r = run( + &mut s, + "inspect.clearance", + json!({"bodies": ["A", "B"], "against": "C", "min_volume": 0.01, "clearance": 30, "tolerance": 1e-6, "nearest": 2, "skip_within": "occurrence"}), + ); + matches(&r, false); + assert!(r["near"].as_array().is_some_and(|n| !n.is_empty()) && r["nearest"]["A"].is_array(), "{r}"); + matches(&run(&mut s, "inspect.clearance", json!({"against": ["A"], "skip_within": null})), false); + matches(&run(&mut s, "inspect.clearance", json!({"clearence": 3})), true); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 2981f17f7..546cc80d8 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -57,6 +57,7 @@ mod tests; pub mod appearance; pub mod bom; pub mod browser; +pub mod clearance; pub mod component; pub mod config; pub mod construct; diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index a1d80a689..46d93a58a 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -78,7 +78,6 @@ frame.member frame.profile.insert frame.profile.list frame.profile.properties -inspect.clearance inspect.compare inspect.interference inspect.measure