diff --git a/assets/locales/pending/fastener-checks.json b/assets/locales/pending/fastener-checks.json new file mode 100644 index 00000000000..939b8c3be0c --- /dev/null +++ b/assets/locales/pending/fastener-checks.json @@ -0,0 +1,26 @@ +{ + "en": { + "cmd.inspect.fastener_checks": "Fastener Checks" + }, + "de": { + "cmd.inspect.fastener_checks": "Verbindungselemente prüfen" + }, + "ko": { + "cmd.inspect.fastener_checks": "체결 부품 검사" + }, + "ar": { + "cmd.inspect.fastener_checks": "فحوصات المثبّتات" + }, + "he": { + "cmd.inspect.fastener_checks": "בדיקות מחברים" + }, + "ja": { + "cmd.inspect.fastener_checks": "締結部品チェック" + }, + "vi": { + "cmd.inspect.fastener_checks": "Kiểm tra chi tiết lắp xiết" + }, + "zh": { + "cmd.inspect.fastener_checks": "紧固件检查" + } +} diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 70b7b726d34..f1878555997 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -1001,6 +1001,9 @@ fn finish_decode( } } for study in &d.assembly.studies { + if [study.duration_s, study.sample_rate_hz].into_iter().flatten().any(|x| !x.is_finite() || x <= 0.0 || x > MAX_REAL) { + return Err(DocError::Invalid(format!("damaged design: motion study `{}` has an invalid duration or sample rate", study.name))); + } if study.configs.len() > 256 { return Err(DocError::Invalid(format!("damaged design: motion study `{}` has too many configuration keys", study.name))); } diff --git a/crates/doc/src/format/pending/motion-study-time-base.rs b/crates/doc/src/format/pending/motion-study-time-base.rs new file mode 100644 index 00000000000..1a91e7adddb --- /dev/null +++ b/crates/doc/src/format/pending/motion-study-time-base.rs @@ -0,0 +1,9 @@ +//! A motion study given in physical time keeps its time base in `MotionStudy::duration_s` and +//! `MotionStudy::sample_rate_hz` (seconds, and steps per second; step `k` is at `k / sample_rate_hz` +//! seconds) (#24217). Both are saved only when set, so studies timed in steps, and every design +//! made before, save byte for byte as they did. The study's keys keep their points in steps (a key +//! given at `time_s` is stored at `time_s * sample_rate_hz`), so playing and exporting are unchanged. +//! Older designs have neither field, default to none, and need no migration step. +//! The last release warns about the newer format and opens the design; it plays the study by its +//! steps as before, and an older release keeps the two fields when it saves (the newer-file +//! handling keeps unknown fields), without using them. diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index f1329f42cc2..3db11ef88ff 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -399,6 +399,16 @@ pub struct MotionStudy { pub name: String, pub steps: u32, pub keys: Vec, + /// The study's length in seconds, when it was given in time (`sample_rate_hz` is then set + /// too): `steps` is `round(duration_s * sample_rate_hz)`, or, for a study made from a trajectory + /// file (an import), that product rounded up so the last sample is never past `steps`. Saved + /// only when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_s: Option, + /// Steps per second, when the study's keys were given in time: step `k` is at `k / sample_rate_hz` + /// seconds, and a key's step is its time times this rate. Saved only when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sample_rate_hz: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub configs: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -542,7 +552,16 @@ mod tests { // Adding the study referencing `stroke` and local `t`: `used_params` includes `stroke` (via curve_exprs) // and parameter renaming skips local `t` on curves, while blocking renames to `t`/`step` when referenced. - doc.assembly.studies.push(MotionStudy { id: 1, name: "S".into(), steps: 10, keys: vec![curve_key], configs: Vec::new(), params: Vec::new() }); + doc.assembly.studies.push(MotionStudy { + id: 1, + name: "S".into(), + steps: 10, + keys: vec![curve_key], + duration_s: None, + sample_rate_hz: None, + configs: Vec::new(), + params: Vec::new(), + }); assert!(doc.rename_param("t", "thick").is_ok()); assert_eq!(doc.assembly.studies[0].keys[0].curve(0), Some("stroke * t^2 + step")); assert!(doc.rename_param("stroke", "travel").is_ok()); @@ -570,6 +589,8 @@ mod tests { name: "Modes".into(), steps: 20, keys: Vec::new(), + duration_s: None, + sample_rate_hz: None, configs: vec![StudyConfigKey { step: 0, config: "Closed".into() }, StudyConfigKey { step: 10, config: "Open".into() }], params: vec![ StudyParamKey { step: 0, name: "gap".into(), value: "base * 1".into() }, diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs index a939cd5abf3..918ea544875 100644 --- a/crates/doc/src/params.rs +++ b/crates/doc/src/params.rs @@ -2593,6 +2593,8 @@ pub(crate) mod param_rows_tests { name: "S".into(), steps: 10, keys: Vec::new(), + duration_s: None, + sample_rate_hz: None, configs: Vec::new(), params: vec![ crate::motion::StudyParamKey { step: 0, name: "caption".into(), value: "width".into() }, diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index b61b6475c97..6642a9b6121 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -96,8 +96,26 @@ fn documents() -> (Document, Document) { ]; let key = |joint| StudyKey { joint, index: 0, points: vec![(0.0, 0.0), (10.0, 0.5)], exprs: Vec::new(), easings: Vec::new(), curves: Vec::new() }; source.assembly.studies = vec![ - MotionStudy { id: 3, name: "Internal study".into(), steps: 10, keys: vec![key(1), key(2)], configs: Vec::new(), params: Vec::new() }, - MotionStudy { id: 4, name: "Cross study".into(), steps: 10, keys: vec![key(1), key(3)], configs: Vec::new(), params: Vec::new() }, + MotionStudy { + id: 3, + name: "Internal study".into(), + steps: 10, + keys: vec![key(1), key(2)], + duration_s: None, + sample_rate_hz: None, + configs: Vec::new(), + params: Vec::new(), + }, + MotionStudy { + id: 4, + name: "Cross study".into(), + steps: 10, + keys: vec![key(1), key(3)], + duration_s: None, + sample_rate_hz: None, + configs: Vec::new(), + params: Vec::new(), + }, ]; source.assembly.exploded = vec![ ExplodedView { id: 5, name: "Internal explode".into(), moves: vec![(1, Vec3::X * 10.0), (2, Vec3::Y * 20.0)] }, diff --git a/crates/engine/src/cmd/fastener_checks.rs b/crates/engine/src/cmd/fastener_checks.rs new file mode 100644 index 00000000000..4396bc554fd --- /dev/null +++ b/crates/engine/src/cmd/fastener_checks.rs @@ -0,0 +1,471 @@ +//! Fastener Checks (`inspect.fastener_checks`, #24216): for each placed standard fastener, the +//! solid wall between its hole and the outside of the body it is seated in, and whether a tool +//! can reach it. Read-only: nothing is added to the design. +//! +//! The wall is measured on the exact B-rep by [`solidcraft_kernel::hole_ligament`]: the shortest +//! distance from the hole's cylinders and cones (a bore, its countersink or counterbore) to the +//! host's nearest other face (the outer boundary or another hole), leaving out the planes square to +//! the axis: the wall around the hole, not the floor under a blind hole. The tool is a socket (about a +//! hex head or a nut) or a hex key (into a socket in the head): a cylinder about the fastener's +//! axis along the way its head points, checked as `inspect.socket_reach` checks a socket's space. +//! `parts.fastener` adds the same checks to its reply on request and never refuses a placement +//! because of them. + +use serde_json::Value; + +use super::CommandSpec; +use super::socket_reach::{Space, blockers}; +use crate::params::{bad, bool_, num, string_list}; +use crate::schema::fastener_checks::{FastenerCheck, FastenerChecks, FastenerChecksParams, MAX_EDGE_DISTANCE, NearestFace, ToolClearance}; +use crate::schema::parts::InsertedPart; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session, Vec3}; + +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("inspect.fastener_checks", "Fastener Checks", crate::checked!("inspect.fastener_checks", fastener_checks)) + .icon("fastener") + .noundo() + .read_only() + .contract(&CONTRACT) + .output(output_schema_for::) + .params( + "fasteners?: [components or occurrences, by name or id] (default: every placed standard part); min_edge_distance_mm?: mm (a hole nearer the outside of its body is a violation); \ + check_tool_clearance?: bool (also check that a socket or hex key reaches the head along the axis) \ + → fasteners: [{fastener, component, occurrence, position, axis (the way the head points), host (the body whose hole it sits in), hole_diameter_mm, \ + edge_distance_mm (the thinnest solid wall: from the hole's bore, countersink or counterbore to the host's other faces, except planes square to the axis, exact), \ + nearest_face: {body, face, point, hole_point}, violation?, unchecked? (why no distance), tool?: {tool: socket | hex key, diameter_mm, length_mm, origin, direction, clear?, reason, blocked, unchecked}}], violations. \ + Nothing is added to the design", + ), +]; + +/// A hole whose nearer end lies this far (mm) from the fastener's seat, along its axis, is the one +/// it sits in: a countersunk head seats a little above or below the rim it was picked on. The seat +/// is that of the part seated directly on the host, so a washer's thickness does not count. +const SEAT_REACH: f64 = 2.0; + +/// The fastener's envelope (its head, or the widest standard part stacked under it) grown by this +/// many mm is the widest bore on the axis that counts as its hole. +const HOLE_MARGIN: f64 = 1.0; + +/// Most bodies and occurrences one call goes through, as `inspect.socket_reach` limits bodies. +const MAX_BODIES: usize = 20_000; +const MAX_OCCURRENCES: usize = 20_000; + +/// Parts are coaxial when their axes agree within this (unit vectors) and the line is off by less +/// than [`LINE_TOL`] mm. +const AXIS_TOL: f64 = 1e-6; +const LINE_TOL: f64 = 1e-3; + +/// A socket's outside diameter over the hex's width across flats: a six-point socket's wall. +const SOCKET_FACTOR: f64 = 1.5; + +/// A hex key's width over the socket's width across flats: its corners, a little clear. +const KEY_FACTOR: f64 = 1.2; + +/// How far past the drive's top the tool's space runs (mm). +const TOOL_LENGTH: f64 = 30.0; + +/// The tool's space starts this far (mm) off the plane it would otherwise start on, which the +/// host's face or the part's head lies in: faces that only touch are not an overlap to work out. +const TOOL_LIFT: f64 = 0.01; + +/// One body of the world: its name, its definition's, its component, the occurrences it is placed +/// through and its placement, as `Document::body_frames_with_source` gives them. +type Frame = (String, String, u64, Vec, solidcraft_doc::Mat); + +/// What to check besides what every fastener gets. +pub(crate) struct Options { + /// A hole nearer the outside than this is a violation. + pub min_edge: Option, + /// Check that a tool reaches the fastener. + pub tool: bool, +} + +/// The options a call gives, `null` and a key left out being the same. +pub(crate) fn options(p: &Value, cmd: &str) -> Result { + let min_edge = match p.get("min_edge_distance_mm") { + None | Some(Value::Null) => None, + Some(_) => Some( + num(p, "min_edge_distance_mm") + .filter(|x| *x >= 0.0 && *x <= MAX_EDGE_DISTANCE) + .ok_or_else(|| bad(cmd, format!("`min_edge_distance_mm` must be a length in mm from 0 to {MAX_EDGE_DISTANCE}")))?, + ), + }; + let tool = match p.get("check_tool_clearance") { + None | Some(Value::Null) => false, + Some(_) => bool_(p, "check_tool_clearance").ok_or_else(|| bad(cmd, "`check_tool_clearance` must be true or false"))?, + }; + Ok(Options { min_edge, tool }) +} + +fn fastener_checks(s: &mut Session, p: &Value) -> Result { + let cmd = "inspect.fastener_checks"; + let opts = options(p, cmd)?; + let names = string_list(cmd, p, "fasteners")?; + let only = if p.get("fasteners").is_none_or(Value::is_null) { None } else { Some(occurrences_named(s, &names, cmd)?) }; + let fasteners = check(s, only.as_deref(), &opts, cmd)?; + let violations = fasteners.iter().filter(|c| c.violation == Some(true) || c.tool.as_ref().is_some_and(|t| t.clear == Some(false))).count(); + let reply = FastenerChecks { fasteners, violations, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// `parts.fastener`'s opt-in checks (#24216): with `min_edge_distance_mm` or `check_tool_clearance` +/// in `p`, the checks of the parts just placed go into the reply as `checks`, with a `warnings` +/// line for each violation. With neither, the reply is left as it is. A check that fails is a +/// warning, never a refused placement; only a parameter that is not a length or a flag is refused. +pub(crate) fn add_checks(s: &Session, opts: &Options, cmd: &str, out: &mut InsertedPart) { + if opts.min_edge.is_none() && !opts.tool { + return; + } + let placed = out.occurrences.clone().unwrap_or_else(|| vec![out.occurrence]); + match check(s, Some(&placed), opts, cmd) { + Ok(checks) => { + out.warnings.extend(warnings(&checks, opts)); + out.checks = Some(checks); + } + Err(e) => out.warnings.push(format!("fastener checks not made: {e}")), + } +} + +/// A line for each violation in `checks`, and for each check asked for that could not be made. +fn warnings(checks: &[FastenerCheck], opts: &Options) -> Vec { + let mut lines = Vec::new(); + for c in checks { + if opts.min_edge.is_some() && c.edge_distance_mm.is_none() { + lines.push(format!("{}: edge distance not checked: {}", c.fastener, c.unchecked.as_deref().unwrap_or("no wall found"))); + } + if let Some(tool) = &c.tool + && tool.clear.is_none() + { + lines.push(format!("{}: tool clearance not checked: {}", c.fastener, tool.reason)); + } + if c.violation == Some(true) { + let (distance, host) = (c.edge_distance_mm.unwrap_or(0.0), c.host.as_deref().unwrap_or("its host")); + let min = opts.min_edge.unwrap_or(0.0); + lines.push(format!("{}: its hole is {distance:.2} mm from the outside of {host}, under the {min} mm asked", c.fastener)); + } + if let Some(tool) = &c.tool + && tool.clear == Some(false) + { + lines.push(format!("{}: {}", c.fastener, tool.reason)); + } + } + lines +} + +/// The name of component `id`. +fn component_name(s: &Session, id: u64) -> Option<&str> { + s.doc.components.iter().find(|c| c.id == id).map(|c| c.name.as_str()) +} + +/// The occurrences of standard parts that `names` name: each a component or an occurrence, by name +/// or id; a component stands for every placement of it. +fn occurrences_named(s: &Session, names: &[String], cmd: &str) -> Result> { + let mut ids = Vec::new(); + for name in names { + let found: Vec = s + .doc + .occurrences + .iter() + .filter(|o| s.doc.parts.contains_key(&o.component)) + .filter(|o| { + o.name == *name + || o.id.to_string() == *name + || o.component.to_string() == *name + || component_name(s, o.component) == Some(name.as_str()) + }) + .map(|o| o.id) + .collect(); + if found.is_empty() { + return Err(bad(cmd, format!("no placed standard part `{name}`"))); + } + ids.extend(found); + } + ids.sort_unstable(); + ids.dedup(); + Ok(ids) +} + +/// Where an occurrence's part is seated (the origin of its frame) and the unit direction of its +/// +z, in the world. +fn frame_of(placed: &solidcraft_doc::Document, occ: u64) -> (Vec3, Vec3) { + let m = solidcraft_doc::joints::occurrence_world(placed, occ); + let position = solidcraft_doc::apply_point(&m, Vec3::ZERO); + let axis = solidcraft_doc::unit_direction(solidcraft_doc::apply_vector(&m, Vec3::Z)).unwrap_or(Vec3::Z); + (position, axis) +} + +/// What a check works from. +struct Ctx<'a> { + s: &'a Session, + placed: &'a solidcraft_doc::Document, + world: &'a solidcraft_doc::ModelState, + frames: &'a [Frame], + /// Each placed standard part's occurrence, seat and axis. + parts: &'a [(u64, Vec3, Vec3)], + opts: &'a Options, + cmd: &'a str, +} + +/// The checks of the placed standard parts in `only` (occurrence ids; `None`: all of them), in the +/// order of their occurrences. +pub(crate) fn check(s: &Session, only: Option<&[u64]>, opts: &Options, cmd: &str) -> Result> { + let world = s.world_state()?; + if world.bodies.len() > MAX_BODIES { + return Err(bad(cmd, format!("at most {MAX_BODIES} bodies"))); + } + if s.doc.occurrences.len() > MAX_OCCURRENCES { + return Err(bad(cmd, format!("at most {MAX_OCCURRENCES} occurrences"))); + } + let st = s.model.state(); + let placed = s.placed_document(); + let frames = placed.body_frames_with_source(&st); + // The standard parts' frames, once. + let parts: Vec<(u64, Vec3, Vec3)> = s + .doc + .occurrences + .iter() + .filter(|o| s.doc.parts.contains_key(&o.component)) + .map(|o| { + let (position, axis) = frame_of(&placed, o.id); + (o.id, position, axis) + }) + .collect(); + let ctx = Ctx { s, placed: &placed, world: &world, frames: &frames, parts: &parts, opts, cmd }; + let mut out = Vec::new(); + for occ in &s.doc.occurrences { + if s.doc.parts.contains_key(&occ.component) && only.is_none_or(|ids| ids.contains(&occ.id)) { + out.push(ctx.one(occ)); + } + } + Ok(out) +} + +impl Ctx<'_> { + /// The checks of one placed part. + fn one(&self, occ: &solidcraft_doc::Occurrence) -> FastenerCheck { + let (position, axis) = self.frame(occ.id); + let fastener = if occ.name.is_empty() { component_name(self.s, occ.component).unwrap_or("").to_string() } else { occ.name.clone() }; + let mut check = FastenerCheck { + fastener, + component: occ.component, + occurrence: occ.id, + position: [position.x, position.y, position.z], + axis: [axis.x, axis.y, axis.z], + host: None, + hole_diameter_mm: None, + edge_distance_mm: None, + nearest_face: None, + violation: None, + unchecked: None, + tool: None, + }; + self.edge(occ.id, position, axis, &mut check); + if self.opts.tool { + check.tool = Some(self.tool(occ, position, axis)); + } + check + } + + /// Where an occurrence's part is seated (the origin of its frame) and the unit direction of its + /// +z, in the world. + fn frame(&self, occ: u64) -> (Vec3, Vec3) { + match self.parts.iter().find(|p| p.0 == occ) { + Some((_, position, axis)) => (*position, *axis), + None => frame_of(self.placed, occ), + } + } + + /// Whether the occurrence's part lies on the line through `position` along `axis`: its axis + /// agrees with it (either way) within [`AXIS_TOL`] and its seat is within [`LINE_TOL`] mm of it. + fn coaxial(&self, occ: u64, position: Vec3, axis: Vec3) -> bool { + let (there, direction) = self.frame(occ); + solidcraft_kernel::line_coaxial(position.into(), axis.into(), there.into(), direction.into(), AXIS_TOL, LINE_TOL) + } + + /// Whether a joined part is seated at or behind `position` along `axis`, on the axis or not: a + /// washer under a bolt stands aside, a part in front of the tool, such as a jam nut, does not. + fn joined_behind(&self, occ: u64, position: Vec3, axis: Vec3) -> bool { + let (there, _) = self.frame(occ); + solidcraft_kernel::line_behind(position.into(), axis.into(), there.into(), LINE_TOL) + } + + /// Whether the occurrence's part is coaxial with the one at `position` and seated at or behind + /// it along `axis`, the tool's way (a bolt through a nut), not in front of it (a jam nut on + /// top of a nut stands in the tool's way). + fn behind(&self, occ: u64, position: Vec3, axis: Vec3) -> bool { + let (there, _) = self.frame(occ); + self.coaxial(occ, position, axis) && solidcraft_kernel::line_behind(position.into(), axis.into(), there.into(), LINE_TOL) + } + + /// Whether the occurrence is a placed standard part. + fn is_part(&self, occ: u64) -> bool { + self.parts.iter().any(|p| p.0 == occ) + } + + /// The widest bore about its axis that counts as the hole an occurrence's part sits in: the + /// radius of the smallest cylinder that holds the part, and a margin. A hex head or nut sits + /// in a counterbore sized for its socket, 0.75 of its width across flats in all if that is + /// more than 1 mm beyond it. + fn envelope(&self, occ: u64) -> Option { + let o = self.s.doc.occurrences.iter().find(|o| o.id == occ)?; + let part = self.s.doc.parts.get(&o.component)?; + let radius = super::parts::envelope_radius(&part.family, &part.size, part.length)?; + let socket = super::parts::drive(&part.family, &part.size, part.length).filter(|d| !d.key).map_or(0.0, |d| 0.75 * d.across_flats); + Some((radius + HOLE_MARGIN).max(socket)) + } + + /// Where the part is seated, from its joints: the occurrence whose bodies hold the hole (the + /// one it is seated on, or, for a part seated on another standard part, a screw on a washer, + /// the one that part is seated on), the part seated directly on it, and the standard parts + /// from the one checked to that one. None when a joint does not say. + fn seat_chain(&self, occ: u64) -> Option<(u64, u64, Vec)> { + let mut at = occ; + let mut chain = vec![occ]; + for _ in 0..8 { + let joint = self.s.doc.assembly.joints.iter().find(|j| j.b.occurrence == at)?; + let host = joint.a.occurrence; + if !self.is_part(host) { + return Some((host, at, chain)); + } + chain.push(host); + at = host; + } + None + } + + /// The thinnest solid wall around the hole the part sits in. A part with no joint looks for a + /// hole about its axis in every body that is not a standard part. + fn edge(&self, occ: u64, position: Vec3, axis: Vec3, check: &mut FastenerCheck) { + let seat = self.seat_chain(occ); + let host = seat.as_ref().map(|(h, ..)| *h); + // The hole is measured from the seat of the part on the host: a washer's thickness is no gap. + let (from, chain) = match &seat { + Some((_, on, chain)) => (self.frame(*on).0, chain.clone()), + None => (position, vec![occ]), + }; + let widest = chain.iter().filter_map(|id| self.envelope(*id)).fold(0.0, f64::max); + let bodies = self.frames.iter().filter(|f| match host { + Some(h) => f.3.last().copied().unwrap_or(0) == h, + None => !self.s.doc.parts.contains_key(&f.2), + }); + let mut best: Option<(&str, solidcraft_kernel::HoleLigament)> = None; + let mut failure = None; + for f in bodies { + let Some(model_body) = self.world.body(&f.0) else { continue }; + match solidcraft_kernel::hole_ligament(&model_body.body, from, axis, SEAT_REACH, widest) { + Ok(Some(hole)) => { + if best.as_ref().is_none_or(|(_, b)| hole.gap < b.gap) { + best = Some((f.0.as_str(), hole)); + } + } + Ok(None) => {} + Err(e) => failure = Some(e.to_string()), + } + } + let Some((body, hole)) = best else { + check.unchecked = Some(match failure { + Some(e) => format!("the edge distance could not be worked out: {e}"), + None if host.is_some() => "no round hole the check can read about its axis in the body it is seated on".to_string(), + None => "no round hole the check can read about its axis".to_string(), + }); + return; + }; + check.host = Some(body.to_string()); + if hole.radius > 0.0 { + check.hole_diameter_mm = Some(2.0 * hole.radius); + } + let Some(near) = hole.nearest else { + check.unchecked = Some(if hole.dropped > 0 { + format!("no wall with material behind it was found (faces set aside, open air behind them: {})", hole.dropped) + } else { + "the host has no other face to measure to".to_string() + }); + return; + }; + check.edge_distance_mm = Some(near.distance); + check.nearest_face = Some(NearestFace { + body: body.to_string(), + face: near.face, + point: [near.to.x, near.to.y, near.to.z], + hole_point: [near.from.x, near.from.y, near.from.z], + }); + check.violation = self.opts.min_edge.map(|min| near.distance + 1e-9 < min); + } + + /// Whether a tool reaches the part's head or drive along its axis. + fn tool(&self, occ: &solidcraft_doc::Occurrence, position: Vec3, axis: Vec3) -> ToolClearance { + let answer = |tool: &str, diameter: f64, length: f64, origin: Vec3, clear: Option, reason: String| ToolClearance { + tool: tool.to_string(), + diameter_mm: diameter, + length_mm: length, + origin: [origin.x, origin.y, origin.z], + direction: [axis.x, axis.y, axis.z], + clear, + reason, + blocked: Vec::new(), + unchecked: Vec::new(), + }; + let Some(part) = self.s.doc.parts.get(&occ.component) else { + return answer("none", 0.0, 0.0, position, None, "not a standard part".to_string()); + }; + let Some(drive) = super::parts::drive(&part.family, &part.size, part.length) else { + return answer("none", 0.0, 0.0, position, None, "no drive: a tool does not turn this part".to_string()); + }; + // A socket goes down over the head to the seating plane; a key only into the socket in its top. + let (tool, factor, start) = if drive.key { ("hex key", KEY_FACTOR, drive.top) } else { ("socket", SOCKET_FACTOR, 0.0) }; + let start = start + TOOL_LIFT; + let diameter = factor * drive.across_flats; + let length = drive.top - start + TOOL_LENGTH; + let origin = position + axis * start; + let body = match solidcraft_kernel::cylinder(origin, axis, diameter / 2.0, length) { + Ok(body) => body, + Err(e) => return answer(tool, diameter, length, origin, None, format!("the tool's space could not be built: {e}")), + }; + let space = Space { origin, direction: axis, body }; + // The part itself, the standard parts it is joined to and every standard part on its axis + // (the bolt through a nut, whose tip is in the socket) are not in the way. + let mut mine = vec![occ.id]; + for j in &self.s.doc.assembly.joints { + let other = if j.b.occurrence == occ.id { + j.a.occurrence + } else if j.a.occurrence == occ.id { + j.b.occurrence + } else { + continue; + }; + // A part joined in front of the tool (a jam nut placed on this nut) is in its way. + if self.is_part(other) && self.joined_behind(other, position, axis) { + mine.push(other); + } + } + for o in &self.s.doc.occurrences { + if o.id != occ.id && self.is_part(o.id) && self.behind(o.id, position, axis) { + mine.push(o.id); + } + } + let ignore: Vec = self.frames.iter().filter(|f| mine.contains(&f.3.last().copied().unwrap_or(0))).map(|f| f.0.clone()).collect(); + match blockers(self.world, &space, length, &ignore, self.cmd) { + Ok((blocked, unchecked)) => { + let reason = if blocked.is_empty() { + format!("nothing is in the {diameter:.1} mm {tool}'s way along the axis, over {length:.1} mm") + } else { + let names: Vec = + blocked.iter().map(|b| format!("{} ({:.2} mm³, from {:.2} mm along the axis)", b.body, b.volume_mm3, b.from_mm)).collect(); + format!("the {diameter:.1} mm {tool} is blocked by {}", names.join(", ")) + }; + let mut out = answer(tool, diameter, length, origin, Some(blocked.is_empty()), reason); + out.blocked = blocked; + out.unchecked = unchecked; + out + } + Err(e) => answer(tool, diameter, length, origin, None, format!("the tool's space could not be checked: {e}")), + } + } +} + +#[cfg(test)] +#[path = "fastener_checks_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/fastener_checks_tests.rs b/crates/engine/src/cmd/fastener_checks_tests.rs new file mode 100644 index 00000000000..ae1931e6162 --- /dev/null +++ b/crates/engine/src/cmd/fastener_checks_tests.rs @@ -0,0 +1,281 @@ +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn f(v: &Value) -> f64 { + v.as_f64().unwrap_or(f64::NAN) +} + +/// A 60 x 30 x 10 plate (x 0 to 60, y 0 to 30, z 0 to 10) with two 6.4 mm holes through its top +/// face, one 8 mm in from the end x = 0 and one 40 mm: a point on each hole's rim. +fn plate(s: &mut Session) -> [[f64; 3]; 2] { + run(s, "solid.box", json!({"length": 60, "width": 30, "height": 10, "body_name": "Plate"})); + run(s, "solid.hole", json!({"position": [8, 15, 10], "diameter": 6.4})); + run(s, "solid.hole", json!({"position": [40, 15, 10], "diameter": 6.4})); + [[11.2, 15.0, 10.0], [43.2, 15.0, 10.0]] +} + +fn bolts(s: &mut Session, rims: [[f64; 3]; 2], extra: Value) -> Value { + let mut p = json!({"family": "hex_bolt", "size": "M6", "length": 16, "at": rims}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + run(s, "parts.fastener", p) +} + +fn rows(r: &Value, key: &str) -> Vec { + r[key].as_array().cloned().unwrap_or_default() +} + +/// The wall around a hole is measured to the faces it does not open onto. The hole 8 mm from the +/// end of the plate has 8 - 3.2 = 4.8 mm to that end; the one 40 mm along has 15 - 3.2 = 11.8 mm +/// to the sides (the end is 16.8 away, the other hole 25.6). Nothing is added to the design. +#[test] +fn the_edge_distance_is_the_wall_between_the_hole_and_the_nearest_outside_face() { + let mut s = Session::default(); + let rims = plate(&mut s); + let placed = bolts(&mut s, rims, json!({})); + assert!(placed.get("checks").is_none() && placed.get("warnings").is_none(), "no flag, no checks: {placed}"); + let bodies = s.model.state().bodies.len(); + let r = run(&mut s, "inspect.fastener_checks", json!({})); + let found = rows(&r, "fasteners"); + assert_eq!(found.len(), 2, "{r}"); + assert!((f(&found[0]["edge_distance_mm"]) - 4.8).abs() < 1e-6, "{r}"); + assert!((f(&found[1]["edge_distance_mm"]) - 11.8).abs() < 1e-6, "{r}"); + for row in &found { + assert_eq!(row["host"], json!("Plate"), "{r}"); + assert!((f(&row["hole_diameter_mm"]) - 6.4).abs() < 1e-6, "{r}"); + assert!((f(&row["axis"][2]) - 1.0).abs() < 1e-9, "the head points up: {r}"); + assert!(row.get("violation").is_none() && row.get("tool").is_none() && row.get("unchecked").is_none(), "{r}"); + } + // The near hole's wall ends on the end face x = 0, from the hole's nearest point x = 4.8. + let face = &found[0]["nearest_face"]; + assert!(f(&face["point"][0]).abs() < 1e-6 && (f(&face["hole_point"][0]) - 4.8).abs() < 1e-6, "{r}"); + assert!(face["face"].is_number() && face["body"] == json!("Plate"), "{r}"); + assert_eq!(r["violations"], json!(0), "{r}"); + assert_eq!(s.model.state().bodies.len(), bodies, "nothing is added to the design"); + // A component names all its placements; a name that is none is refused. + let name = placed["name"].clone(); + assert_eq!(rows(&run(&mut s, "inspect.fastener_checks", json!({"fasteners": [name]})), "fasteners").len(), 2); + assert!(s.execute("inspect.fastener_checks", &json!({"fasteners": ["Nope"]})).is_err()); +} + +/// `min_edge_distance_mm` flags the hole that is nearer the outside than that; `parts.fastener` +/// asked for it adds the same checks and a warning to its reply, and places the parts anyway. +#[test] +fn a_hole_nearer_the_outside_than_asked_is_a_violation_and_a_warning() { + let mut s = Session::default(); + let rims = plate(&mut s); + let placed = bolts(&mut s, rims, json!({"min_edge_distance_mm": 5})); + let checks = rows(&placed, "checks"); + assert_eq!(checks.len(), 2, "{placed}"); + assert_eq!((&checks[0]["violation"], &checks[1]["violation"]), (&json!(true), &json!(false)), "{placed}"); + let warnings = rows(&placed, "warnings"); + assert_eq!(warnings.len(), 1, "{placed}"); + assert!(warnings[0].as_str().is_some_and(|w| w.contains("4.80") && w.contains("Plate")), "{placed}"); + assert_eq!(placed["joints"].as_array().map(Vec::len), Some(2), "placed anyway: {placed}"); + // The inspect command says the same of the parts as placed. + let again = run(&mut s, "inspect.fastener_checks", json!({"min_edge_distance_mm": 5})); + assert_eq!(again["fasteners"], placed["checks"], "{again}"); + assert_eq!(again["violations"], json!(1), "{again}"); + // A limit under the wall (4.8 mm) is kept; one over it is not. + let mut at = |min: f64| rows(&run(&mut s, "inspect.fastener_checks", json!({"min_edge_distance_mm": min})), "fasteners")[0]["violation"].clone(); + assert_eq!((at(4.79), at(4.81)), (json!(false), json!(true))); +} + +/// With neither flag, or with the tool check off, `parts.fastener` replies as it did. +#[test] +fn parts_fastener_without_the_flags_replies_as_before() { + let reply = |extra: Value| { + let mut s = Session::default(); + let rims = plate(&mut s); + bolts(&mut s, rims, extra) + }; + let plain = reply(json!({})); + assert_eq!(reply(json!({"check_tool_clearance": false})), plain); + assert_eq!(reply(json!({"check_tool_clearance": null, "min_edge_distance_mm": null})), plain); + assert!(plain.get("checks").is_none() && plain.get("warnings").is_none(), "{plain}"); +} + +/// A socket over a hex head has 1.5 times its width across flats (15 mm for an M6 bolt, 10 mm +/// across flats) from the seating plane up. Open, nothing is in its way; with a wall 6.5 mm from +/// one bolt's axis, which is clear of the head but not of the socket, that bolt's socket is +/// blocked, and the other's is not. +#[test] +fn a_socket_reaches_a_bolt_in_the_open_and_not_past_a_wall_beside_its_head() { + let mut s = Session::default(); + let rims = plate(&mut s); + bolts(&mut s, rims, json!({})); + let open = run(&mut s, "inspect.fastener_checks", json!({"check_tool_clearance": true})); + let found = rows(&open, "fasteners"); + assert_eq!(found.len(), 2, "{open}"); + for row in &found { + assert_eq!((row["tool"]["tool"].clone(), row["tool"]["clear"].clone()), (json!("socket"), json!(true)), "{open}"); + assert!((f(&row["tool"]["diameter_mm"]) - 15.0).abs() < 1e-9, "{open}"); + assert!(row["tool"]["reason"].as_str().is_some_and(|w| w.contains("nothing")), "{open}"); + } + assert_eq!(open["violations"], json!(0), "{open}"); + run(&mut s, "solid.box", json!({"corner": [46.5, 0, 10], "length": 3.5, "width": 30, "height": 30, "operation": "new", "body_name": "Wall"})); + let walled = run(&mut s, "inspect.fastener_checks", json!({"check_tool_clearance": true})); + let found = rows(&walled, "fasteners"); + assert_eq!(found[0]["tool"]["clear"], json!(true), "{walled}"); + assert_eq!(found[1]["tool"]["clear"], json!(false), "{walled}"); + let blocked = rows(&found[1]["tool"], "blocked"); + assert_eq!(blocked.iter().map(|b| b["body"].as_str().unwrap_or("")).collect::>(), ["Wall"], "{walled}"); + assert!(found[1]["tool"]["reason"].as_str().is_some_and(|w| w.contains("Wall")), "{walled}"); + assert_eq!(walled["violations"], json!(1), "{walled}"); + // Fasteners placed beside the wall say so in their own reply, as a warning, and are placed. + let mut t = Session::default(); + let rims = plate(&mut t); + run(&mut t, "solid.box", json!({"corner": [46.5, 0, 10], "length": 3.5, "width": 30, "height": 30, "operation": "new", "body_name": "Wall"})); + let placed = bolts(&mut t, rims, json!({"check_tool_clearance": true})); + assert_eq!(rows(&placed, "checks").len(), 2, "{placed}"); + assert_eq!(rows(&placed, "warnings").len(), 1, "{placed}"); + assert!(placed["warnings"][0].as_str().is_some_and(|w| w.contains("Wall")), "{placed}"); + assert_eq!(placed["joints"].as_array().map(Vec::len), Some(2), "placed anyway: {placed}"); +} + +/// A hex key goes into the socket of a socket head cap screw: 1.2 times its 5 mm across flats. +/// A part a tool does not turn, or one seated in no hole, says why it has nothing to report. +#[test] +fn a_hex_key_reaches_a_socket_head_and_a_part_without_a_hole_says_why_it_has_no_wall() { + let mut s = Session::default(); + let rims = plate(&mut s); + let screw = run( + &mut s, + "parts.fastener", + json!({"family": "socket_head_cap_screw", "size": "M6", "length": 16, "at": rims[1], "check_tool_clearance": true}), + ); + let tool = &screw["checks"][0]["tool"]; + assert_eq!((tool["tool"].clone(), tool["clear"].clone()), (json!("hex key"), json!(true)), "{screw}"); + assert!((f(&tool["diameter_mm"]) - 6.0).abs() < 1e-9, "{screw}"); + assert!((f(&screw["checks"][0]["edge_distance_mm"]) - 11.8).abs() < 1e-6, "{screw}"); + run(&mut s, "parts.insert", json!({"family": "washer", "size": "M6", "point": [100, 100, 0], "name": "Loose"})); + let all = run(&mut s, "inspect.fastener_checks", json!({"check_tool_clearance": true})); + let found = rows(&all, "fasteners"); + assert_eq!(found.len(), 2, "{all}"); + let loose = &found[1]; + assert!(loose.get("host").is_none() && loose.get("edge_distance_mm").is_none(), "{all}"); + assert!(loose["unchecked"].as_str().is_some_and(|w| w.contains("no round hole")), "{all}"); + assert!(loose["tool"].get("clear").is_none() && loose["tool"]["reason"].as_str().is_some_and(|w| w.contains("no drive")), "{all}"); + // A check asked for in an insert and not made is a warning, and the part is placed. + let asked = run( + &mut s, + "parts.fastener", + json!({"family": "washer", "size": "M6", "point": [100, 50, 0], "min_edge_distance_mm": 3, "check_tool_clearance": true}), + ); + let lines: Vec<&str> = asked["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(lines.iter().any(|w| w.contains("edge distance not checked: ")), "{asked}"); + assert!(lines.iter().any(|w| w.contains("tool clearance not checked: ")), "{asked}"); + assert!(asked["occurrence"].is_number(), "{asked}"); +} + +/// A jam nut stacked on the tool's side of a nut blocks its socket; the nut behind it, on the +/// bolt, does not block the jam nut's. +#[test] +fn a_jam_nut_on_a_nut_blocks_the_lower_nuts_socket() { + let mut s = Session::default(); + let rims = plate(&mut s); + run(&mut s, "parts.fastener", json!({"family": "hex_bolt", "size": "M6", "length": 16, "at": rims[1]})); + run(&mut s, "parts.fastener", json!({"family": "hex_nut", "size": "M6", "point": [40, 15, 0], "direction": [0, 0, -1]})); + run(&mut s, "parts.fastener", json!({"family": "hex_nut", "size": "M6", "point": [40, 15, -5.2], "direction": [0, 0, -1]})); + let r = run(&mut s, "inspect.fastener_checks", json!({"check_tool_clearance": true})); + let found = rows(&r, "fasteners"); + assert_eq!(found.len(), 3, "{r}"); + assert_eq!(found[1]["tool"]["clear"], json!(false), "{r}"); + assert_eq!(found[2]["tool"]["clear"], json!(true), "{r}"); +} + +/// A nut's socket is not blocked by its own bolt, whose tip stands in it. +#[test] +fn a_nut_on_its_bolt_has_a_clear_socket() { + let mut s = Session::default(); + let rims = plate(&mut s); + run(&mut s, "parts.fastener", json!({"family": "hex_bolt", "size": "M6", "length": 16, "at": rims[1]})); + run(&mut s, "parts.fastener", json!({"family": "hex_nut", "size": "M6", "point": [40, 15, 0], "direction": [0, 0, -1]})); + let r = run(&mut s, "inspect.fastener_checks", json!({"check_tool_clearance": true})); + let found = rows(&r, "fasteners"); + assert_eq!(found.len(), 2, "{r}"); + assert_eq!(found[1]["tool"]["clear"], json!(true), "{r}"); + assert_eq!(found[1]["tool"]["tool"], json!("socket"), "{r}"); +} + +/// A washer 2.5 mm thick (M12) under a bolt does not put the hole out of reach, and the bolt is +/// measured against the plate's hole: 20 - 6.5 = 13.5 mm to the sides. +#[test] +fn a_thick_washer_under_a_bolt_does_not_hide_the_hole() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10, "body_name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [30, 20, 10], "diameter": 13})); + run(&mut s, "parts.fastener", json!({"family": "washer", "size": "M12", "at": [36.5, 20, 10]})); + run(&mut s, "parts.fastener", json!({"family": "hex_bolt", "size": "M12", "length": 25, "at": [36.5, 20, 12.5]})); + let r = run(&mut s, "inspect.fastener_checks", json!({})); + let found = rows(&r, "fasteners"); + assert_eq!(found.len(), 2, "{r}"); + for row in &found { + assert_eq!(row["host"], json!("Plate"), "{r}"); + assert!((f(&row["edge_distance_mm"]) - 13.5).abs() < 1e-6, "{r}"); + } +} + +/// A bolt through the floor of a round cup is measured to its own hole's wall, not to the cup's +/// wall on the same axis. +#[test] +fn a_wider_bore_on_the_axis_is_not_the_bolts_hole() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 0], "radius": 30, "height": 20, "body_name": "Cup"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 2], "radius": 25, "height": 20, "operation": "cut", "targets": ["Cup"]})); + run(&mut s, "solid.hole", json!({"position": [0, 0, 2], "diameter": 6.4})); + run(&mut s, "parts.fastener", json!({"family": "hex_bolt", "size": "M6", "length": 16, "at": [3.2, 0, 2]})); + let r = run(&mut s, "inspect.fastener_checks", json!({})); + let row = &rows(&r, "fasteners")[0]; + // To the cup's outside, 30 - 3.2: the floor's material runs from the bore to the outside, and + // the cup's inside wall rises beside the hole across open air. + assert!((f(&row["edge_distance_mm"]) - 26.8).abs() < 1e-6, "{r}"); + assert!((f(&row["hole_diameter_mm"]) - 6.4).abs() < 1e-6, "{r}"); +} + +/// A cross hole that breaks into the bolt's hole leaves no wall; the floor under a blind hole is +/// not its wall. +#[test] +fn a_breached_hole_reads_zero_and_a_blind_floor_is_not_a_wall() { + let mut s = Session::default(); + let rims = plate(&mut s); + run(&mut s, "solid.cylinder", json!({"radius": 2, "height": 32, "base": [40, -1, 5], "axis": "Y", "operation": "cut", "targets": ["Plate"]})); + bolts(&mut s, rims, json!({})); + let r = run(&mut s, "inspect.fastener_checks", json!({"min_edge_distance_mm": 1})); + let found = rows(&r, "fasteners"); + assert!(f(&found[1]["edge_distance_mm"]) < 1e-6 && found[1]["violation"] == json!(true), "{r}"); + assert!((f(&found[0]["edge_distance_mm"]) - 4.8).abs() < 1e-6, "{r}"); + + let mut t = Session::default(); + run(&mut t, "solid.box", json!({"length": 60, "width": 30, "height": 10, "body_name": "Plate"})); + run(&mut t, "solid.hole", json!({"position": [40, 15, 10], "direction": [0, 0, -1], "diameter": 6.4, "depth": 8})); + run(&mut t, "parts.fastener", json!({"family": "hex_bolt", "size": "M6", "length": 6, "at": [43.2, 15, 10]})); + let r = run(&mut t, "inspect.fastener_checks", json!({"min_edge_distance_mm": 5})); + let row = &rows(&r, "fasteners")[0]; + assert!((f(&row["edge_distance_mm"]) - 11.8).abs() < 1e-6 && row["violation"] == json!(false), "{r}"); +} + +/// The widest part of a counterbore or a countersink is the wall of the hole: a hole 8 mm in from +/// the end of the plate has 8 - 5.5 = 2.5 mm left at an 11 mm counterbore and 8 - 6 = 2 mm at a +/// 12 mm countersink. +#[test] +fn counterbores_and_countersinks_are_measured_at_their_widest() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 60, "width": 30, "height": 10, "body_name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [8, 15, 10], "type": "counterbore", "diameter": 6.6, "cb_diameter": 11, "cb_depth": 6.4})); + run(&mut s, "parts.fastener", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 16, "at": [13.5, 15, 10]})); + let r = run(&mut s, "inspect.fastener_checks", json!({})); + assert!((f(&rows(&r, "fasteners")[0]["edge_distance_mm"]) - 2.5).abs() < 1e-6, "{r}"); + let mut t = Session::default(); + run(&mut t, "solid.box", json!({"length": 60, "width": 30, "height": 10, "body_name": "Plate"})); + run(&mut t, "solid.hole", json!({"position": [8, 15, 10], "diameter": 6, "type": "countersink", "cs_diameter": 12, "cs_angle": 90})); + run(&mut t, "parts.fastener", json!({"family": "countersunk_socket_screw", "size": "M6", "length": 16, "at": [11, 15, 7]})); + let r = run(&mut t, "inspect.fastener_checks", json!({})); + assert!((f(&rows(&r, "fasteners")[0]["edge_distance_mm"]) - 2.0).abs() < 1e-6, "{r}"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index bcc1e4e9cec..5a88038697d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -68,6 +68,7 @@ mod drawing_view; mod edit; mod envelopes; mod face; +mod fastener_checks; mod fastener_rationalize; mod features; mod features_more; @@ -754,6 +755,7 @@ fn gather_command_specs() -> Vec<&'static CommandSpec> { v.extend(machinability::COMMANDS.iter()); v.extend(fastener_rationalize::COMMANDS.iter()); v.extend(socket_reach::COMMANDS.iter()); + v.extend(fastener_checks::COMMANDS.iter()); v.extend(sweep_clearance::COMMANDS.iter()); v.extend(tolerance_stack::COMMANDS.iter()); v.extend(motion::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index be52477c172..f4c501a9ea9 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -20,7 +20,8 @@ use crate::schema::motion::{ ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, ExplodeCreateParams, ExplodeCreated, ExplodeDeleteParams, ExplodeDeleted, ExplodeListParams, ExplodeMoveInfo, ExplodeShowParams, ExplodeShown, ExplodeViews, ExplodedViewInfo, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, - MotionStudyParams, MotionStudySaved, StudyConfigKeyInfo, StudyParamKeyInfo, parse_study_configs, parse_study_params, parse_study_segments, + MotionStudyParams, MotionStudySaved, PointAt, StudyConfigKeyInfo, StudyParamKeyInfo, parse_study_configs, parse_study_params, + parse_study_segments, study_point, }; use crate::schema::motion_animation::{AnimationExported, ExportAnimationParams}; use crate::schema::motion_play::{ @@ -46,6 +47,8 @@ pub(crate) mod associative; pub(crate) mod contact_sweep; #[path = "motion_sweep.rs"] mod sweep; +#[path = "motion_import.rs"] +mod trajectory; macro_rules! trace_doc { () => { @@ -124,7 +127,14 @@ pub static COMMANDS: &[CommandSpec] = &[ .params( "name?; study? (edit an existing one); steps? (timeline length, default 100); keys?: [{joint, index?, points: [[step, value], …], easings?, curves?, expressions?}] \ (values: degrees for angles, mm for distances, or expressions; optional `expressions` matches `points` in length with `null` for plain numbers so `motion.list` keys round-trip unchanged; expressions naming parameters are kept and re-evaluated when parameters or configurations change); \ - configs?: [{step, config}] (step-keyed configuration switches); params?: [{step, name, value}] (step-keyed parameter overrides) \ + configs?: [{step, config}] (step-keyed configuration switches); params?: [{step, name, value}] (step-keyed parameter overrides); \ + in time instead of steps: sample_rate_hz? (steps per second) with duration_s? (steps = round(duration_s × sample_rate_hz); step k is at k / sample_rate_hz seconds; not with steps) \ + and points as {time_s, value} (all of a study's points by time_s, or all by step; time_s ≥ 0 needs sample_rate_hz); \ + from a recorded trajectory instead of keys: file (a .csv with a header row, or .json: {\"\": [values…]} or a list of row objects; \ + at most 8 MiB and 10000 rows, time strictly increasing), columns: {\"\": \"\"} (the joint's first value), \ + format? (csv|json, default from the extension), time_column? (seconds, default \"time\"), units?: {\"\": \"deg\"|\"rad\"|\"mm\"|\"m\"} (default deg and mm), \ + zero_offset?: bool (subtract each column's first value), sample_rate_hz? (resample to this rate; default the file's average rate) \ + — the file replaces the keys, steps and duration_s; a study timed in seconds reports duration_s and sample_rate_hz \ → study, name, steps, keys, warnings?: [string] (one for each key that asks a joint value for more than its limits allow: motion.play holds the value at the limit)", ), CommandSpec::new("motion.play", "Play Motion Study", crate::checked!("motion.play", play)) @@ -978,7 +988,11 @@ fn study(s: &mut Session, p: &Value) -> Result { } None => None, }; - let mut keys = Vec::new(); + let Timing { rate_hz, duration_s, steps: timed_steps, keys: imported } = study_timing(s, p, cmd, existing, steps)?; + let steps = steps.or(timed_steps); + let replaces_keys = p.get("keys").is_some() || imported.is_some(); + let mut keys = imported.unwrap_or_default(); + let (mut any_step, mut any_time) = (false, false); if let Some(list) = p.get("keys") { let list = list.as_array().ok_or_else(|| bad(cmd, "`keys` must be a list"))?; if list.len() > 1000 { @@ -1010,9 +1024,24 @@ fn study(s: &mut Session, p: &Value) -> Result { }; let mut raw_points = Vec::new(); for (i, pt) in pts.iter().enumerate() { - let (Some(st), Some(v)) = (pt.get(0).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() < 1e9), pt.get(1)) else { - return Err(bad(cmd, "points are [step, value]")); + let (at, v) = study_point(pt).map_err(|e| bad(cmd, e))?; + let st = match at { + PointAt::Step(step) => { + any_step = true; + step + } + PointAt::Time(time_s) => { + any_time = true; + let rate = rate_hz.ok_or_else(|| bad(cmd, "points in time (`time_s`) need `sample_rate_hz`, the steps per second"))?; + trajectory::time_to_step(time_s, rate) + } }; + if any_step && any_time { + return Err(bad(cmd, "a study's points are all by `step` or all by `time_s`, not some of each")); + } + if !st.is_finite() || st.abs() >= 1e9 { + return Err(bad(cmd, "a point's step must be within ±1e9 (a time times `sample_rate_hz`)")); + } let expr_v = exprs_arr.and_then(|arr| arr.get(i)).filter(|e| !e.is_null()); let src = if v.is_string() { v } else { expr_v.unwrap_or(v) }; raw_points.push((st, value(s, src, kind.is_angle(index), cmd)?, super::joints::typed(Some(src)))); @@ -1030,6 +1059,27 @@ fn study(s: &mut Session, p: &Value) -> Result { keys.push(key); } } + // A new rate for a study that has one, with its keys kept: they stay at the same seconds, so + // their steps scale with it, and so does a timeline set by hand (rounded up, so the keys stay + // inside it; with a duration, the steps come from that). Refused before anything is changed. + let rescale = existing.and_then(|i| s.doc.assembly.studies.get(i)).and_then(|m| { + let (before, now) = (m.sample_rate_hz?, rate_hz?); + (!replaces_keys && (before - now).abs() > before * 1e-12).then_some((now / before, m)) + }); + let mut rescaled_steps = None; + if let Some((ratio, m)) = rescale { + if m.keys.iter().flat_map(|key| key.points.iter()).any(|point| !(point.0 * ratio).is_finite() || (point.0 * ratio).abs() >= 1e9) { + return Err(bad(cmd, "the new `sample_rate_hz` puts a key past ±1e9 steps")); + } + if steps.is_none() { + let n = trajectory::time_to_step(f64::from(m.steps), ratio).ceil(); + if !(1.0..=100_000.0).contains(&n) { + return Err(bad(cmd, "the new `sample_rate_hz` puts the timeline outside 1…100000 steps")); + } + rescaled_steps = Some(n as u32); + } + } + let steps = steps.or(rescaled_steps); // Keys that ask for a value beyond its joint's limits: motion.play holds the value at the limit (#24243). let warnings = study_limit_warnings(s, &keys); let configs = match p.get("configs") { @@ -1069,12 +1119,14 @@ fn study(s: &mut Session, p: &Value) -> Result { let cur_study = existing.and_then(|i| s.doc.assembly.studies.get(i)); let eff_configs = configs.as_deref().unwrap_or_else(|| cur_study.map_or(&[], |m| m.configs.as_slice())).to_vec(); let eff_params = param_keys.as_deref().unwrap_or_else(|| cur_study.map_or(&[], |m| m.params.as_slice())).to_vec(); - let eff_keys = if p.get("keys").is_some() { keys.clone() } else { cur_study.map_or_else(Vec::new, |m| m.keys.clone()) }; + let eff_keys = if replaces_keys { keys.clone() } else { cur_study.map_or_else(Vec::new, |m| m.keys.clone()) }; let preview_study = MotionStudy { id: 0, name: str_(p, "name").map(str::to_string).or_else(|| cur_study.map(|m| m.name.clone())).unwrap_or_else(|| "study".into()), steps: total_steps, keys: eff_keys, + duration_s, + sample_rate_hz: rate_hz, configs: eff_configs, params: eff_params, }; @@ -1106,9 +1158,19 @@ fn study(s: &mut Session, p: &Value) -> Result { if let Some(n) = steps { m.steps = n; } - if p.get("keys").is_some() { + if replaces_keys { m.keys = keys; + } else if let (Some(before), Some(now)) = (m.sample_rate_hz, rate_hz) + && (before - now).abs() > before * 1e-12 + { + // A new rate keeps the keys at the same seconds, so their steps scale with it. (A new + // `steps` alone keeps them at the same steps: the timeline is cut or extended.) + for point in m.keys.iter_mut().flat_map(|key| key.points.iter_mut()) { + point.0 = trajectory::time_to_step(point.0, now / before); + } } + m.duration_s = duration_s; + m.sample_rate_hz = rate_hz; if let Some(cs) = configs { m.configs = cs; } @@ -1129,6 +1191,8 @@ fn study(s: &mut Session, p: &Value) -> Result { name: str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Motion Study", a.studies.iter().map(|m| m.name.as_str()))), steps: steps.unwrap_or(100), keys, + duration_s, + sample_rate_hz: rate_hz, configs: configs.unwrap_or_default(), params: param_keys.unwrap_or_default(), }; @@ -1136,7 +1200,93 @@ fn study(s: &mut Session, p: &Value) -> Result { m } }; - typed_reply(cmd, MotionStudySaved { study: out.id, name: out.name, steps: out.steps, keys: out.keys.len(), warnings, param_warnings: Vec::new() }) + typed_reply( + cmd, + MotionStudySaved { + study: out.id, + name: out.name, + steps: out.steps, + keys: out.keys.len(), + duration_s: out.duration_s, + sample_rate_hz: out.sample_rate_hz, + warnings, + param_warnings: Vec::new(), + }, + ) +} + +/// What `motion.study`'s time parameters and `file` make of the study: its time base, the steps +/// that time base gives, and the keys of a trajectory file. +struct Timing { + rate_hz: Option, + duration_s: Option, + steps: Option, + keys: Option>, +} + +/// A number above 0 (and below 1e9) that `key` holds, when it is given. +fn positive(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None => Ok(None), + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && *x > 0.0 && *x < 1e9) + .map(Some) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a number above 0"))), + } +} + +/// The study's time base after this call: `sample_rate_hz` and `duration_s` given or kept from the +/// study being changed (`existing`), the steps they give (`steps` is the call's own, which clears the +/// duration), and, with `file`, the trajectory's keys, rate, steps and duration. With none of them +/// in the call and none kept, every field is `None`: a study timed in steps is left as it was. +fn study_timing(s: &Session, p: &Value, cmd: &str, existing: Option, steps: Option) -> Result { + let file = p.get("file").is_some(); + if file { + if let Some(key) = ["keys", "steps", "duration_s"].into_iter().find(|key| p.get(*key).is_some()) { + return Err(bad(cmd, format!("`file` makes the study's keys, steps and duration_s: not with `{key}`"))); + } + } else if let Some(key) = ["columns", "format", "time_column", "units", "zero_offset"].into_iter().find(|key| p.get(*key).is_some()) { + return Err(bad(cmd, format!("`{key}` goes with `file`"))); + } + let rate_in = positive(p, "sample_rate_hz", cmd)?; + let duration_in = positive(p, "duration_s", cmd)?; + if file { + let t = trajectory::read(s, p, cmd, rate_in)?; + return Ok(Timing { rate_hz: Some(t.rate_hz), duration_s: Some(t.duration_s), steps: Some(t.steps), keys: Some(t.keys) }); + } + let old = existing.and_then(|i| s.doc.assembly.studies.get(i)); + let (old_rate, old_duration) = (old.and_then(|m| m.sample_rate_hz), old.and_then(|m| m.duration_s)); + let rate_hz = rate_in.or(old_rate); + let timed = |duration: f64, rate: Option| { + let rate = rate.ok_or_else(|| bad(cmd, "`duration_s` needs `sample_rate_hz`, the steps per second"))?; + trajectory::steps_for(duration, rate).map_err(|e| bad(cmd, e)) + }; + let (duration_s, timed_steps) = match (duration_in, steps) { + (Some(d), Some(n)) => { + // `motion.list` says all three: they agree when `steps` is the rounded product. + let agreed = timed(d, rate_hz)?; + // A resampled import has the steps its duration reaches, rounded up. + let rounded_up = trajectory::time_to_step(d, rate_hz.unwrap_or_default()).ceil(); + if agreed != n && f64::from(n) != rounded_up { + return Err(bad( + cmd, + format!("give `steps`, or `duration_s` with `sample_rate_hz`, not both (`duration_s` × `sample_rate_hz` is {agreed} steps)"), + )); + } + (Some(d), Some(n)) + } + (Some(d), None) => (Some(d), Some(timed(d, rate_hz)?)), + (None, Some(_)) => (None, None), + (None, None) => match (rate_in, old_duration) { + // The same rate (within the tolerance `motion.study` uses to tell a new rate) keeps the steps: + // an import rounded them up from `duration_s` × rate, and `round` would cut one off. + (Some(r), Some(d)) if old_rate.is_some_and(|before| (before - r).abs() <= before * 1e-12) => (Some(d), None), + (Some(_), Some(d)) => (Some(d), Some(timed(d, rate_hz)?)), + _ => (old_duration, None), + }, + }; + Ok(Timing { rate_hz, duration_s, steps: timed_steps, keys: None }) } /// One warning for each key of a study that asks a joint value for more than its limits allow: @@ -1821,7 +1971,17 @@ fn study_info(s: &Session, m: &MotionStudy) -> MotionStudyInfo { } let configs = m.configs.iter().map(|c| StudyConfigKeyInfo { step: c.step, config: c.config.clone() }).collect(); let params = m.params.iter().map(|p| StudyParamKeyInfo { step: p.step, name: p.name.clone(), value: p.value.clone() }).collect(); - MotionStudyInfo { id: m.id, name: m.name.clone(), steps: m.steps, keys, configs, params, errors } + MotionStudyInfo { + id: m.id, + name: m.name.clone(), + steps: m.steps, + keys, + duration_s: m.duration_s, + sample_rate_hz: m.sample_rate_hz, + configs, + params, + errors, + } } fn delete_study(s: &mut Session, p: &Value) -> Result { @@ -2059,3 +2219,6 @@ pub fn world_point(s: &Session, occurrence: u64, p: Vec3) -> Vec3 { #[cfg(test)] #[path = "motion_tests.rs"] mod tests; +#[cfg(test)] +#[path = "motion_time_tests.rs"] +mod time_tests; diff --git a/crates/engine/src/cmd/motion_analysis.rs b/crates/engine/src/cmd/motion_analysis.rs index 611991781aa..5dc9075e674 100644 --- a/crates/engine/src/cmd/motion_analysis.rs +++ b/crates/engine/src/cmd/motion_analysis.rs @@ -22,7 +22,8 @@ use crate::{EngineError, Result, Session}; pub const PLOT_DOC: &str = "study: id|name; joints?: [id|name] (default: every joint that moves); occurrence? and point? (a point \ of a part to follow, as motion.trace takes them); samples? (3…1000, default the study's steps + 1); duration?: seconds the \ - whole study takes, 0.001 or more (velocities and accelerations then per second, else per step) → step: [the study step of each sample], \ + whole study takes, 0.001 or more (velocities and accelerations then per second, else per step; a study with a \ + sample_rate_hz plots per second by that rate when no duration is given) → step: [the study step of each sample], \ time?: [s], joints: [{joint, name, index, dof, unit, value, velocity, acceleration, velocity_unit, acceleration_unit}] \ (degrees for angles, mm for distances; angles unwrapped), point?: {occurrence, position: [[x,y,z]…], velocity, \ acceleration (vectors), speed, acceleration_norm, unit, velocity_unit, acceleration_unit}, samples (taken), stopped_at, \ @@ -234,10 +235,10 @@ pub(super) fn plot(s: &mut Session, p: &Value) -> Result { } Ok(true) })?; - // Sample spacing in steps, or in seconds when the study has a duration. - let seconds_per_step = duration.map(|d| d / f64::from(m.steps)); + // Sample spacing in steps, or in seconds when the plot is given a duration, or the study a rate. + let seconds_per_step = duration.map(|d| d / f64::from(m.steps)).or(m.sample_rate_hz.map(|rate| 1.0 / rate)); let h = f64::from(m.steps) / (n - 1) as f64 * seconds_per_step.unwrap_or(1.0); - let per = if duration.is_some() { "s" } else { "step" }; + let per = if seconds_per_step.is_some() { "s" } else { "step" }; let step: Vec = (0..taken).map(|k| step_of(&m, k, n)).collect(); let time = seconds_per_step.map(|sps| step.iter().map(|st| st * sps).collect()); let joints_out: Vec = series diff --git a/crates/engine/src/cmd/motion_import.rs b/crates/engine/src/cmd/motion_import.rs new file mode 100644 index 00000000000..6c3ab05f354 --- /dev/null +++ b/crates/engine/src/cmd/motion_import.rs @@ -0,0 +1,383 @@ +//! `motion.study`'s `file`: a recorded trajectory (a CSV or JSON table of joint values over time) +//! becomes the study's keys, one per mapped column, at the time the file gives each sample. +//! +//! Why a `file` on `motion.study` and not a command of its own: the import is the study's keys +//! made from another source, so it keeps the study's naming, editing (`study`), undo step and +//! reply; and the agent chat gate already asks for a parameter named `file`, while +//! `control_pending` counts `motion.study` as a design change, not as a write of a file. + +use std::collections::{BTreeMap, HashSet}; + +use serde_json::Value; +use solidcraft_doc::joints::JointKind; +use solidcraft_doc::motion::StudyKey; + +use super::joint_id; +use crate::params::bad; +use crate::{EngineError, Result, Session}; + +/// The largest trajectory file read. +const MAX_BYTES: usize = 8 << 20; +/// The most samples (rows) a trajectory has: a key takes at most this many points. +const MAX_ROWS: usize = 10_000; +/// The most columns a trajectory file has. +const MAX_COLUMNS: usize = 1000; +/// The most steps a study's timeline has. +const MAX_STEPS: f64 = 100_000.0; +/// Joint values and steps are read only while smaller than this in size. +const MAX_VALUE: f64 = 1e9; + +/// What a trajectory file makes: the keys, and the time base they are in. +pub(super) struct Trajectory { + pub keys: Vec, + /// Steps per second. + pub rate_hz: f64, + pub steps: u32, + /// The time from the file's first sample to its last, in seconds: the first sample is time 0. + pub duration_s: f64, +} + +/// How many steps a trajectory of `duration_s` seconds takes at `rate_hz`, rounded up so that its +/// last sample is never past the last step: 1 to 100 000. +fn import_steps(duration_s: f64, rate_hz: f64) -> std::result::Result { + let steps = time_to_step(duration_s, rate_hz).ceil(); + if steps.is_finite() && (1.0..=MAX_STEPS).contains(&steps) { + Ok(steps as u32) + } else { + Err(format!("{duration_s} s at {rate_hz} steps per second is {steps} steps; a study has 1…100000")) + } +} + +/// The step at `time_s` seconds when a step takes `1 / rate_hz` seconds: the product, with the +/// rounding noise of the multiplication (`0.3 * 10`) taken off. +pub(super) fn time_to_step(time_s: f64, rate_hz: f64) -> f64 { + (time_s * rate_hz * 1e9).round() / 1e9 +} + +/// How many steps `duration_s` seconds take at `rate_hz`: 1 to 100 000. +pub(super) fn steps_for(duration_s: f64, rate_hz: f64) -> std::result::Result { + let steps = (duration_s * rate_hz).round(); + if steps.is_finite() && (1.0..=MAX_STEPS).contains(&steps) { + Ok(steps as u32) + } else { + Err(format!("{duration_s} s at {rate_hz} steps per second is {steps} steps; a study has 1…100000")) + } +} + +enum Cell { + Number(f64), + Text, +} + +/// A file's columns, each as long as the file has rows. +struct Table { + columns: Vec<(String, Vec)>, +} + +impl Table { + fn rows(&self) -> usize { + self.columns.first().map_or(0, |(_, cells)| cells.len()) + } + + fn names(&self) -> String { + self.columns.iter().map(|(name, _)| name.as_str()).take(20).collect::>().join(", ") + } + + /// A column's numbers; a cell that is not a finite number fails with its row. + fn numbers(&self, name: &str) -> std::result::Result, String> { + let (_, cells) = self + .columns + .iter() + .find(|(column, _)| column == name) + .ok_or_else(|| format!("no column `{name}` in the file (it has: {})", self.names()))?; + cells + .iter() + .enumerate() + .map(|(i, cell)| match cell { + Cell::Number(x) if x.is_finite() => Ok(*x), + _ => Err(format!("column `{name}`, row {}: not a finite number", i + 1)), + }) + .collect() + } +} + +/// The fields of one CSV line: comma separated, a field optionally in double quotes (`""` is a +/// quote inside one). `line` is the file's line number, for the message. +fn csv_fields(text: &str, line: usize) -> std::result::Result, String> { + let mut out = Vec::new(); + let mut chars = text.chars().peekable(); + loop { + let mut field = String::new(); + while chars.peek().is_some_and(|c| c.is_whitespace()) { + chars.next(); + } + if chars.peek() == Some(&'"') { + chars.next(); + loop { + match chars.next() { + Some('"') if chars.peek() == Some(&'"') => { + chars.next(); + field.push('"'); + } + Some('"') => break, + Some(c) => field.push(c), + None => return Err(format!("line {line}: a quoted field is not closed")), + } + } + while chars.peek().is_some_and(|c| c.is_whitespace()) { + chars.next(); + } + match chars.next() { + None => { + out.push(field); + return Ok(out); + } + Some(',') => out.push(field), + Some(_) => return Err(format!("line {line}: text after a closing quote")), + } + } else { + loop { + match chars.next() { + None => { + out.push(field.trim().to_string()); + return Ok(out); + } + Some(',') => { + out.push(field.trim().to_string()); + break; + } + Some('"') => return Err(format!("line {line}: a quote inside an unquoted field")), + Some(c) => field.push(c), + } + } + } + } +} + +/// A CSV file: a header row naming the columns, then one row per sample; blank lines are skipped. +fn csv_table(text: &str) -> std::result::Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut lines = text.lines().enumerate().filter(|(_, line)| !line.trim().is_empty()); + let (at, header) = lines.next().ok_or("the file is empty")?; + let names = csv_fields(header, at + 1)?; + if names.iter().any(String::is_empty) { + return Err(format!("line {}: a column has no name", at + 1)); + } + if names.len() > MAX_COLUMNS { + return Err(format!("more than {MAX_COLUMNS} columns")); + } + let mut seen = HashSet::new(); + if let Some(name) = names.iter().find(|name| !seen.insert(name.as_str())) { + return Err(format!("the column `{name}` is named twice")); + } + let mut columns: Vec<(String, Vec)> = names.into_iter().map(|name| (name, Vec::new())).collect(); + for (at, line) in lines { + if columns.first().is_some_and(|(_, cells)| cells.len() >= MAX_ROWS) { + return Err(format!("more than {MAX_ROWS} rows")); + } + let fields = csv_fields(line, at + 1)?; + if fields.len() != columns.len() { + return Err(format!("line {}: {} fields, the header has {}", at + 1, fields.len(), columns.len())); + } + for ((_, cells), field) in columns.iter_mut().zip(fields) { + cells.push(field.parse::().map_or(Cell::Text, Cell::Number)); + } + } + Ok(Table { columns }) +} + +fn json_cell(v: &Value) -> Cell { + v.as_f64().map_or(Cell::Text, Cell::Number) +} + +/// A JSON file: `{"": [values…], …}` (every list as long as the others), or a list of +/// rows, each an object with the same columns. +fn json_table(text: &str) -> std::result::Result { + let value: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?; + let columns: Vec<(String, Vec)> = match value { + Value::Object(fields) => { + if fields.len() > MAX_COLUMNS { + return Err(format!("more than {MAX_COLUMNS} columns")); + } + let mut columns = Vec::new(); + for (name, column) in fields { + if let Value::Array(cells) = column { + if cells.len() > MAX_ROWS { + return Err(format!("more than {MAX_ROWS} rows")); + } + columns.push((name, cells.iter().map(json_cell).collect::>())); + } + } + if let Some((name, _)) = columns.iter().find(|(_, cells)| columns.first().is_some_and(|(_, first)| first.len() != cells.len())) { + return Err(format!("the lists are not all as long: `{name}` differs from the first")); + } + columns + } + Value::Array(rows) => { + if rows.len() > MAX_ROWS { + return Err(format!("more than {MAX_ROWS} rows")); + } + let first = rows.first().and_then(Value::as_object).ok_or("a list of rows must hold objects")?; + if first.len() > MAX_COLUMNS { + return Err(format!("more than {MAX_COLUMNS} columns")); + } + let mut columns: Vec<(String, Vec)> = first.keys().map(|name| (name.clone(), Vec::new())).collect(); + for (i, row) in rows.iter().enumerate() { + let fields = row.as_object().ok_or_else(|| format!("row {}: not an object", i + 1))?; + if fields.len() != columns.len() { + return Err(format!("row {}: {} fields, the first row has {}", i + 1, fields.len(), columns.len())); + } + for (name, cells) in &mut columns { + cells.push(json_cell(fields.get(name.as_str()).ok_or_else(|| format!("row {}: no `{name}`", i + 1))?)); + } + } + columns + } + _ => return Err("JSON must be {\"\": [values…]} or a list of row objects".into()), + }; + Ok(Table { columns }) +} + +/// What one unit multiplies to in the joint's own unit (radians, mm). +fn unit_factor(unit: Option<&str>, angle: bool) -> std::result::Result { + match (angle, unit) { + (true, None | Some("deg")) => Ok(std::f64::consts::PI / 180.0), + (true, Some("rad")) => Ok(1.0), + (false, None | Some("mm")) => Ok(1.0), + (false, Some("m")) => Ok(1000.0), + (true, Some(u)) => Err(format!("`{u}` is not a unit of an angle (deg or rad)")), + (false, Some(u)) => Err(format!("`{u}` is not a unit of a distance (mm or m)")), + } +} + +/// The value at `time` of the samples `(times[i], values[i])`: linear between them, held before the +/// first and after the last. +fn sample_at(times: &[f64], values: &[f64], time: f64) -> f64 { + let after = times.partition_point(|t| *t <= time); + let before = after.checked_sub(1).and_then(|i| times.get(i).zip(values.get(i))); + match (before, times.get(after).zip(values.get(after))) { + (Some((t0, v0)), Some((t1, v1))) => v0 + (v1 - v0) * (time - t0) / (t1 - t0), + (Some((_, v)), None) | (None, Some((_, v))) => *v, + (None, None) => 0.0, + } +} + +/// The key `p`'s `file` makes for `motion.study` (see [`Params`](crate::schema::motion::MotionStudyParams)): +/// its `columns`, `time_column`, `units`, `zero_offset` and `format`, resampled to `resample_hz` +/// when that is given. The file's first sample is time 0 (a file that starts at 5 s starts the study +/// at 0 s), and the timeline has the steps that reach its last sample, rounded up. Nothing is changed. +pub(super) fn read(s: &Session, p: &Value, cmd: &str, resample_hz: Option) -> Result { + let file = + p.get("file").and_then(Value::as_str).filter(|f| !f.trim().is_empty() && f.len() < 4096).ok_or_else(|| bad(cmd, "`file` must be a path"))?; + let columns = p + .get("columns") + .and_then(Value::as_object) + .filter(|c| !c.is_empty()) + .ok_or_else(|| bad(cmd, "`columns` must say which joint each column drives: {\"\": \"\"}"))?; + let time_column = match p.get("time_column") { + None | Some(Value::Null) => "time", + Some(Value::String(t)) if !t.is_empty() => t.as_str(), + Some(_) => return Err(bad(cmd, "`time_column` must be a column name")), + }; + let units: BTreeMap<&str, &str> = match p.get("units") { + None | Some(Value::Null) => BTreeMap::new(), + Some(Value::Object(o)) => o + .iter() + .map(|(column, unit)| { + unit.as_str() + .map(|u| (column.as_str(), u)) + .ok_or_else(|| bad(cmd, format!("the unit of `{column}` must be text (deg, rad, mm or m)"))) + }) + .collect::>()?, + Some(_) => return Err(bad(cmd, "`units` must map a column to its unit: {\"\": \"deg\"}")), + }; + if let Some(column) = units.keys().find(|column| !columns.contains_key(**column)) { + return Err(bad(cmd, format!("`units` names `{column}`, which `columns` does not map to a joint"))); + } + let zero_offset = match p.get("zero_offset") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`zero_offset` must be true or false")), + }; + // (column, joint, factor to the joint's unit) + let mut driven: Vec<(&str, u64, f64)> = Vec::new(); + for (column, target) in columns { + if column == time_column { + return Err(bad(cmd, format!("the time column `{column}` cannot drive a joint"))); + } + let joint = joint_id(s, Some(target), cmd)?; + let kind = s.doc.assembly.joints.iter().find(|j| j.id == joint).map_or(JointKind::Rigid, |j| j.kind); + let name = target.as_str().map_or_else(|| target.to_string(), str::to_string); + if kind.dofs().is_empty() { + return Err(bad(cmd, format!("joint `{name}` has no moving value for column `{column}`"))); + } + if driven.iter().any(|(_, j, _)| *j == joint) { + return Err(bad(cmd, format!("joint `{name}` is driven by two columns"))); + } + let factor = unit_factor(units.get(column.as_str()).copied(), kind.is_angle(0)).map_err(|e| bad(cmd, format!("column `{column}`: {e}")))?; + driven.push((column.as_str(), joint, factor)); + } + let extension = std::path::Path::new(file).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let format = match p.get("format") { + None | Some(Value::Null) => extension.unwrap_or_default(), + Some(Value::String(f)) => f.to_ascii_lowercase(), + Some(_) => return Err(bad(cmd, "`format` must be csv or json")), + }; + if format != "csv" && format != "json" { + return Err(bad(cmd, "`format` must be csv or json (left out, the file's extension says: .csv or .json)")); + } + let bytes = solidcraft_io::vfs::read_design_path(file, s.path.as_deref(), MAX_BYTES).map_err(|e| EngineError::Other(format!("{file}: {e}")))?; + let text = String::from_utf8(bytes).map_err(|_| bad(cmd, format!("{file}: not UTF-8 text")))?; + let table = if format == "csv" { csv_table(&text) } else { json_table(&text) }.map_err(|e| bad(cmd, format!("{file}: {e}")))?; + let rows = table.rows(); + if rows < 2 { + return Err(bad(cmd, format!("{file}: a trajectory needs at least 2 rows"))); + } + let times = table.numbers(time_column).map_err(|e| bad(cmd, e))?; + if let Some(i) = times.iter().position(|t| *t < 0.0) { + return Err(bad(cmd, format!("column `{time_column}`, row {}: a time cannot be negative", i + 1))); + } + if let Some(i) = times.windows(2).position(|w| matches!(w, [a, b] if b <= a)) { + return Err(bad(cmd, format!("column `{time_column}`, row {}: time does not increase (it must grow from row to row)", i + 2))); + } + if let Some(i) = times.iter().position(|t| *t >= MAX_VALUE) { + return Err(bad(cmd, format!("column `{time_column}`, row {}: a time must be below 1e9 seconds", i + 1))); + } + let (Some(&first), Some(&last)) = (times.first(), times.last()) else { return Err(bad(cmd, "the file has no samples")) }; + // The first sample is time 0, whatever time the file starts at. + let duration = last - first; + let times: Vec = times.iter().map(|t| t - first).collect(); + let rate = match resample_hz { + Some(rate) => rate, + None => (rows - 1) as f64 / duration, + }; + if !(rate.is_finite() && rate > 0.0) { + return Err(bad(cmd, "`sample_rate_hz` must be above 0")); + } + if rate >= MAX_VALUE { + return Err(bad(cmd, format!("{file}: the file's own rate, {rate} steps per second, is too high; give `sample_rate_hz` to resample"))); + } + let steps = import_steps(duration, rate).map_err(|e| bad(cmd, format!("{file}: {e}; give `sample_rate_hz` to resample")))?; + if resample_hz.is_some() && steps as usize + 1 > MAX_ROWS { + return Err(bad( + cmd, + format!("{file}: resampling to {rate} Hz makes {} points a key; at most {MAX_ROWS} (lower `sample_rate_hz`)", steps + 1), + )); + } + let mut keys = Vec::with_capacity(driven.len()); + for (column, joint, factor) in driven { + let raw = table.numbers(column).map_err(|e| bad(cmd, e))?; + let offset = if zero_offset { raw.first().copied().unwrap_or(0.0) } else { 0.0 }; + let values: Vec = raw.iter().map(|v| (v - offset) * factor).collect(); + if values.iter().any(|v| v.abs() >= MAX_VALUE) { + return Err(bad(cmd, format!("column `{column}`: values must be within ±1e9"))); + } + let points: Vec<(f64, f64)> = if resample_hz.is_some() { + (0..=steps).map(|k| (f64::from(k), sample_at(×, &values, f64::from(k) / rate))).collect() + } else { + times.iter().zip(&values).map(|(t, v)| (time_to_step(*t, rate), *v)).collect() + }; + keys.push(StudyKey { joint, index: 0, points, exprs: Vec::new(), easings: Vec::new(), curves: Vec::new() }); + } + Ok(Trajectory { keys, rate_hz: rate, steps, duration_s: duration }) +} diff --git a/crates/engine/src/cmd/motion_time_tests.rs b/crates/engine/src/cmd/motion_time_tests.rs new file mode 100644 index 00000000000..d40b0781e11 --- /dev/null +++ b/crates/engine/src/cmd/motion_time_tests.rs @@ -0,0 +1,405 @@ +//! Motion studies in physical time (#24217): points at `time_s`, a study's `duration_s` and +//! `sample_rate_hz`, and a study made from a recorded trajectory file (`motion.study`'s `file`). + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use solidcraft_io::vfs::{self, PathScope}; + +use crate::Session; + +/// Two boxes on a hinge (`Hinge`, degrees) and a slide (`Rail`, mm). +fn door() -> Session { + let mut s = Session::default(); + for (name, corner, size) in [("Door", [0, 0, 0], [100, 4, 50]), ("Slide", [0, -40, 0], [10, 10, 10])] { + for (id, p) in [ + ("component.activate", json!({"component": "root"})), + ("component.create", json!({"name": name, "grounded": false})), + ("solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner})), + ] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + } + for p in [ + json!({"type": "revolute", "a": {"occurrence": 0, "point": [0, 0, 0]}, "b": {"occurrence": "Door", "point": [0, 0, 0]}, "flip": true, "name": "Hinge"}), + json!({"type": "slider", "a": {"occurrence": 0, "point": [0, -40, 0], "z": [1, 0, 0]}, "b": {"occurrence": "Slide", "point": [0, -40, 0], "z": [1, 0, 0]}, "flip": true, "name": "Rail"}), + ] { + s.execute("joint.create", &p).unwrap_or_else(|e| panic!("{e}")); + } + s +} + +fn run(s: &mut Session, p: Value) -> Value { + s.execute("motion.study", &p).unwrap_or_else(|e| panic!("{p}: {e}")) +} + +fn refused(s: &mut Session, p: Value) -> String { + match s.execute("motion.study", &p) { + Ok(r) => panic!("{p} should be refused, got {r}"), + Err(e) => e.to_string(), + } +} + +/// A study's key `key`, as `motion.list` shows it: [step, value] pairs, degrees and mm. +fn points(s: &mut Session, study: &str, key: usize) -> Vec<[f64; 2]> { + let list = s.execute("motion.list", &json!({})).unwrap_or_else(|e| panic!("{e}")); + let study = list["studies"].as_array().unwrap().iter().find(|m| m["name"] == study).unwrap_or_else(|| panic!("{study}: {list}")); + study["keys"][key]["points"].as_array().unwrap().iter().map(|p| [p[0].as_f64().unwrap(), p[1].as_f64().unwrap()]).collect() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn assert_points(got: &[[f64; 2]], want: &[[f64; 2]]) { + assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}"); + for (g, w) in got.iter().zip(want) { + assert!(close(g[0], w[0]) && close(g[1], w[1]), "{got:?} vs {want:?}"); + } +} + +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-motion-time-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn file(dir: &Path, name: &str, text: &str) -> String { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + path.to_string_lossy().into_owned() +} + +fn played(s: &mut Session, study: &str, step: f64) -> f64 { + let r = s.execute("motion.play", &json!({"study": study, "step": step})).unwrap_or_else(|e| panic!("{e}")); + r["values"][0]["values"][0]["value"].as_f64().unwrap_or_else(|| panic!("{r}")) +} + +/// Points at `time_s` are the points at `time_s * sample_rate_hz` steps: the study plays the same. +#[test] +fn time_points_interpolate_like_step_points_at_the_matching_steps() { + let mut s = door(); + run(&mut s, json!({"name": "ByStep", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [4, 40], [10, 100]]}]})); + let r = run( + &mut s, + json!({"name": "ByTime", "sample_rate_hz": 10, "duration_s": 1, "keys": [{"joint": "Hinge", "points": [ + {"time_s": 0, "value": 0}, {"time_s": 0.4, "value": 40}, {"time_s": 1, "value": 100}]}]}), + ); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(10), Some(1.0), Some(10.0)), "{r}"); + assert_points(&points(&mut s, "ByTime", 0), &points(&mut s, "ByStep", 0)); + for step in [0.0, 1.0, 3.0, 4.0, 7.0, 10.0] { + let (a, b) = (played(&mut s, "ByStep", step), played(&mut s, "ByTime", step)); + assert!(close(a, b), "step {step}: {a} vs {b}"); + } + // A rate kept by the study is reused by keys given in time later. + let id = r["study"].clone(); + run(&mut s, json!({"study": id, "keys": [{"joint": "Rail", "points": [{"time_s": 0.5, "value": 8}]}]})); + assert_points(&points(&mut s, "ByTime", 0), &[[5.0, 8.0]]); +} + +#[test] +fn duration_and_rate_give_the_steps_and_are_kept_by_the_study() { + let mut s = door(); + let key = json!([{"joint": "Hinge", "points": [{"time_s": 0.4, "value": 10}]}]); + let r = run(&mut s, json!({"name": "Timed", "duration_s": 2.5, "sample_rate_hz": 4, "keys": key})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(10), Some(2.5), Some(4.0)), "{r}"); + assert_points(&points(&mut s, "Timed", 0), &[[1.6, 10.0]]); + // What `motion.list` says goes back in: `steps` agrees with the duration and the rate. + run(&mut s, json!({"study": "Timed", "steps": 10, "duration_s": 2.5, "sample_rate_hz": 4})); + // A fraction of a step rounds, as `steps` does. + let r = run(&mut s, json!({"name": "Rounded", "duration_s": 0.26, "sample_rate_hz": 10})); + assert_eq!(r["steps"].as_u64(), Some(3), "{r}"); + // A new rate for the study keeps its duration, and its keys at the same seconds (0.4 s). + let r = run(&mut s, json!({"study": "Timed", "sample_rate_hz": 8})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64()), (Some(20), Some(2.5)), "{r}"); + assert_points(&points(&mut s, "Timed", 0), &[[3.2, 10.0]]); + // Steps given by hand end the study's duration, but not its rate. + let r = run(&mut s, json!({"study": "Timed", "steps": 5})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(5), None, Some(8.0)), "{r}"); + let list = s.execute("motion.list", &json!({})).unwrap(); + assert_eq!(list["studies"][0]["sample_rate_hz"], 8.0, "{list}"); + assert!(list["studies"][0].get("duration_s").is_none(), "{list}"); +} + +#[test] +fn mixed_or_unreadable_times_are_refused() { + let mut s = door(); + let mixed = json!({"sample_rate_hz": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], {"time_s": 1, "value": 5}]}]}); + assert!(refused(&mut s, mixed).contains("all by `step` or all by `time_s`")); + let across = json!({"sample_rate_hz": 10, "keys": [ + {"joint": "Hinge", "points": [{"step": 0, "value": 0}]}, {"joint": "Rail", "points": [{"time_s": 1, "value": 5}]}]}); + assert!(refused(&mut s, across).contains("all by `step` or all by `time_s`")); + let at = |time: Value| json!({"sample_rate_hz": 10, "keys": [{"joint": "Hinge", "points": [{"time_s": time, "value": 5}]}]}); + for time in [json!(-0.5), json!(null), json!("1"), json!(f64::NAN), json!(1e12)] { + assert!(refused(&mut s, at(time.clone())).contains("time_s"), "{time}"); + } + for rate in [json!(0), json!(-4), json!(null)] { + assert!(refused(&mut s, json!({"sample_rate_hz": rate, "steps": 10})).contains("`sample_rate_hz` must be a number above 0"), "{rate}"); + } + assert!(s.execute("motion.study", &json!({"sample_rate_hz": "fast", "steps": 10})).is_err()); + assert!(refused(&mut s, json!({"duration_s": 0, "sample_rate_hz": 10})).contains("`duration_s` must be a number above 0")); + assert!(refused(&mut s, json!({"duration_s": 1})).contains("needs `sample_rate_hz`")); + assert!(refused(&mut s, json!({"duration_s": 1, "sample_rate_hz": 10, "steps": 11})).contains("not both")); + assert!(refused(&mut s, json!({"duration_s": 1e6, "sample_rate_hz": 10})).contains("1…100000")); + assert!(refused(&mut s, json!({"duration_s": 0.01, "sample_rate_hz": 10})).contains("1…100000")); + let no_rate = json!({"keys": [{"joint": "Hinge", "points": [{"time_s": 1, "value": 5}]}]}); + assert!(refused(&mut s, no_rate).contains("need `sample_rate_hz`")); + // Nothing was made. + assert!(s.doc.assembly.studies.is_empty()); +} + +/// Without any of the new fields a study is what it was: the reply, the listing and the saved +/// study carry no time base. +#[test] +fn a_study_timed_in_steps_is_unchanged() { + let mut s = door(); + let r = run(&mut s, json!({"name": "Plain", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 90]]}]})); + let mut reply: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect(); + reply.sort_unstable(); + assert_eq!(reply, ["keys", "name", "steps", "study"], "{r}"); + let saved = serde_json::to_value(s.doc.assembly.studies.first().unwrap()).unwrap(); + let mut fields: Vec<&str> = saved.as_object().unwrap().keys().map(String::as_str).collect(); + fields.sort_unstable(); + assert_eq!(fields, ["id", "keys", "name", "steps"], "{saved}"); + let list = s.execute("motion.list", &json!({})).unwrap(); + assert!(list["studies"][0].get("duration_s").is_none() && list["studies"][0].get("sample_rate_hz").is_none(), "{list}"); + // Changing it by steps leaves it so. + let r = run(&mut s, json!({"study": "Plain", "steps": 20})); + assert!(r.get("duration_s").is_none() && r.get("sample_rate_hz").is_none(), "{r}"); +} + +#[test] +fn a_csv_trajectory_becomes_time_keys_in_the_joints_units() { + let mut s = door(); + let dir = folder("csv"); + let csv = file(&dir, "run.csv", "time,theta,pos,note\r\n0,10,0.010,a\r\n0.1,20,0.020,\"b, c\"\r\n0.2,30,0.030,d\r\n0.3,40,0.040,e\r\n\r\n"); + let p = |extra: Value| { + let mut p = json!({"name": "Run", "file": csv, "columns": {"theta": "Hinge", "pos": "Rail"}, "units": {"pos": "m"}}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + let r = run(&mut s, p(json!({"zero_offset": true}))); + assert_eq!((r["steps"].as_u64(), r["keys"].as_u64()), (Some(3), Some(2)), "{r}"); + assert!(close(r["duration_s"].as_f64().unwrap(), 0.3) && close(r["sample_rate_hz"].as_f64().unwrap(), 10.0), "{r}"); + // Degrees and metres, less each column's first value, in the units `motion.list` shows. + assert_points(&points(&mut s, "Run", 0), &[[0.0, 0.0], [1.0, 10.0], [2.0, 20.0], [3.0, 30.0]]); + assert_points(&points(&mut s, "Run", 1), &[[0.0, 0.0], [1.0, 10.0], [2.0, 20.0], [3.0, 30.0]]); + // Stored in radians and mm. + let study = s.doc.assembly.studies.first().unwrap(); + let hinge = study.keys.iter().find(|k| s.doc.assembly.joints.iter().any(|j| j.id == k.joint && j.name == "Hinge")).unwrap(); + assert!(close(hinge.points[3].1, 30.0_f64.to_radians()), "{:?}", hinge.points); + // Without the offset the values are the file's; the study is replaced, not added to. + let id = r["study"].clone(); + run(&mut s, p(json!({"study": id}))); + assert_eq!(s.doc.assembly.studies.len(), 1); + assert_points(&points(&mut s, "Run", 0), &[[0.0, 10.0], [1.0, 20.0], [2.0, 30.0], [3.0, 40.0]]); + assert_points(&points(&mut s, "Run", 1), &[[0.0, 10.0], [1.0, 20.0], [2.0, 30.0], [3.0, 40.0]]); + // Radians, and another name for the time column. + let radians = file(&dir, "radians.csv", "t,x\n0,0\n1,1.5707963267948966\n"); + let r = run(&mut s, json!({"name": "Rad", "file": radians, "time_column": "t", "columns": {"x": "Hinge"}, "units": {"x": "rad"}})); + assert_eq!((r["steps"].as_u64(), r["sample_rate_hz"].as_f64()), (Some(1), Some(1.0)), "{r}"); + assert_points(&points(&mut s, "Rad", 0), &[[0.0, 0.0], [1.0, 90.0]]); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_json_trajectory_in_either_shape_and_resampled() { + let mut s = door(); + let dir = folder("json"); + let columns = file(&dir, "columns.json", r#"{"time": [0, 0.5, 1], "a": [0, 45, 90], "unit": "deg"}"#); + let rows = file(&dir, "rows.json", r#"[{"time": 0, "a": 0}, {"time": 0.5, "a": 45}, {"time": 1, "a": 90}]"#); + for (name, path) in [("Columns", &columns), ("Rows", &rows)] { + let r = run(&mut s, json!({"name": name, "file": path, "columns": {"a": "Hinge"}})); + assert_eq!((r["steps"].as_u64(), r["sample_rate_hz"].as_f64()), (Some(2), Some(2.0)), "{name}: {r}"); + assert_points(&points(&mut s, name, 0), &[[0.0, 0.0], [1.0, 45.0], [2.0, 90.0]]); + } + // Resampled to another rate, linearly between the samples. + let r = run(&mut s, json!({"name": "Fine", "file": columns, "columns": {"a": "Hinge"}, "sample_rate_hz": 4})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(4), Some(1.0), Some(4.0)), "{r}"); + assert_points(&points(&mut s, "Fine", 0), &[[0.0, 0.0], [1.0, 22.5], [2.0, 45.0], [3.0, 67.5], [4.0, 90.0]]); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_trajectory_the_study_cannot_use_is_refused() { + let mut s = door(); + let dir = folder("refused"); + let good = file(&dir, "good.csv", "time,a,b\n0,0,1\n1,10,2\n"); + let columns = json!({"a": "Hinge"}); + let with = |path: &str, columns: &Value| json!({"file": path, "columns": columns}); + for (p, why) in [ + (with(&good, &json!({"a": "Nowhere"})), "no joint `Nowhere`"), + (with(&good, &json!({"zzz": "Hinge"})), "no column `zzz`"), + (with(&good, &json!({"time": "Hinge"})), "time column"), + (with(&good, &json!({"a": "Hinge", "b": "Hinge"})), "driven by two columns"), + (with(&good, &json!({})), "`columns`"), + (json!({"file": good, "columns": {"a": "Hinge"}, "units": {"a": "m"}}), "not a unit of an angle"), + (json!({"file": good, "columns": {"a": "Rail"}, "units": {"a": "deg"}}), "not a unit of a distance"), + (json!({"file": good, "columns": {"a": "Hinge"}, "units": {"b": "deg"}}), "does not map"), + (json!({"file": good, "columns": {"a": "Hinge"}, "time_column": "t"}), "no column `t`"), + (json!({"file": good, "columns": {"a": "Hinge"}, "format": "xml"}), "csv or json"), + (json!({"file": good, "columns": {"a": "Hinge"}, "keys": []}), "not with `keys`"), + (json!({"file": good, "columns": {"a": "Hinge"}, "steps": 10}), "not with `steps`"), + (json!({"file": good, "columns": {"a": "Hinge"}, "duration_s": 10}), "not with `duration_s`"), + (json!({"file": good, "columns": {"a": "Hinge"}, "sample_rate_hz": 0}), "above 0"), + (json!({"columns": {"a": "Hinge"}}), "goes with `file`"), + (json!({"zero_offset": true}), "goes with `file`"), + (with(&dir.join("missing.csv").to_string_lossy(), &columns), "missing.csv"), + ] { + let message = refused(&mut s, p.clone()); + assert!(message.contains(why), "{p}: {message}"); + } + for (name, text, why) in [ + ("backwards.csv", "time,a\n0,0\n2,1\n1,2\n", "time does not increase"), + ("repeated.csv", "time,a\n0,0\n1,1\n1,2\n", "time does not increase"), + ("negative.csv", "time,a\n-1,0\n1,1\n", "cannot be negative"), + ("nan.csv", "time,a\n0,0\n1,nan\n", "not a finite number"), + ("infinite.csv", "time,a\n0,0\ninf,1\n", "not a finite number"), + ("text.csv", "time,a\n0,0\n1,high\n", "not a finite number"), + ("empty_cell.csv", "time,a\n0,0\n1,\n", "not a finite number"), + ("ragged.csv", "time,a\n0,0\n1\n", "1 fields, the header has 2"), + ("wide.csv", "time,a\n0,0,5\n1,1\n", "3 fields, the header has 2"), + ("quote.csv", "time,a\n0,\"0\n1,1\n", "not closed"), + ("twice.csv", "time,a,a\n0,0,0\n1,1,1\n", "named twice"), + ("one_row.csv", "time,a\n0,0\n", "at least 2 rows"), + ("header_only.csv", "time,a\n", "at least 2 rows"), + ("empty.csv", "", "empty"), + ("short.json", r#"{"time": [0, 1, 2], "a": [0, 1]}"#, "not all as long"), + ("row_gap.json", r#"[{"time": 0, "a": 0}, {"time": 1}]"#, "1 fields, the first row has 2"), + ("scalar.json", "5", "JSON must be"), + ("broken.json", r#"{"time": [0, 1"#, "not valid JSON"), + ("backwards.json", r#"{"time": [0, 2, 1], "a": [0, 1, 2]}"#, "time does not increase"), + ("string_number.json", r#"{"time": [0, 1], "a": [0, "1"]}"#, "not a finite number"), + ] { + let path = file(&dir, name, text); + let message = refused(&mut s, json!({"file": path, "columns": {"a": "Hinge"}})); + assert!(message.contains(why), "{name}: {message}"); + } + // Too many samples for a timeline, and for a key. + let long = file(&dir, "long.csv", "time,a\n0,0\n1000000,1\n"); + assert!(refused(&mut s, json!({"file": long, "columns": {"a": "Hinge"}, "sample_rate_hz": 1})).contains("1…100000")); + let fine = file(&dir, "fine.csv", "time,a\n0,0\n100,1\n"); + assert!(refused(&mut s, json!({"file": fine, "columns": {"a": "Hinge"}, "sample_rate_hz": 1000})).contains("points a key")); + // An extension that says nothing needs `format`. + let plain = file(&dir, "run.dat", "time,a\n0,0\n1,1\n"); + assert!(refused(&mut s, json!({"file": plain, "columns": {"a": "Hinge"}})).contains("csv or json")); + run(&mut s, json!({"file": plain, "format": "CSV", "columns": {"a": "Hinge"}})); + assert_eq!(s.doc.assembly.studies.len(), 1, "only the last one was made"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// The file is read like any file an agent reads: outside the folders it may use, it is refused. +#[test] +fn a_trajectory_outside_the_allowed_folders_is_refused() { + let mut s = door(); + let (inside, outside) = (folder("scope-in"), folder("scope-out")); + let allowed = file(&inside, "run.csv", "time,a\n0,0\n1,10\n"); + let elsewhere = file(&outside, "run.csv", "time,a\n0,0\n1,10\n"); + let ask = |path: &str| json!({"file": path, "columns": {"a": "Hinge"}}); + let (ok, no) = vfs::scoped(Some(PathScope::new([inside.clone()])), || { + (s.execute("motion.study", &ask(&allowed)), s.execute("motion.study", &ask(&elsewhere))) + }); + assert!(ok.is_ok(), "{ok:?}"); + let message = no.unwrap_err().to_string(); + assert!(message.contains("outside the folders this agent may use"), "{message}"); + assert_eq!(s.doc.assembly.studies.len(), 1, "the refused file made no study"); + for dir in [inside, outside] { + std::fs::remove_dir_all(dir).unwrap(); + } +} + +/// The file's first sample is time 0, and the timeline reaches its last sample, rounded up. +#[test] +fn an_imported_trajectory_starts_at_zero_and_never_ends_past_its_steps() { + let mut s = door(); + let dir = folder("start"); + let late = file(&dir, "late.csv", "time,a\n5,0\n6,10\n"); + let r = run(&mut s, json!({"name": "Late", "file": late, "columns": {"a": "Hinge"}})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64()), (Some(1), Some(1.0)), "{r}"); + assert_points(&points(&mut s, "Late", 0), &[[0.0, 0.0], [1.0, 10.0]]); + // 0.5 s at 3 Hz is 1.5 steps: 2 (the last sample is held at step 2). + let short = file(&dir, "short.csv", "time,a\n0,0\n0.25,5\n0.5,10\n"); + let r = run(&mut s, json!({"name": "Three", "file": short, "columns": {"a": "Hinge"}, "sample_rate_hz": 3})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64()), (Some(2), Some(0.5)), "{r}"); + assert_points(&points(&mut s, "Three", 0), &[[0.0, 0.0], [1.0, 20.0 / 3.0], [2.0, 10.0]]); + // A joint is named without quotes in a message, and an id works as a name does. + let message = refused(&mut s, json!({"file": short, "columns": {"a": "Hinge", "time": "Rail"}})); + assert!(message.contains("the time column `time`"), "{message}"); + let ids = file(&dir, "ids.csv", "time,a,b\n0,0,0\n1,1,1\n"); + let message = refused(&mut s, json!({"file": ids, "columns": {"a": "Hinge", "b": "Hinge"}})); + assert!(message.contains("joint `Hinge` is driven by two columns"), "{message}"); + let hinge = s.doc.assembly.joints.iter().find(|j| j.name == "Hinge").unwrap().id; + run(&mut s, json!({"name": "ById", "file": ids, "columns": {"a": hinge}})); + // More columns than a table has. + let wide: String = (0..1001).map(|i| format!("c{i}")).collect::>().join(","); + let wide = file(&dir, "wide.csv", &format!("time,{wide}\n")); + assert!(refused(&mut s, json!({"file": wide, "columns": {"c1": "Hinge"}})).contains("more than 1000 columns")); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// An import rounds its steps up (0.4 s at 3 Hz is 1.2 steps: 2); giving the study the rate it +/// already has keeps them, where rounding the product again would cut the timeline to 1. Another +/// rate still takes the steps its duration gives. +#[test] +fn the_same_rate_keeps_the_steps_an_import_rounded_up() { + let mut s = door(); + let dir = folder("same-rate"); + let path = file(&dir, "short.csv", "time,a\n0,0\n0.2,5\n0.4,10\n"); + let r = run(&mut s, json!({"name": "Imported", "file": path, "columns": {"a": "Hinge"}, "sample_rate_hz": 3})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(2), Some(0.4), Some(3.0)), "{r}"); + let before = points(&mut s, "Imported", 0); + let r = run(&mut s, json!({"study": r["study"], "sample_rate_hz": 3})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(2), Some(0.4), Some(3.0)), "{r}"); + assert_points(&points(&mut s, "Imported", 0), &before); + // A genuine change of rate recomputes the steps from the duration, as before. + let r = run(&mut s, json!({"study": r["study"], "sample_rate_hz": 10})); + assert_eq!((r["steps"].as_u64(), r["duration_s"].as_f64(), r["sample_rate_hz"].as_f64()), (Some(4), Some(0.4), Some(10.0)), "{r}"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// A study with a rate plots per second by it, as with a `duration`. +#[test] +fn a_plot_of_a_timed_study_is_per_second() { + let mut s = door(); + run(&mut s, json!({"name": "Swing", "sample_rate_hz": 10, "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 100]]}]})); + let r = s.execute("motion.plot", &json!({"study": "Swing", "joints": ["Hinge"]})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["joints"][0]["velocity_unit"], "deg/s", "{r}"); + assert!(close(r["time"][10].as_f64().unwrap(), 1.0), "{r}"); + // 10 degrees a step, ten steps a second. + assert!(close(r["joints"][0]["velocity"][5].as_f64().unwrap(), 100.0), "{r}"); + // A duration given to the plot still wins; a study timed in steps still plots per step. + let r = s.execute("motion.plot", &json!({"study": "Swing", "joints": ["Hinge"], "duration": 5})).unwrap(); + assert!(close(r["joints"][0]["velocity"][5].as_f64().unwrap(), 20.0), "{r}"); + run(&mut s, json!({"name": "Plain", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 100]]}]})); + let r = s.execute("motion.plot", &json!({"study": "Plain", "joints": ["Hinge"]})).unwrap(); + assert_eq!(r["joints"][0]["velocity_unit"], "deg/step", "{r}"); + assert!(r.get("time").is_none(), "{r}"); +} + +/// A new rate that would push a key past ±1e9 steps is refused whole; one on a study with no +/// duration scales its steps too. +#[test] +fn a_new_rate_is_refused_when_it_pushes_a_key_out_of_range() { + let mut s = door(); + let key = json!([{"joint": "Hinge", "points": [{"time_s": 1e8, "value": 10}]}]); + run(&mut s, json!({"name": "Far", "sample_rate_hz": 1, "steps": 5, "keys": key})); + let message = refused(&mut s, json!({"study": "Far", "sample_rate_hz": 100})); + assert!(message.contains("past ±1e9 steps"), "{message}"); + assert_points(&points(&mut s, "Far", 0), &[[1e8, 10.0]]); + assert_eq!(s.doc.assembly.studies.first().and_then(|m| m.sample_rate_hz), Some(1.0)); + // No duration: the timeline scales with the rate, rounded up. + let r = run(&mut s, json!({"name": "Hand", "sample_rate_hz": 4, "steps": 8})); + let r = run(&mut s, json!({"study": r["study"], "sample_rate_hz": 6})); + assert_eq!(r["steps"].as_u64(), Some(12), "{r}"); +} + +/// A trajectory whose times are out of range is refused. +#[test] +fn a_trajectory_out_of_range_in_time_is_refused() { + let mut s = door(); + let dir = folder("range"); + let late = file(&dir, "late.csv", "time,a\n0,0\n2000000000,1\n"); + let message = refused(&mut s, json!({"file": late, "columns": {"a": "Hinge"}})); + assert!(message.contains("below 1e9 seconds"), "{message}"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 6914f1ca486..62a5087265e 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -49,7 +49,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&INSERT_CONTRACT) .output(output_schema_for::) .params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction? (from the shank's tip toward the head), flip?, name?, material?, \ - auto_length? (length from the hole's stack), min_engagement_d?, washer_thickness_mm?, through_bolt?"), + auto_length? (length from the hole's stack), min_engagement_d?, washer_thickness_mm?, through_bolt?, min_edge_distance_mm?, check_tool_clearance? (both off by default: the reply then adds checks, as inspect.fastener_checks gives them, and warnings; the part is placed either way)"), CommandSpec::new("parts.insert", "Insert Part", crate::checked!("parts.insert", insert_atomic)).begins_edit() .icon("fastener") .contract(&INSERT_CONTRACT) @@ -64,15 +64,18 @@ pub static COMMANDS: &[CommandSpec] = &[ them (one component, placed and seated once per pick) | point?: [x,y,z] with direction?: [x,y,z] (no joint: the part's seating plane, under a head or \ the bottom of a nut, washer or bearing, the top of a set screw, pin or countersunk head, goes to point, and direction is its +z, from the shank's tip toward the head; default [0,0,1], \ head up, shank down -z); flip?: bool (default false: turned over, head into the material with at, +z against direction \ - with point); material?: physical material (default \"Steel\"); hardness_class?: \"200 HV\" | \"300 HV\" | \"380 HV\" (washer, washer_narrow: saved as a part property; a washer under 300 HV under a property class 10.9 or 12.9 screw adds a warning); property_class?: \"4.6\" … \"12.9\" (ISO 898-1, metric only) (screws and bolts: saved as a part property); name?; thread?: for a part with a metric thread, cosmetic (default: recorded on the face, the body unchanged) | \ + with point); material?: physical material (default \"Steel\"; \"Stainless Steel\" with an A2-70 or A4-80 property_class); \ + hardness_class?: \"200 HV\" | \"300 HV\" | \"380 HV\" (washer, washer_narrow: saved as a part property; a washer under 300 HV under a property class 10.9 or 12.9 screw adds a warning); \ + property_class?: metric screws and bolts 4.6 | 4.8 | 5.6 | 5.8 | 6.8 | 8.8 | 9.8 | 10.9 | 12.9 (ISO 898-1), metric nuts 5 | 6 | 8 | 10 | 12 (ISO 898-2), both A2-70 | A4-80 (ISO 3506); saved as a part property and in its part number; \ + finish?, supplier?, catalog_part_number?: text of at most 200 characters, kept on the component (the finish is its BOM finish; the others are BOM properties); name?; thread?: for a part with a metric thread, cosmetic (default: recorded on the face, the body unchanged) | \ modeled (cut into the body over the standard's thread length from the tip, the start chamfered; slower, and refused past 80 \ turns); auto_length?: bool (default false; with at, and no length: measure the stack of coaxial holes under each picked rim and \ take the shortest standard length that engages the tapped layer min_engagement_d? nominal diameters (default 1.5; capped at the \ tapped layer's depth, with a warning) without passing a blind \ tapped hole's floor less two thread pitches (bottoming clearance), or, with no thread, with through_bolt?: bool, clears a nut and two pitches; washer_thickness_mm? (default 0) is the thickness of a washer not placed in the model, added under the head (ignored, with a warning, when the pick is on a placed washer); \ - when nothing fits the default length stays and warnings says why) → component, occurrence, thread? (how the thread was made, for a part with a metric thread), \ + when nothing fits the default length stays and warnings says why); min_edge_distance_mm?, check_tool_clearance? (both off by default: the reply then adds checks and warnings, as parts.fastener's) → component, occurrence, thread? (how the thread was made, for a part with a metric thread), \ joint?, directions (each placement's head direction in the world, the one \ - chosen), and with at: occurrences, joints (one per pick, in pick order); hardness_class?, property_class?, length_mm?, warnings? (non-blocking)", + chosen), and with at: occurrences, joints (one per pick, in pick order); hardness_class?, property_class?, length_mm?, checks?, warnings? (non-blocking)", ), CommandSpec::new("parts.seats", "Resolve Fastener Seats", crate::checked!("parts.seats", resolve_seats)) .icon("fastener") @@ -133,8 +136,11 @@ fn has_hardness(family: &str) -> bool { matches!(family, "washer" | "washer_narrow") } -/// The property classes of a steel screw or bolt (ISO 898-1) that `property_class` takes. -const PROPERTY_CLASSES: &[&str] = &["4.6", "4.8", "5.6", "5.8", "6.8", "8.8", "9.8", "10.9", "12.9"]; +/// The property classes `parts.insert` takes: ISO 898-1 for metric carbon steel screws and bolts, +/// ISO 898-2 for metric nuts, and ISO 3506 for the stainless A2-70 and A4-80 of both. +const ISO_898_1: &[&str] = &["4.6", "4.8", "5.6", "5.8", "6.8", "8.8", "9.8", "10.9", "12.9"]; +const ISO_898_2: &[&str] = &["5", "6", "8", "10", "12"]; +const ISO_3506: &[&str] = &["A2-70", "A4-80"]; /// The property classes at which a washer under 300 HV is too soft for the screw's clamp load. const HIGH_PROPERTY_CLASSES: &[&str] = &["10.9", "12.9"]; @@ -1435,6 +1441,103 @@ fn length_param(p: &Value, cmd: &str) -> Result> { } } +/// The longest `finish`, `supplier` or `catalog_part_number`, in characters. +const MAX_CATALOG_TEXT: usize = 200; + +/// What `parts.insert` records about where a fastener comes from (#24215), all optional: its +/// `finish`, `supplier` and `catalog_part_number`. The finish is the component's `finish` part +/// property (a column of the bill of materials); the other two are free properties of the +/// component under their own names (the bill lists them in its properties). +#[derive(Default)] +struct Catalog { + finish: Option, + supplier: Option, + catalog_part_number: Option, +} + +impl Catalog { + fn read(p: &Value, cmd: &str) -> Result { + let finish = catalog_text(p, "finish", cmd)?; + let supplier = catalog_text(p, "supplier", cmd)?; + let catalog_part_number = catalog_text(p, "catalog_part_number", cmd)?; + Ok(Catalog { finish, supplier, catalog_part_number }) + } +} + +/// An optional text: left out or `null` is none; else text with something in it, one line, at most +/// [`MAX_CATALOG_TEXT`] characters, kept trimmed. +fn catalog_text(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let text = v.as_str().map(str::trim).ok_or_else(|| bad(cmd, format!("`{key}` must be text")))?; + if text.is_empty() { + return Err(bad(cmd, format!("`{key}` must not be empty"))); + } + if text.chars().count() > MAX_CATALOG_TEXT { + return Err(bad(cmd, format!("`{key}` is longer than {MAX_CATALOG_TEXT} characters"))); + } + if text.chars().any(char::is_control) { + return Err(bad(cmd, format!("`{key}` must be one line of text"))); + } + Ok(Some(text.to_string())) +} + +/// The material of a part given no `material`: stainless steel for a stainless class (a +/// material of the library), else the default, steel. +fn default_material(property_class: Option<&str>) -> &'static str { + if property_class.is_some_and(|c| c.starts_with('A')) { "Stainless Steel" } else { "Steel" } +} + +/// A material given that contradicts the class (steel with a stainless class, stainless steel +/// with a carbon steel one): kept as given, and said. +fn class_material_warnings(property_class: Option<&str>, material: &str) -> Vec { + match property_class { + Some(class) if class.starts_with('A') && material == "Steel" => vec![format!("material Steel with the stainless property_class {class}")], + Some(class) if !class.starts_with('A') && material == "Stainless Steel" => { + vec![format!("material Stainless Steel with the carbon steel property_class {class}")] + } + _ => Vec::new(), + } +} + +/// A part's part number and description with its property class, so that two classes of one size +/// are two rows of the bill of materials: `ISO 4017 M8x30 - A2-70`, `Hex Bolt M8x30 A2-70`. +fn classed(identity: (String, String), class: Option<&str>) -> (String, String) { + match class { + Some(class) => (format!("{} - {class}", identity.0), format!("{} {class}", identity.1)), + None => identity, + } +} + +/// A resized part is no longer the catalog part its number named: drop `catalog_part_number` and say so. +fn drop_catalog_number(s: &mut Session, comp: u64) -> Vec { + let has = s.doc.components.iter().find(|c| c.id == comp).is_some_and(|c| c.properties.contains_key("catalog_part_number")); + if !has { + return Vec::new(); + } + if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) { + c.properties.remove("catalog_part_number"); + } + vec!["catalog_part_number removed: it named the old size".to_string()] +} + +/// Write what the insert was given on the new component; nothing given, nothing written. +fn set_catalog(s: &mut Session, comp: u64, catalog: &Catalog) { + use solidcraft_doc::metadata::{FINISH, Owner}; + if catalog.finish.is_none() && catalog.supplier.is_none() && catalog.catalog_part_number.is_none() { + return; + } + let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == comp) else { return }; + if let Some(finish) = &catalog.finish { + let _ = c.metadata.set(Owner::Component, FINISH, Value::String(finish.clone())); + } + let free = [("supplier", catalog.supplier.as_deref()), ("catalog_part_number", catalog.catalog_part_number.as_deref())]; + for (name, value) in free { + if let Some(value) = value { + c.properties.insert(name.to_string(), value.to_string()); + } + } +} + /// Building the part and seating it runs many feature and joint commands: as in /// [`resize_atomic`], they run on a scratch session and the insert is one undo step. fn insert_atomic(s: &mut Session, p: &Value) -> Result { @@ -1458,9 +1561,11 @@ fn insert(s: &mut Session, p: &Value) -> Result { let explicit = length_param(p, cmd)?; let mut sh = shape(&family, &size, explicit).map_err(|e| bad(cmd, e))?; let hardness = hardness_param(p, cmd, &family)?; - let property_class = property_class_param(p, cmd, &family, &sh)?; + let property_class = property_class_param(p, cmd, &family)?; let mode = thread_mode(p, cmd, &family, ThreadMode::Cosmetic)?; + let catalog = Catalog::read(p, cmd)?; check_turns(&family, &sh, mode).map_err(|e| bad(cmd, e))?; + let check_opts = super::fastener_checks::options(p, cmd)?; let auto = stack::Opts::parse(p, cmd)?; // A pick on a hole's rim also touches its end face: step onto the wall just inside the rim. // Each hole's occurrence is found before the part exists, so a pick off every body fails the @@ -1502,7 +1607,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let c = run(s, "component.create", json!({"name": name, "grounded": false}))?; let (comp, occ) = (c["component"].as_u64().unwrap_or(0), c["occurrence"].as_u64().unwrap_or(0)); build(s, &family, &sh, mode, None)?; - let material_name = str_(p, "material").unwrap_or("Steel"); + let material_name = str_(p, "material").unwrap_or(default_material(property_class)); let canonical = s.doc.material_name(material_name).ok_or_else(|| bad(cmd, format!("unknown material `{material_name}` (see material.list)")))?; let bodies: Vec = s.model.state().bodies.iter().filter(|b| s.doc.model_body_component(b) == comp).map(|b| b.name.clone()).collect(); for name in bodies { @@ -1515,8 +1620,9 @@ fn insert(s: &mut Session, p: &Value) -> Result { s.doc_mut() .parts .insert(comp, solidcraft_doc::StandardPart { family: family.clone(), size: size.clone(), length: shape_len(&sh), thread: mode.saved() }); - set_identity(s, comp, identity(&family, &size, &sh, mode), None); + set_identity(s, comp, classed(identity(&family, &size, &sh, mode), property_class), None); set_part_properties(s, comp, hardness, property_class); + set_catalog(s, comp, &catalog); run(s, "component.activate", json!({"component": active}))?; let mut out = InsertedPart { component: comp, @@ -1532,7 +1638,9 @@ fn insert(s: &mut Session, p: &Value) -> Result { length_mm: auto_length, warnings, param_warnings: Vec::new(), + checks: None, }; + out.param_warnings = class_material_warnings(property_class, &canonical); // The part's −z (its shank) mates with the seat's outward z; flipped, its +z does. let part_z = if flip { [0.0, 0.0, 1.0] } else { [0.0, 0.0, -1.0] }; if !seats.is_empty() { @@ -1594,6 +1702,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { out.directions = vec![head_direction(s, occ)]; } out.warnings.extend(soft_washer_warnings(s, comp)); + super::fastener_checks::add_checks(s, &check_opts, cmd, &mut out); reply(cmd, out) } @@ -1615,26 +1724,34 @@ fn hardness_param(p: &Value, cmd: &str, family: &str) -> Result Result> { - let given = match p.get("property_class") { - None | Some(Value::Null) => return Ok(None), - Some(Value::String(v)) => v.trim(), - Some(_) => return Err(bad(cmd, format!("`property_class` must be one of {}", PROPERTY_CLASSES.join(", ")))), - }; - let class = PROPERTY_CLASSES.iter().copied().find(|c| *c == given).ok_or_else(|| { - bad(cmd, format!("`property_class` must be one of {}, not `{}`", PROPERTY_CLASSES.join(", "), super::features::brief(given))) - })?; +/// `property_class` as a call gives it: ISO 898-1 for metric screws and bolts, ISO 898-2 for +/// metric nuts, and ISO 3506 (`A2-70`, `A4-80`) for both. +fn property_class_param(p: &Value, cmd: &str, family: &str) -> Result> { + let Some(text) = catalog_text(p, "property_class", cmd)? else { return Ok(None) }; if is_inch(family) { return Err(bad( cmd, - "`property_class` is an ISO 898-1 class, for a metric screw or bolt: inch parts have none here (SAE and ASTM grades are not supported)", + "`property_class` is an ISO 898-1 / 898-2 / 3506 class, for a metric screw, bolt or nut: inch parts have none here (SAE and ASTM grades are not supported)", )); } - if !matches!(sh, Shape::Screw { .. }) { - return Err(bad(cmd, "`property_class` is for a screw or a bolt")); - } - Ok(Some(class)) + // Screws and bolts have ISO 898-1 classes, nuts ISO 898-2; either may be stainless. + let (carbon, standard) = match family { + "socket_head_cap_screw" + | "button_head_cap_screw" + | "countersunk_socket_screw" + | "hex_bolt" + | "hex_bolt_gost" + | "socket_head_cap_screw_gost" => (ISO_898_1, "ISO 898-1"), + "hex_nut" | "hex_nut_gost" | "hex_nut_thin_gost" => (ISO_898_2, "ISO 898-2"), + _ => { + return Err(bad(cmd, format!("a {} has no `property_class` (give material \"Stainless Steel\")", label(family).to_lowercase()))); + } + }; + let shown: String = text.chars().take(40).collect(); + let found = carbon.iter().chain(ISO_3506).copied().find(|c| c.eq_ignore_ascii_case(&text)); + Ok(Some(found.ok_or_else(|| { + bad(cmd, format!("unknown `property_class` `{shown}` ({standard}: {}; ISO 3506: {})", carbon.join(", "), ISO_3506.join(", "))) + })?)) } /// Save a standard part's hardness class and property class as its part properties: an object @@ -2126,8 +2243,13 @@ fn resize(s: &mut Session, p: &Value) -> Result { marker.saturating_add(active) }); let default_name = part_name(&part.family, &size, &sh); - let was = shape(&part.family, &part.size, part.length).ok().map(|old| identity(&part.family, &part.size, &old, ThreadMode::of(&part))); - set_identity(s, comp, identity(&part.family, &size, &sh, mode), was); + // A property class is part of the part number and description (see `classed`). + let class = part_property(s, comp, "property_class"); + let was = shape(&part.family, &part.size, part.length) + .ok() + .map(|old| classed(identity(&part.family, &part.size, &old, ThreadMode::of(&part)), class.as_deref())); + set_identity(s, comp, classed(identity(&part.family, &size, &sh, mode), class.as_deref()), was); + let warnings = if size != part.size || shape_len(&sh) != part.length { drop_catalog_number(s, comp) } else { Vec::new() }; s.doc_mut() .parts .insert(comp, solidcraft_doc::StandardPart { family: part.family.clone(), size: size.clone(), length: shape_len(&sh), thread: mode.saved() }); @@ -2151,7 +2273,52 @@ fn resize(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(e)); } let thread = threaded(&part.family).then(|| mode.id().to_string()); - reply(cmd, ResizedPart { component: comp, name, size, length: shape_len(&sh), thread, param_warnings: Vec::new() }) + reply(cmd, ResizedPart { component: comp, name, size, length: shape_len(&sh), thread, param_warnings: warnings }) +} + +/// Where a tool takes hold of a placed standard part (#24216), in the part's own frame: its +/// seating plane is z = 0 and its head points to +z. +pub(super) struct Drive { + /// A hex key into a socket in the head, not a socket about a hex head or nut. + pub key: bool, + /// The hex's width across flats, in mm: the key's size, or the head's or nut's. + pub across_flats: f64, + /// How far above the seating plane the drive's top lies, in mm. + pub top: f64, +} + +/// The drive of a standard part of this family, size and length; none for a part a tool does not +/// turn (a washer, a bearing, a pin). +pub(super) fn drive(family: &str, size: &str, length: Option) -> Option { + match shape(family, size, length).ok()? { + Shape::Screw { head: Head::Hex { s, k }, .. } => Some(Drive { key: false, across_flats: s, top: k }), + Shape::Screw { head: Head::Round { k, .. } | Head::Dome { k, .. }, socket: Some((s, _)), .. } => { + Some(Drive { key: true, across_flats: s, top: k }) + } + Shape::Screw { head: Head::Countersunk { .. }, socket: Some((s, _)), .. } | Shape::Rod { socket: Some((s, _)), .. } => { + Some(Drive { key: true, across_flats: s, top: 0.0 }) + } + Shape::Nut { s, m, .. } => Some(Drive { key: false, across_flats: s, top: m }), + _ => None, + } +} + +/// The radius of the smallest cylinder about a standard part's axis that holds it (mm): its head, +/// across the corners of a hex, or its shank, or the outside of a nut, washer or bearing. +pub(super) fn envelope_radius(family: &str, size: &str, length: Option) -> Option { + let hex = |s: f64| s / 3f64.sqrt(); + Some(match shape(family, size, length).ok()? { + Shape::Screw { d, head, .. } => { + let head = match head { + Head::Round { dk, .. } | Head::Dome { dk, .. } | Head::Countersunk { dk, .. } => dk / 2.0, + Head::Hex { s, .. } => hex(s), + }; + head.max(d / 2.0) + } + Shape::Nut { s, .. } => hex(s), + Shape::Ring { d_out, .. } => d_out / 2.0, + Shape::Rod { d, .. } => d / 2.0, + }) } #[cfg(test)] @@ -3967,3 +4134,7 @@ mod tests { assert_eq!(r["directions"], json!([[0.0, 0.0, 1.0]]), "{r}"); } } + +#[cfg(test)] +#[path = "parts_catalog_tests.rs"] +mod catalog_tests; diff --git a/crates/engine/src/cmd/parts_catalog_tests.rs b/crates/engine/src/cmd/parts_catalog_tests.rs new file mode 100644 index 00000000000..3b5678a73a5 --- /dev/null +++ b/crates/engine/src/cmd/parts_catalog_tests.rs @@ -0,0 +1,225 @@ +//! Property classes, finish, supplier and catalog part number of `parts.insert` (#24215). + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn refused(s: &mut Session, p: Value) -> String { + match s.execute("parts.insert", &p) { + Ok(v) => panic!("{p} should be refused, got {v}"), + Err(e) => e.to_string(), + } +} + +fn material_of(s: &Session, comp: u64) -> String { + let Some(body) = s.model.state().bodies.iter().find(|b| s.doc.model_body_component(b) == comp).map(|b| b.name.clone()) else { + panic!("the part has no body") + }; + s.doc.body_material(&body) +} + +fn component(s: &Session, comp: u64) -> &solidcraft_doc::Component { + let Some(c) = s.doc.components.iter().find(|c| c.id == comp) else { panic!("no component {comp}") }; + c +} + +fn class_of(s: &Session, comp: u64) -> Option { + super::part_property(s, comp, "property_class") +} + +fn id_of(out: &Value) -> u64 { + out["component"].as_u64().unwrap_or(0) +} + +#[test] +fn stainless_classes_are_kept_and_pick_stainless_steel() { + let mut s = Session::default(); + let a2 = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "A2-70"})); + assert_eq!(material_of(&s, id_of(&a2)), "Stainless Steel"); + assert_eq!(class_of(&s, id_of(&a2)).as_deref(), Some("A2-70")); + assert_eq!(a2["property_class"], "A2-70", "{a2}"); + assert!(!component(&s, id_of(&a2)).properties.contains_key("property_class"), "only the part property is stored"); + assert!(a2.get("param_warnings").is_none(), "{a2}"); + + // Any spelling of the class is kept in the standard's; nuts take it too. + let a4 = run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M8", "property_class": " a4-80 "})); + assert_eq!(material_of(&s, id_of(&a4)), "Stainless Steel"); + assert_eq!(class_of(&s, id_of(&a4)).as_deref(), Some("A4-80")); + assert_eq!(a4["property_class"], "A4-80", "{a4}"); + + // A material given stays (and is said to contradict the class); a carbon steel class changes + // nothing but the property. + let brass = + run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "A4-80", "material": "Brass"})); + assert_eq!(material_of(&s, id_of(&brass)), "Brass"); + let steel = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "8.8"})); + assert_eq!(material_of(&s, id_of(&steel)), "Steel"); + assert_eq!(class_of(&s, id_of(&steel)).as_deref(), Some("8.8")); + let nut = run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M8", "property_class": "8"})); + assert_eq!(class_of(&s, id_of(&nut)).as_deref(), Some("8")); + assert_eq!(nut["property_class"], "8", "{nut}"); + + let odd = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "A2-70", "material": "Steel"})); + assert_eq!(odd["param_warnings"].as_array().map(Vec::len), Some(1), "{odd}"); + let odd = run( + &mut s, + "parts.insert", + json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "8.8", "material": "Stainless Steel"}), + ); + assert_eq!(odd["param_warnings"].as_array().map(Vec::len), Some(1), "{odd}"); +} + +#[test] +fn a_class_must_suit_the_family_and_be_known() { + let mut s = Session::default(); + for class in [json!("A2-99"), json!("9.9"), json!(8.8)] { + let e = refused(&mut s, json!({"family": "hex_bolt", "size": "M6", "property_class": class})); + assert!(e.contains("property_class"), "{e}"); + } + let e = refused(&mut s, json!({"family": "hex_bolt", "size": "M6", "property_class": " "})); + assert!(e.contains("must not be empty"), "{e}"); + let e = refused(&mut s, json!({"family": "hex_bolt", "size": "M6", "property_class": 5})); + assert!(e.contains("must be text"), "{e}"); + // A nut has the ISO 898-2 classes, a bolt the ISO 898-1 ones. + let e = refused(&mut s, json!({"family": "hex_nut", "size": "M6", "property_class": "8.8"})); + assert!(e.contains("ISO 898-2"), "{e}"); + let e = refused(&mut s, json!({"family": "hex_bolt", "size": "M6", "property_class": "8"})); + assert!(e.contains("ISO 898-1"), "{e}"); + // The other families have none. + for (family, size, label) in + [("washer", "M6", "washer"), ("set_screw", "M6", "set screw"), ("dowel_pin", "6", "dowel pin"), ("bearing", "608", "bearing")] + { + for class in ["8.8", "A2-70"] { + let e = refused(&mut s, json!({"family": family, "size": size, "property_class": class})); + assert!(e.contains(&format!("a {label} has no `property_class`")), "{e}"); + } + } + assert!(s.doc.components.is_empty(), "a refused insert makes nothing"); +} + +#[test] +fn the_class_makes_two_bom_rows_and_resize_keeps_it() { + let mut s = Session::default(); + let a2 = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "A2-70"})); + let carbon = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "8.8"})); + let plain = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30})); + let number = |s: &Session, out: &Value| component(s, id_of(out)).metadata.part_number().unwrap_or_default().to_string(); + let (a2_number, plain_number) = (number(&s, &a2), number(&s, &plain)); + assert!(a2_number.ends_with(" - A2-70"), "{a2_number}"); + assert!(number(&s, &carbon).ends_with(" - 8.8")); + assert!(!plain_number.contains(" - "), "{plain_number}: unset class leaves the number alone"); + assert!(component(&s, id_of(&a2)).metadata.description().is_some_and(|d| d.ends_with(" A2-70"))); + + let bom = run(&mut s, "assembly.bom", json!({})); + assert_eq!(bom["rows"].as_array().map(Vec::len), Some(3), "{bom}"); + + // The suffix follows the size. + run(&mut s, "parts.resize", json!({"component": id_of(&a2), "length": 40})); + let resized = number(&s, &a2); + assert!(resized.ends_with(" - A2-70") && resized != a2_number, "{resized}"); +} + +#[test] +fn resizing_drops_the_catalog_number_it_outgrew() { + let mut s = Session::default(); + let out = run( + &mut s, + "parts.insert", + json!({"family": "hex_bolt", "size": "M8", "length": 30, "property_class": "A2-70", "finish": "passivated", "supplier": "Acme", "catalog_part_number": "AC-1"}), + ); + let comp = id_of(&out); + // The same size changes nothing. + let same = run(&mut s, "parts.resize", json!({"component": comp, "size": "M8"})); + assert!(same.get("param_warnings").is_none(), "{same}"); + assert!(component(&s, comp).properties.contains_key("catalog_part_number")); + + let r = run(&mut s, "parts.resize", json!({"component": comp, "size": "M10"})); + assert_eq!(r["param_warnings"], json!(["catalog_part_number removed: it named the old size"]), "{r}"); + let c = component(&s, comp); + assert!(!c.properties.contains_key("catalog_part_number")); + assert!(!c.properties.contains_key("property_class")); + assert_eq!(c.properties.get("supplier").map(String::as_str), Some("Acme")); + assert_eq!(c.metadata.finish(), Some("passivated")); + assert_eq!(class_of(&s, comp).as_deref(), Some("A2-70")); +} + +#[test] +fn finish_supplier_and_catalog_number_are_kept_and_listed_in_the_bom() { + let mut s = Session::default(); + let out = run( + &mut s, + "parts.insert", + json!({"family": "socket_head_cap_screw", "size": "M5", "length": 16, "finish": " black oxide ", "supplier": "Acme Fasteners", "catalog_part_number": "AF-4762-M5x16"}), + ); + let c = component(&s, id_of(&out)); + assert_eq!(c.metadata.finish(), Some("black oxide")); + assert_eq!(c.properties.get("supplier").map(String::as_str), Some("Acme Fasteners")); + assert_eq!(c.properties.get("catalog_part_number").map(String::as_str), Some("AF-4762-M5x16")); + assert!(!c.properties.contains_key("property_class")); + assert_eq!(class_of(&s, id_of(&out)), None); + + let bom = run(&mut s, "assembly.bom", json!({})); + let Some(rows) = bom["rows"].as_array() else { panic!("rows missing") }; + assert_eq!(rows.len(), 1, "{bom}"); + assert_eq!(rows[0]["finish"], "black oxide", "{bom}"); + assert_eq!(rows[0]["properties"]["supplier"], "Acme Fasteners", "{bom}"); + assert_eq!(rows[0]["properties"]["catalog_part_number"], "AF-4762-M5x16", "{bom}"); +} + +#[test] +fn several_holes_write_the_metadata_once_on_the_shared_definition() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [10, 15, 10], "diameter": 6.4})); + run(&mut s, "solid.hole", json!({"position": [30, 15, 10], "diameter": 6.4})); + let out = run( + &mut s, + "parts.insert", + json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20, "at": [[13.2, 15.0, 10.0], [33.2, 15.0, 10.0]], "finish": "zinc", "supplier": "Acme"}), + ); + assert_eq!(out["occurrences"].as_array().map(Vec::len), Some(2), "{out}"); + let c = component(&s, id_of(&out)); + assert_eq!(c.metadata.finish(), Some("zinc")); + assert_eq!(c.properties.get("supplier").map(String::as_str), Some("Acme")); + assert_eq!(s.doc.components.iter().filter(|c| c.properties.contains_key("supplier")).count(), 1, "one definition holds it"); + let bom = run(&mut s, "assembly.bom", json!({})); + let Some(rows) = bom["rows"].as_array() else { panic!("rows missing") }; + let Some(row) = rows.iter().find(|r| r["finish"] == "zinc") else { panic!("no zinc row: {bom}") }; + assert_eq!(row["count"], 2, "{bom}"); + assert_eq!(row["properties"]["supplier"], "Acme", "{bom}"); +} + +#[test] +fn bad_finish_supplier_and_catalog_text_is_refused() { + let mut s = Session::default(); + let long = "x".repeat(201); + for key in ["finish", "supplier", "catalog_part_number"] { + for value in [json!(" "), json!(""), json!(long), json!(5), json!("two\nlines")] { + let e = refused(&mut s, json!({"family": "hex_nut", "size": "M6", key: value})); + assert!(e.contains(key), "{e}"); + } + // The longest text is fine, and so is null (as left out). + run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M6", key: "y".repeat(200)})); + run(&mut s, "parts.insert", json!({"family": "hex_nut", "size": "M6", key: Value::Null})); + } +} + +#[test] +fn without_them_nothing_is_written() { + let mut s = Session::default(); + let out = run(&mut s, "parts.insert", json!({"family": "hex_bolt", "size": "M8", "length": 30})); + let comp = id_of(&out); + let c = component(&s, comp); + assert!(c.properties.is_empty(), "{:?}", c.properties); + assert_eq!(c.metadata.finish(), None); + assert_eq!(c.metadata.0.keys().map(String::as_str).collect::>(), ["description", "part_number"]); + assert_eq!(material_of(&s, comp), "Steel"); + let keys: Vec<&String> = out.as_object().map(|o| o.keys().collect()).unwrap_or_default(); + for key in ["property_class", "finish", "supplier", "catalog_part_number", "param_warnings"] { + assert!(!keys.iter().any(|k| *k == key), "{out}"); + } +} diff --git a/crates/engine/src/cmd/socket_reach.rs b/crates/engine/src/cmd/socket_reach.rs index 357566d4110..c2ee42cbee1 100644 --- a/crates/engine/src/cmd/socket_reach.rs +++ b/crates/engine/src/cmd/socket_reach.rs @@ -76,29 +76,19 @@ pub(crate) fn space(s: &Session, pick: Vec3, diameter: f64, length: f64, flip: b Ok(Space { origin, direction, body }) } -fn socket_reach(s: &mut Session, p: &Value) -> Result { - let cmd = "inspect.socket_reach"; - let size = |k: &str| -> Result { - num(p, k) - .filter(|x| *x > 0.0 && *x <= MAX_SIZE) - .ok_or_else(|| bad(cmd, format!("`{k}` must be a length in mm above 0 and at most {MAX_SIZE}"))) - }; - let (diameter, length) = (size("diameter")?, size("length")?); - let flip = match p.get("flip") { - None | Some(Value::Null) => false, - Some(_) => bool_(p, "flip").ok_or_else(|| bad(cmd, "`flip` must be true or false"))?, - }; - let ignore = string_list(cmd, p, "ignore")?; - let pick = p.get("edge").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "`edge` must be a point [x, y, z] on a circular edge"))?; - let st = s.world_state()?; - if st.bodies.len() > MAX_BODIES { - return Err(bad(cmd, format!("at most {MAX_BODIES} bodies"))); - } - if let Some(n) = ignore.iter().find(|n| st.body(n).is_none()) { - return Err(bad(cmd, format!("no body `{n}`"))); - } - let Space { origin, direction, body: space } = space(s, pick, diameter, length, flip, cmd)?; - let space_box = solidcraft_kernel::measure(&space).map_err(|e| bad(cmd, e.to_string()))?.bbox; +/// The solid bodies of `st` other than `ignore` that take volume from the socket's `space`, the +/// largest first, and the bodies that could not be checked, each with why. A body taking no more +/// than a contact's volume does not block. `length` is the space's, `cmd` names the command in +/// its errors. Shared with `inspect.fastener_checks`. +pub(crate) fn blockers( + st: &solidcraft_doc::ModelState, + space: &Space, + length: f64, + ignore: &[String], + cmd: &str, +) -> Result<(Vec, Vec)> { + let (origin, direction) = (space.origin, space.direction); + let space_box = solidcraft_kernel::measure(&space.body).map_err(|e| bad(cmd, e.to_string()))?.bbox; let mut blocked = Vec::new(); let mut unchecked = Vec::new(); for b in &st.bodies { @@ -114,7 +104,7 @@ fn socket_reach(s: &mut Session, p: &Value) -> Result { if b.body.exact_bounds().is_ok_and(|bounds| solidcraft_geom::mesh_distance::box_gap(&bounds, &space_box) > 0.0) { continue; } - let shared = match solidcraft_kernel::boolean(&b.body, &space, solidcraft_kernel::BoolOp::Intersect) { + let shared = match solidcraft_kernel::boolean(&b.body, &space.body, solidcraft_kernel::BoolOp::Intersect) { Ok(Some(shared)) => shared, Ok(None) => continue, Err(e) => { @@ -138,6 +128,33 @@ fn socket_reach(s: &mut Session, p: &Value) -> Result { blocked.push(Blocker { body: b.name.clone(), volume_mm3: m.volume, from_mm: from, bbox: [[lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]] }); } blocked.sort_by(|a, b| b.volume_mm3.total_cmp(&a.volume_mm3)); + Ok((blocked, unchecked)) +} + +fn socket_reach(s: &mut Session, p: &Value) -> Result { + let cmd = "inspect.socket_reach"; + let size = |k: &str| -> Result { + num(p, k) + .filter(|x| *x > 0.0 && *x <= MAX_SIZE) + .ok_or_else(|| bad(cmd, format!("`{k}` must be a length in mm above 0 and at most {MAX_SIZE}"))) + }; + let (diameter, length) = (size("diameter")?, size("length")?); + let flip = match p.get("flip") { + None | Some(Value::Null) => false, + Some(_) => bool_(p, "flip").ok_or_else(|| bad(cmd, "`flip` must be true or false"))?, + }; + let ignore = string_list(cmd, p, "ignore")?; + let pick = p.get("edge").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "`edge` must be a point [x, y, z] on a circular edge"))?; + let st = s.world_state()?; + if st.bodies.len() > MAX_BODIES { + return Err(bad(cmd, format!("at most {MAX_BODIES} bodies"))); + } + if let Some(n) = ignore.iter().find(|n| st.body(n).is_none()) { + return Err(bad(cmd, format!("no body `{n}`"))); + } + let space = space(s, pick, diameter, length, flip, cmd)?; + let (blocked, unchecked) = blockers(&st, &space, length, &ignore, cmd)?; + let (origin, direction) = (space.origin, space.direction); let reply = SocketReach { origin: [origin.x, origin.y, origin.z], direction: [direction.x, direction.y, direction.z], diff --git a/crates/engine/src/control_pending.rs b/crates/engine/src/control_pending.rs index dd8582fef6f..2608311c4a4 100644 --- a/crates/engine/src/control_pending.rs +++ b/crates/engine/src/control_pending.rs @@ -254,4 +254,13 @@ mod tests { } assert_eq!(describe("assistant.send", &json!({"prompt": "secret words"})), "`assistant.send`"); } + + /// A motion study made from a trajectory file only reads the file: a timed-out one changes the + /// design, it never writes a file (#24217). + #[test] + fn a_motion_study_from_a_trajectory_file_changes_the_design() { + let p = json!({"command": "motion.study", "params": {"file": "run.csv", "columns": {"a": "Hinge"}}}); + assert_eq!(effect("engine.execute", &p), Effect::Changes); + assert!(!reads_only("engine.execute", &p)); + } } diff --git a/crates/engine/src/schema/fastener_checks.rs b/crates/engine/src/schema/fastener_checks.rs new file mode 100644 index 00000000000..76077abd1e1 --- /dev/null +++ b/crates/engine/src/schema/fastener_checks.rs @@ -0,0 +1,151 @@ +//! Contract and reply types for `inspect.fastener_checks` in `cmd/fastener_checks.rs` (#24216), +//! and the checks `parts.fastener` can add to its reply. + +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::socket_reach::{Blocker, Unchecked}; +use super::types::StringList; +use crate::params; + +/// Largest minimum edge distance asked for (mm). +pub const MAX_EDGE_DISTANCE: f64 = 10_000.0; + +/// A minimum edge distance, as the handlers read it: `null` is left out, else a length in mm from +/// 0 to [`MAX_EDGE_DISTANCE`]. +pub(super) fn min_edge_distance<'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| *x >= 0.0 && *x <= MAX_EDGE_DISTANCE) + .map(Some) + .ok_or_else(|| D::Error::custom(whole(format!("`min_edge_distance_mm` must be a length in mm from 0 to {MAX_EDGE_DISTANCE}")))), + } +} + +pub(super) fn min_edge_distance_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "Report a violation for a fastener whose hole lies nearer than this to the outside of the body it sits in, in mm (default: no limit, the distance is only reported).", + "type": ["number", "null"], + "minimum": 0, + "maximum": MAX_EDGE_DISTANCE + }) +} + +/// `inspect.fastener_checks`: for each placed standard fastener, the solid wall between its hole +/// and the outside of the body it sits in, and whether a tool can reach it. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FastenerChecksParams { + /// The fasteners to check, each a component or occurrence, by name or id (default: every + /// placed standard part). + #[serde(default)] + pub fasteners: Option, + #[serde(default, deserialize_with = "min_edge_distance")] + #[schemars(schema_with = "min_edge_distance_schema")] + pub min_edge_distance_mm: Option, + /// Also check that a socket or hex key can reach each fastener's head or drive along its axis + /// (default false). + #[serde(default)] + pub check_tool_clearance: Option, +} + +/// `inspect.fastener_checks`'s reply. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FastenerChecks { + /// One entry per placed fastener, in the order of their occurrences. + pub fasteners: Vec, + /// How many are in violation: a hole nearer the outside than `min_edge_distance_mm`, or a + /// tool that is blocked. + pub violations: usize, + /// 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, +} + +/// One placed fastener's checks. +#[derive(Debug, Serialize, JsonSchema)] +pub struct FastenerCheck { + /// The fastener's name: its occurrence's, else its component's. + pub fastener: String, + pub component: u64, + pub occurrence: u64, + /// Where it is seated: the point of its axis on its seating plane (under a head, the bottom of + /// a nut or washer; the top of a countersunk head), in world coordinates. + pub position: [f64; 3], + /// The unit direction of its axis, from the shank's tip toward the head. + pub axis: [f64; 3], + /// The body whose hole it sits in. + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + /// The diameter of the hole's narrowest bore, in mm. + #[serde(skip_serializing_if = "Option::is_none")] + pub hole_diameter_mm: Option, + /// The thinnest solid wall around the hole: the shortest distance from the hole's faces to the + /// host's nearest other face (its outer boundary or another hole), in mm. Not the floor under + /// a blind hole. + #[serde(skip_serializing_if = "Option::is_none")] + pub edge_distance_mm: Option, + /// Where the wall ends. + #[serde(skip_serializing_if = "Option::is_none")] + pub nearest_face: Option, + /// With `min_edge_distance_mm`: whether the wall is thinner than it. + #[serde(skip_serializing_if = "Option::is_none")] + pub violation: Option, + /// Why no edge distance is given. + #[serde(skip_serializing_if = "Option::is_none")] + pub unchecked: Option, + /// With `check_tool_clearance`: whether a tool reaches the fastener. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool: Option, +} + +/// The face of the host the wall ends on. +#[derive(Clone, Debug, Serialize, JsonSchema)] +pub struct NearestFace { + /// The host's name. + pub body: String, + /// The face's index in the host's face order, when it could be told. + #[serde(skip_serializing_if = "Option::is_none")] + pub face: Option, + /// The nearest point on that face. + pub point: [f64; 3], + /// The nearest point on the hole. + pub hole_point: [f64; 3], +} + +/// Whether a tool can reach a fastener's head or drive. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ToolClearance { + /// The tool: `socket` (about a hex head or nut), `hex key` (into a socket in the head) or + /// `none` (a part no tool turns, such as a washer or a pin: `clear` is then left out). + pub tool: String, + /// The tool's space is a cylinder about the fastener's axis this wide, in mm. + pub diameter_mm: f64, + /// And this long, in mm. + pub length_mm: f64, + /// Where the space starts, in world coordinates. + pub origin: [f64; 3], + /// The unit direction it runs: the way the head points. + pub direction: [f64; 3], + /// Whether nothing blocks the tool; left out when it could not be checked. + #[serde(skip_serializing_if = "Option::is_none")] + pub clear: Option, + /// Why, in words. + pub reason: String, + /// The bodies in the tool's space, the largest overlap first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub blocked: Vec, + /// Bodies not checked, with why. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unchecked: Vec, +} + +#[cfg(test)] +#[path = "fastener_checks_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/fastener_checks_tests.rs b/crates/engine/src/schema/fastener_checks_tests.rs new file mode 100644 index 00000000000..c77e43eb924 --- /dev/null +++ b/crates/engine/src/schema/fastener_checks_tests.rs @@ -0,0 +1,71 @@ +use serde_json::{Value, json}; + +use super::{FastenerChecks, FastenerChecksParams}; +use crate::Session; +use crate::schema::parts::InsertedPart; +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}")) +} + +/// A 40 x 30 x 10 plate with two 6.4 mm holes through its top face: a point on each hole's rim. +fn plate(s: &mut Session) -> [[f64; 3]; 2] { + run(s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + run(s, "solid.hole", json!({"position": [10, 15, 10], "diameter": 6.4})); + run(s, "solid.hole", json!({"position": [30, 15, 10], "diameter": 6.4})); + [[13.2, 15.0, 10.0], [33.2, 15.0, 10.0]] +} + +#[test] +fn the_schema_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["check_tool_clearance", "fasteners", "min_edge_distance_mm"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[("inspect.fastener_checks", json!({"fasteners": ["Nope"]}))]); + // A length or a flag that is none is refused with the check off and in strict, by both commands. + for (id, extra) in [ + ("inspect.fastener_checks", json!({"min_edge_distance_mm": -1})), + ("inspect.fastener_checks", json!({"min_edge_distance_mm": "wide"})), + ("inspect.fastener_checks", json!({"check_tool_clearance": "yes"})), + ("parts.fastener", json!({"family": "washer", "size": "M6", "min_edge_distance_mm": -1})), + ("parts.fastener", json!({"family": "washer", "size": "M6", "check_tool_clearance": 1})), + ] { + for (level, name) in [(ParamCheck::Off, "off"), (ParamCheck::Strict, "strict")] { + let mut s = Session { param_check: level, ..Session::default() }; + assert!(s.execute(id, &extra).is_err(), "{id} {extra} with the check {name}"); + } + } +} + +/// The checks, alone and in a fastener insert, reply as their output schemas say, in Warn +/// without warnings for good calls and with them for a misspelt key. +#[test] +fn the_checks_reply_with_their_schemas() { + let (checks, inserted) = (output_schema_for::(), output_schema_for::()); + let matches = |schema: &schemars::Schema, 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() }; + let holes = plate(&mut s); + let r = run(&mut s, "inspect.fastener_checks", json!({})); + matches(&checks, &r, false); + assert_eq!(r["fasteners"], json!([]), "no fastener yet: {r}"); + let r = run( + &mut s, + "parts.fastener", + json!({"family": "hex_bolt", "size": "M6", "length": 16, "at": holes, "min_edge_distance_mm": 8, "check_tool_clearance": true}), + ); + matches(&inserted, &r, false); + assert_eq!(r["checks"].as_array().map(Vec::len), Some(2), "{r}"); + let r = run(&mut s, "inspect.fastener_checks", json!({"min_edge_distance_mm": 8, "check_tool_clearance": true})); + matches(&checks, &r, false); + assert_eq!(r["fasteners"].as_array().map(Vec::len), Some(2), "{r}"); + matches(&checks, &run(&mut s, "inspect.fastener_checks", json!({"min_edge": 8})), true); + matches(&inserted, &run(&mut s, "parts.fastener", json!({"family": "washer", "size": "M6", "min_edge_distance": 8})), true); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index db8968cb01b..bb3da0bfe30 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -96,6 +96,7 @@ pub mod drawing_view; pub mod edit; pub mod end_cap; pub mod face_edits; +pub mod fastener_checks; pub mod fastener_rationalize; pub mod features; pub mod features_more; diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rs index 52ca2963630..b349bceea20 100644 --- a/crates/engine/src/schema/motion.rs +++ b/crates/engine/src/schema/motion.rs @@ -495,6 +495,44 @@ pub struct MotionStudyParams { #[serde(default, deserialize_with = "study_keys", skip_serializing_if = "Option::is_none")] #[schemars(schema_with = "study_keys_schema")] pub keys: Option>, + /// The study's length in seconds (above 0), with `sample_rate_hz`: the timeline then has + /// `round(duration_s * sample_rate_hz)` steps (1 to 100 000), step `k` being at `k / sample_rate_hz` + /// seconds. Not with `steps`, unless `steps` is that number. Left out, the study keeps the + /// length it has. + #[serde(default, deserialize_with = "study_duration", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "above_zero_schema")] + pub duration_s: Option, + /// Steps per second (above 0). Needed by keys given in time (`time_s`) and by `duration_s`; a + /// key's step is its time times this rate. Given a new rate on a study that has one, its keys + /// (unless replaced in the same call) stay at the same seconds. With `file`, the rate the + /// trajectory is resampled to. + #[serde(default, deserialize_with = "study_rate", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "above_zero_schema")] + pub sample_rate_hz: Option, + /// A trajectory file (CSV with a header row, or JSON) to make the study's keys from, replacing + /// them: one key per mapped column, at the times of the file's time column. Not with `keys`, + /// `steps` or `duration_s`. The file is read inside the folders an agent may use, and asks the + /// agent chat first. + #[serde(default)] + pub file: Option, + /// With `file`: `csv` or `json`. Default: from the file's extension. + #[serde(default)] + pub format: Option, + /// With `file`: which column drives which joint, `{"": ""}` (at least + /// one; the joint's first value). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "columns_schema")] + pub columns: Option>, + /// With `file`: the column holding the time in seconds. Default: `time`. + #[serde(default)] + pub time_column: Option, + /// With `file`: each mapped column's unit, `deg` or `rad` for an angle, `mm` or `m` for a + /// distance. Default: degrees and mm. + #[serde(default)] + pub units: Option>, + /// With `file`: subtract each column's first value (a calibration offset). Default: false. + #[serde(default)] + pub zero_offset: Option, /// Step-keyed configuration row switches `[{step, config}]`, replacing any the study has. #[serde(default, deserialize_with = "study_configs", skip_serializing_if = "Option::is_none")] #[schemars(schema_with = "study_configs_schema")] @@ -551,6 +589,67 @@ fn study_steps<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> .ok_or_else(|| D::Error::custom(whole("`steps` must be 1…100000"))) } +/// `duration_s` or `sample_rate_hz`: a number above 0 and below 1e9, with the handler's message for +/// anything else, `null` included. +fn above_zero<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result, D::Error> { + Value::deserialize(d)? + .as_f64() + .filter(|n| n.is_finite() && *n > 0.0 && *n < 1e9) + .map(Some) + .ok_or_else(|| D::Error::custom(whole(format!("`{key}` must be a number above 0")))) +} + +fn study_duration<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + above_zero(d, "duration_s") +} + +fn study_rate<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + above_zero(d, "sample_rate_hz") +} + +fn above_zero_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "number", "exclusiveMinimum": 0, "exclusiveMaximum": 1e9}) +} + +/// `columns`: each file column to a joint, by name (text) or id (a number). +fn columns_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "object", "minProperties": 1, "additionalProperties": {"type": ["number", "string"]}}) +} + +/// Where a key's point is on the timeline: a step, or a time in seconds (`motion.study` turns it +/// into a step with the study's `sample_rate_hz`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PointAt { + Step(f64), + Time(f64), +} + +/// A key's point: `[step, value]`, or `{"step": s, "value": v}`, or `{"time_s": t, "value": v}`. +/// Its place, and its value as given (read further by the caller). The messages are the handler's. +pub(crate) fn study_point(point: &Value) -> Result<(PointAt, &Value), String> { + let number = |x: Option<&Value>| x.and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() < MAX_POINT_MAGNITUDE); + let Value::Object(fields) = point else { + let step = number(point.get(0)); + return match point.get(1).filter(|_| step.is_some()) { + Some(value) => Ok((PointAt::Step(step.unwrap_or_default()), value)), + None => Err("points are [step, value]".into()), + }; + }; + const SHAPE: &str = "a point is [step, value], {\"step\": step, \"value\": value} or {\"time_s\": seconds, \"value\": value}"; + if fields.keys().any(|k| !matches!(k.as_str(), "step" | "time_s" | "value")) { + return Err(SHAPE.into()); + } + let value = fields.get("value").ok_or_else(|| String::from(SHAPE))?; + match (fields.get("step"), fields.get("time_s")) { + (Some(step), None) => number(Some(step)).map(|x| (PointAt::Step(x), value)).ok_or_else(|| "a point's `step` must be a number".into()), + (None, Some(time)) => match number(Some(time)) { + Some(t) if t >= 0.0 => Ok((PointAt::Time(t), value)), + _ => Err("a point's `time_s` must be a number of 0 or more (seconds)".into()), + }, + _ => Err(SHAPE.into()), + } +} + /// Parse `easings` and `curves` segment arrays on one study key, shared with `cmd/motion.rs`. pub(crate) fn parse_study_segments(key: &Value, seg_count: usize) -> Result<(Vec, Vec>), String> { let easings = match key.get("easings") { @@ -590,8 +689,16 @@ pub(crate) fn parse_study_segments(key: &Value, seg_count: usize) -> Result<(Vec if (!easings.is_empty() || !curves.is_empty()) && let Some(points) = key.get("points").and_then(Value::as_array) { - let steps: Vec = points.iter().filter_map(|pt| pt.get(0).and_then(Value::as_f64)).collect(); - if steps.len() == points.len() && steps.windows(2).any(|w| w[1] <= w[0]) { + let coords: Vec<(bool, f64)> = points + .iter() + .filter_map(|pt| { + study_point(pt).ok().map(|(at, _)| match at { + PointAt::Step(s) => (false, s), + PointAt::Time(t) => (true, t), + }) + }) + .collect(); + if coords.len() == points.len() && coords.windows(2).all(|w| w[0].0 == w[1].0) && coords.windows(2).any(|w| w[1].1 <= w[0].1) { return Err("a key with `easings` or `curves` must list `points` in strictly increasing step order".into()); } } @@ -615,9 +722,9 @@ fn study_key_problem(key: &Value) -> Option { return Some("a key needs 1…10000 points".into()); } for point in points { - let step = point.get(0).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() < MAX_POINT_MAGNITUDE); - let Some(value) = point.get(1).filter(|_| step.is_some()) else { - return Some("points are [step, value]".into()); + let value = match study_point(point) { + Ok((_, value)) => value, + Err(problem) => return Some(problem), }; let readable = match value { Value::Number(n) => n.as_f64().is_some_and(|x| x.is_finite() && x.abs() < MAX_POINT_MAGNITUDE), @@ -677,11 +784,27 @@ fn study_keys_schema(_: &mut SchemaGenerator) -> Schema { "minItems": 1, "maxItems": MAX_KEY_POINTS, "items": { - "type": "array", - "minItems": 2, - "prefixItems": [ - number.clone(), - {"anyOf": [number, {"type": "string"}]} + "anyOf": [ + { + "type": "array", + "minItems": 2, + "prefixItems": [ + number.clone(), + {"anyOf": [number.clone(), {"type": "string"}]} + ] + }, + { + "description": "A point in time: `time_s` (seconds, 0 or more; needs the study's `sample_rate_hz`) or `step`, and `value`. A study's points are all by step or all by time.", + "type": "object", + "required": ["value"], + "oneOf": [{"required": ["step"]}, {"required": ["time_s"]}], + "properties": { + "step": number, + "time_s": {"type": "number", "minimum": 0, "exclusiveMaximum": MAX_POINT_MAGNITUDE}, + "value": {"anyOf": [number, {"type": "string"}]} + }, + "additionalProperties": false + } ] } }, @@ -830,6 +953,12 @@ pub struct MotionStudySaved { pub steps: u32, /// How many keys it has. pub keys: usize, + /// The study's length in seconds, when it was given in time. Left out otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_s: Option, + /// Steps per second, when the study was given in time. Left out otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sample_rate_hz: Option, /// One for each key that asks a joint value for more than its limits allow (how many of its /// points do, and the furthest): playing the study holds the value at the limit. Left out /// when there is none. @@ -861,6 +990,12 @@ pub struct MotionStudyInfo { pub name: String, pub steps: u32, pub keys: Vec, + /// The study's length in seconds, when it was given in time. Left out otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_s: Option, + /// Steps per second, when the study was given in time. Left out otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sample_rate_hz: Option, /// Step-keyed configuration row switches. Left out when empty. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub configs: Vec, diff --git a/crates/engine/src/schema/motion_analysis.rs b/crates/engine/src/schema/motion_analysis.rs index af3d7cf2b58..dc4dda33380 100644 --- a/crates/engine/src/schema/motion_analysis.rs +++ b/crates/engine/src/schema/motion_analysis.rs @@ -334,7 +334,7 @@ pub struct MotionPlot { pub samples: usize, /// The study step of each sample. pub step: Vec, - /// With a `duration` only: the time of each sample, in seconds. + /// With a `duration`, or a study that has a `sample_rate_hz`, only: the time of each sample, in seconds. #[serde(skip_serializing_if = "Option::is_none")] pub time: Option>, pub joints: Vec, diff --git a/crates/engine/src/schema/motion_tests.rs b/crates/engine/src/schema/motion_tests.rs index 4bce8d5c80b..7ef4e3eb13f 100644 --- a/crates/engine/src/schema/motion_tests.rs +++ b/crates/engine/src/schema/motion_tests.rs @@ -21,7 +21,25 @@ fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &[]); assert_keys(input_schema_for::(), &["name", "occurrences"]); assert_keys(input_schema_for::(), &["delete", "name", "occurrences", "set", "suppressed"]); - assert_keys(input_schema_for::(), &["configs", "keys", "name", "params", "steps", "study"]); + assert_keys( + input_schema_for::(), + &[ + "columns", + "configs", + "duration_s", + "file", + "format", + "keys", + "name", + "params", + "sample_rate_hz", + "steps", + "study", + "time_column", + "units", + "zero_offset", + ], + ); assert_keys(input_schema_for::(), &[]); assert_keys(input_schema_for::(), &["study"]); assert_keys(input_schema_for::(), &["moves", "name", "scale"]); @@ -52,6 +70,23 @@ fn strict_keeps_todays_errors() { ]); } +/// #24217: the time parameters of `motion.study` fail in strict mode as they do with the check off. +#[test] +fn strict_keeps_todays_errors_for_a_studys_time() { + assert_strict_keeps_todays_errors(&[ + ("motion.study", json!({"sample_rate_hz": 0})), + ("motion.study", json!({"sample_rate_hz": -4})), + ("motion.study", json!({"sample_rate_hz": null})), + ("motion.study", json!({"sample_rate_hz": "fast"})), + ("motion.study", json!({"duration_s": 0})), + ("motion.study", json!({"duration_s": null})), + ("motion.study", json!({"duration_s": "long"})), + ("motion.study", json!({"duration_s": 1})), + ("motion.study", json!({"duration_s": 1, "sample_rate_hz": 10, "steps": 11})), + ("motion.study", json!({"file": "x.csv", "columns": {"a": "Hinge"}, "keys": []})), + ]); +} + /// The contact contracts say what their handlers need: `occurrences` and `set` are required in /// the schemas, though the types leave them to the handlers' messages, and a list names two or /// more occurrences. diff --git a/crates/engine/src/schema/parts.rs b/crates/engine/src/schema/parts.rs index 1ccee4c6bc8..4d629abbace 100644 --- a/crates/engine/src/schema/parts.rs +++ b/crates/engine/src/schema/parts.rs @@ -55,9 +55,22 @@ pub struct PartsInsertParams { /// out of the face; with `point`, its +Z against `direction` (default false). #[serde(default)] pub flip: Option, - /// Physical material for the generated solid (default: "Steel"). + /// Physical material for the generated solid (default: "Steel"; "Stainless Steel" with a + /// stainless `property_class`). #[serde(default)] pub material: Option, + /// The coating, such as "zinc", "black oxide" or "passivated": at most 200 characters, kept as + /// the component's `finish` (the bill of materials' finish). + #[serde(default)] + pub finish: Option, + /// Who sells it: at most 200 characters, kept as the component's `supplier` property. + #[serde(default)] + pub supplier: Option, + /// The supplier's part number: at most 200 characters, kept as the component's + /// `catalog_part_number` property (dropped, with a warning, when `parts.resize` changes the + /// part's size or length). + #[serde(default)] + pub catalog_part_number: Option, /// For a part with a metric thread: `cosmetic` (default: recorded on the face, the body /// unchanged) or `modeled` (cut into the body over the standard's thread length from the tip, /// the start chamfered; slower, and refused past 80 turns). @@ -68,8 +81,11 @@ pub struct PartsInsertParams { #[serde(default)] #[schemars(schema_with = "hardness_class_schema")] pub hardness_class: Option, - /// For a screw or bolt: its property class (ISO 898-1), saved as a part property. A washer - /// of 200 HV under a screw of 10.9 or 12.9 makes the insert warn. + /// The strength class, saved as a part property and added to the part number and description. + /// Metric screws and bolts: `4.6`, `4.8`, `5.6`, `5.8`, `6.8`, `8.8`, `9.8`, `10.9`, `12.9` + /// (ISO 898-1); metric nuts: `5`, `6`, `8`, `10`, `12` (ISO 898-2); both: the stainless + /// `A2-70`, `A4-80` (ISO 3506). A washer of 200 HV under a screw of 10.9 or 12.9 makes the + /// insert warn. #[serde(default)] #[schemars(schema_with = "property_class_schema")] pub property_class: Option, @@ -100,6 +116,14 @@ pub struct PartsInsertParams { /// thread pitches of protrusion (default false). #[serde(default)] pub through_bolt: Option, + #[serde(default, deserialize_with = "super::fastener_checks::min_edge_distance")] + #[schemars(schema_with = "super::fastener_checks::min_edge_distance_schema")] + pub min_edge_distance_mm: Option, + /// Also check that a socket or hex key can reach each placed fastener's head or drive + /// (default false: not checked). The reply gets `checks`, and `warnings` for what is blocked; + /// the part is placed either way. + #[serde(default)] + pub check_tool_clearance: Option, } fn hardness_class_schema(_: &mut SchemaGenerator) -> Schema { @@ -112,9 +136,9 @@ fn hardness_class_schema(_: &mut SchemaGenerator) -> Schema { fn property_class_schema(_: &mut SchemaGenerator) -> Schema { json_schema!({ - "description": "For a screw or bolt: its property class (ISO 898-1), saved as a part property. A washer of 200 HV under a 10.9 or 12.9 screw makes the insert warn.", + "description": "The strength class. Metric screws and bolts: `4.6`, `4.8`, `5.6`, `5.8`, `6.8`, `8.8`, `9.8`, `10.9`, `12.9` (ISO 898-1); metric nuts: `5`, `6`, `8`, `10`, `12` (ISO 898-2); both: the stainless `A2-70`, `A4-80` (ISO 3506). Saved as a part property and added to the part number and description. A washer of 200 HV under a 10.9 or 12.9 screw makes the insert warn.", "type": ["string", "null"], - "enum": ["4.6", "4.8", "5.6", "5.8", "6.8", "8.8", "9.8", "10.9", "12.9", null] + "enum": ["4.6", "4.8", "5.6", "5.8", "6.8", "8.8", "9.8", "10.9", "12.9", "5", "6", "8", "10", "12", "A2-70", "A4-80", null] }) } @@ -365,20 +389,25 @@ pub struct InsertedPart { /// The washer's hardness class (`200 HV`, `300 HV` or `380 HV`), when one was given. #[serde(skip_serializing_if = "Option::is_none")] pub hardness_class: Option, - /// The screw's property class, when one was given. + /// The part's property class, when one was given. #[serde(skip_serializing_if = "Option::is_none")] pub property_class: Option, - /// Non-blocking notes on what was placed: a washer under 300 HV with a screw of property - /// class 10.9 or 12.9. Left out when there are none. /// With `auto_length`: the length it chose, in mm (left out when none was). #[serde(default, skip_serializing_if = "Option::is_none")] pub length_mm: Option, - /// With `auto_length`: what kept it from a length, or from the engagement asked for. + /// Non-blocking notes on what was placed: what `auto_length` did, a washer under 300 HV with a + /// screw of property class 10.9 or 12.9, and, with `min_edge_distance_mm` or + /// `check_tool_clearance`, a line for each hole nearer the outside than asked, each tool that + /// is blocked and each check that could not be made. Left out when there are none. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub warnings: Vec, /// 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, + /// With `min_edge_distance_mm` or `check_tool_clearance`: what `inspect.fastener_checks` + /// says of each part just placed, in placement order. + #[serde(skip_serializing_if = "Option::is_none")] + pub checks: Option>, } /// What `parts.resize` returns. diff --git a/crates/engine/src/schema/parts_tests.rs b/crates/engine/src/schema/parts_tests.rs index 9ca4231c907..a72cbe93d03 100644 --- a/crates/engine/src/schema/parts_tests.rs +++ b/crates/engine/src/schema/parts_tests.rs @@ -27,17 +27,22 @@ fn schemas_and_the_key_check_agree() { &[ "at", "auto_length", + "catalog_part_number", + "check_tool_clearance", "direction", "family", + "finish", "flip", "hardness_class", "length", "material", + "min_edge_distance_mm", "min_engagement_d", "name", "point", "property_class", "size", + "supplier", "thread", "through_bolt", "washer_thickness_mm", diff --git a/crates/kernel/src/hole_ligament.rs b/crates/kernel/src/hole_ligament.rs new file mode 100644 index 00000000000..e700ce81218 --- /dev/null +++ b/crates/kernel/src/hole_ligament.rs @@ -0,0 +1,244 @@ +//! The solid wall around a round hole (#24216): how far a hole's walls lie from the rest of the +//! body's boundary, on the exact B-rep. A fastener's edge distance is this wall. +//! +//! The geometry is solidcore's ([`solidcore_ops::hole_ligament`]): it finds the hole among the +//! body's cylinders and cones about the axis, measures from it to every other face but the +//! planes square to the axis, and drops the faces with open air behind them. This module reads +//! the body for it (`Reader`: each face's cylinder or cone from its rims, a plane's normal, the +//! exact distances between faces, a face's outward normal, whether a point is outside) and keeps +//! the result in the kernel's own types. A hole entering an inclined face is not found at all: a +//! piece of the hole needs two circular rims square to the axis ([`cylinder_between_rims`]), so +//! the result is `None`. A counterbore entering an inclined face is no piece of the hole either, +//! so only the bore is read. +//! +//! The line helpers ([`line_coaxial`], [`line_behind`]) are the checks a fastener's axis asks of +//! the parts about it. + +use solidcore_ops::hole_ligament as ops; +use solidcore_record::Vec3; + +use crate::distance::{Members, faces_closest, point_closest}; +use crate::surface_kind::{FaceSurface, face_surface}; +use crate::topo::{cone_face, cylinder_between_rims}; +use crate::{Body, KernelError, PointClass, Result}; + +/// A hole in a body, and the wall around it. +#[derive(Clone, Debug, PartialEq)] +pub struct HoleLigament { + /// The hole's faces (indices in the body's face order): its cylinders and cones. + pub faces: Vec, + /// The radius of the hole's narrowest cylinder (0 for a hole with only cones). + pub radius: f64, + /// How far along the axis the hole lies from `origin` (0 when `origin` is within it). + pub gap: f64, + /// The nearest other face with material behind it; `None` when the body has no face to measure + /// to, or every face looked at had open air behind it (`dropped` says how many). + pub nearest: Option, + /// How many faces were set aside for having no material between them and the hole. + pub dropped: usize, +} + +/// The shortest distance from a hole's faces to the body's other faces. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ligament { + /// The wall's thickness, in mm. + pub distance: f64, + /// On the hole's faces. + pub from: Vec3, + /// On the other face. + pub to: Vec3, + /// The other face, when it could be named (its index in the body's face order). + pub face: Option, +} + +impl From for Ligament { + fn from(l: ops::Ligament) -> Ligament { + Ligament { distance: l.distance, from: Vec3::from(l.from), to: Vec3::from(l.to), face: l.face } + } +} + +impl From for HoleLigament { + fn from(h: ops::HoleLigament) -> HoleLigament { + HoleLigament { faces: h.faces, radius: h.radius, gap: h.gap, nearest: h.nearest.map(Ligament::from), dropped: h.dropped } + } +} + +/// An exact B-rep body, read for the hole query. +struct Reader<'a>(&'a Body); + +impl ops::HoleBody for Reader<'_> { + type Error = KernelError; + + fn face_count(&self) -> usize { + self.0.face_count() + } + + /// The face's cylinder, else its cone. + fn piece(&self, face: usize) -> Option { + let body = self.0; + let (c, cylinder) = cylinder_between_rims(body, face).map(|c| (c, true)).or_else(|| cone_face(body, face).map(|(c, _)| (c, false)))?; + Some(ops::Piece { + axis_point: c.axis_point.into(), + axis: c.axis.vec().into(), + radius: c.radius, + start: c.start, + end: c.end, + internal: c.internal, + cylinder, + }) + } + + fn plane_normal(&self, face: usize) -> Option<[f64; 3]> { + match face_surface(self.0, face) { + Some(FaceSurface::Plane { normal, .. }) => Some(normal.vec().into()), + _ => None, + } + } + + fn closest(&self, hole: &[usize], others: &[usize]) -> Result> { + let near = faces_closest(self.0, hole, self.0, others)?; + Ok(near.map(|d| ops::Near { distance: d.distance, from: d.from.into(), to: d.to.into() })) + } + + fn distance_to_face(&self, at: [f64; 3], face: usize) -> Option { + point_closest(Vec3::from(at), self.0, Members::Faces(&[face])).ok().flatten().map(|hit| hit.distance) + } + + /// A plane's own normal, else the kernel's. + fn outward(&self, face: usize, at: [f64; 3]) -> Option<[f64; 3]> { + match face_surface(self.0, face) { + Some(FaceSurface::Plane { normal, .. }) => Some(normal.vec().into()), + _ => self.0.face_normal_at(face, Vec3::from(at)).ok().flatten().map(Into::into), + } + } + + fn is_outside(&self, at: [f64; 3]) -> bool { + self.0.classify_point(Vec3::from(at)).map_or(true, |class| matches!(class, PointClass::Outside)) + } +} + +/// The hole of `body` about the line through `origin` along the unit `axis` whose nearest end lies +/// within `reach` mm of `origin` along the axis, and the wall around it. Only cylinders and cones +/// up to `max_radius` count as the hole (a larger bore on the same axis, such as the inside of a +/// cup the fastener goes through the floor of, is not the fastener's hole and is measured to like +/// any other face). `None` for a mesh or surface body and when no such hole is about that line. +/// +/// # Errors +/// +/// [`crate::KernelError::Failed`] for a B-rep body the kernel can't take and when the kernel can't +/// give the distance. +pub fn hole_ligament(body: &Body, origin: Vec3, axis: Vec3, reach: f64, max_radius: f64) -> Result> { + if body.is_mesh() || body.is_surface() { + return Ok(None); + } + let found = ops::hole_ligament(&Reader(body), body.size(), origin.into(), axis.into(), reach, max_radius)?; + Ok(found.map(HoleLigament::from)) +} + +/// Whether a part seated at `point`, its own axis `direction`, is coaxial with the line through +/// `origin` along the unit `axis`: `direction` is `axis` either way round within `axis_tol` (unit +/// vectors) and `point` is within `line_tol` mm of the line. +pub fn line_coaxial(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], direction: [f64; 3], axis_tol: f64, line_tol: f64) -> bool { + ops::coaxial(origin, axis, point, direction, axis_tol, line_tol) +} + +/// Whether `point` is at or behind `origin` along `axis`, to within `tol` mm: not in front of it, +/// the way a tool along `axis` goes. +pub fn line_behind(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], tol: f64) -> bool { + ops::behind(origin, axis, point, tol) +} + +#[cfg(test)] +mod tests { + use solidcore_record::Vec3; + + use super::hole_ligament; + use crate::build::box_solid; + use crate::{Body, BoolOp}; + + /// A 60 x 30 x 10 plate, x 0 to 60, y 0 to 30, z 0 to 10. + fn plate() -> Body { + box_solid(Vec3::ZERO, Vec3::new(60.0, 30.0, 10.0)).unwrap() + } + + /// `body` with a cylinder about the vertical line through (`x`, 15), from `z` up, cut out of it. + fn cut(body: &Body, x: f64, z: f64, radius: f64, height: f64) -> Body { + let tool = crate::cylinder(Vec3::new(x, 15.0, z), Vec3::Z, radius, height).unwrap(); + crate::boolean(body, &tool, BoolOp::Cut).unwrap().unwrap() + } + + fn wall(body: &Body, x: f64) -> f64 { + let hole = hole_ligament(body, Vec3::new(x, 15.0, 10.0), Vec3::Z, 2.0, 100.0).unwrap().expect("a hole"); + hole.nearest.expect("a wall").distance + } + + /// A through hole 8 mm from the end of the plate: 8 - 3.2 to the end; the top and bottom do not count. + #[test] + fn a_through_hole_has_the_wall_to_the_end() { + let body = cut(&plate(), 8.0, -1.0, 3.2, 12.0); + let hole = hole_ligament(&body, Vec3::new(8.0, 15.0, 10.0), Vec3::Z, 2.0, 100.0).unwrap().expect("a hole"); + assert!((hole.radius - 3.2).abs() < 1e-9 && hole.gap.abs() < 1e-9, "{hole:?}"); + let near = hole.nearest.expect("a wall"); + assert!((near.distance - 4.8).abs() < 1e-6 && near.face.is_some(), "{near:?}"); + // No hole about another line. + assert!(hole_ligament(&body, Vec3::new(30.0, 15.0, 10.0), Vec3::Z, 2.0, 100.0).unwrap().is_none()); + } + + /// A counterbore's wider wall is the nearer one; its floor is not a wall. + #[test] + fn a_counterbore_is_measured_from_its_wider_wall() { + let body = cut(&cut(&plate(), 8.0, -1.0, 3.2, 12.0), 8.0, 4.0, 5.5, 7.0); + assert!((wall(&body, 8.0) - 2.5).abs() < 1e-6); + } + + /// The floor under a blind hole is not its wall. + #[test] + fn a_blind_hole_with_a_thin_floor_has_the_wall_to_the_side() { + let body = cut(&plate(), 40.0, 2.0, 3.2, 9.0); + assert!((wall(&body, 40.0) - 11.8).abs() < 1e-6); + } + + /// A hole that breaks out of the end of the plate has no wall. + #[test] + fn a_hole_that_breaks_out_of_a_side_has_no_wall() { + let body = cut(&plate(), 2.0, -1.0, 3.2, 12.0); + assert!(wall(&body, 2.0) < 1e-6); + } + + /// A riser joined to the plate 0.8 mm from the hole's rim is no wall: nothing but air lies + /// between them. The plate's hole is at x = 40 (rim at 43.2), the riser stands x 44 to 48, + /// z 10 to 20, across the plate's width. Its near face, 0.8 away, looks at the hole and is + /// dropped. Its far face, 4.8 away, meets the plate top in a concave foot at (48, 15, 10), + /// where the plate runs on to x = 60: the point just past it is on the boundary, not outside, + /// so it is dropped too. The wall is to the sides, 15 - 3.2 = 11.8 (the end is 16.8 away). + #[test] + fn a_wall_rising_beside_the_hole_is_not_a_thin_wall() { + let body = cut(&plate(), 40.0, -1.0, 3.2, 12.0); + let riser = box_solid(Vec3::new(44.0, 0.0, 10.0), Vec3::new(48.0, 30.0, 20.0)).unwrap(); + let body = crate::boolean(&body, &riser, BoolOp::Union).unwrap().unwrap(); + let hole = hole_ligament(&body, Vec3::new(40.0, 15.0, 10.0), Vec3::Z, 2.0, 100.0).unwrap().expect("a hole"); + let near = hole.nearest.expect("a wall"); + assert!((near.distance - 11.8).abs() < 1e-6, "{near:?}"); + } + + /// A bore wider than `max_radius` on the same axis is not the hole. + #[test] + fn a_wider_bore_on_the_axis_is_not_the_hole() { + let body = cut(&cut(&plate(), 30.0, 4.0, 12.0, 7.0), 30.0, -1.0, 3.2, 12.0); + let narrow = hole_ligament(&body, Vec3::new(30.0, 15.0, 4.0), Vec3::Z, 2.0, 5.0).unwrap().expect("a hole"); + assert!((narrow.radius - 3.2).abs() < 1e-9, "{narrow:?}"); + let wide = hole_ligament(&body, Vec3::new(30.0, 15.0, 4.0), Vec3::Z, 2.0, 100.0).unwrap().expect("a hole"); + assert!(wide.faces.len() > narrow.faces.len(), "{wide:?} {narrow:?}"); + } + + /// The line checks are solidcore's: a part is coaxial on either way round of the axis and on + /// the line, and behind a seat when it is not in front of it. + #[test] + fn the_line_checks_are_the_kernels() { + let (origin, z) = ([0.0, 0.0, 10.0], [0.0, 0.0, 1.0]); + assert!(super::line_coaxial(origin, z, [0.0, 0.0, 4.0], [0.0, 0.0, -1.0], 1e-6, 1e-3)); + assert!(!super::line_coaxial(origin, z, [0.5, 0.0, 4.0], z, 1e-6, 1e-3)); + assert!(super::line_behind(origin, z, [3.0, 0.0, 4.0], 1e-3)); + assert!(!super::line_behind(origin, z, [0.0, 0.0, 11.0], 1e-3)); + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 8c9bae5b5c6..4ed0af2cea6 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -62,6 +62,7 @@ mod held; mod helix; pub mod history; pub mod hlr; +mod hole_ligament; mod iges_in; mod iges_out; mod intersection; @@ -395,6 +396,11 @@ pub use held::record_reads; pub use helix::MAX_HELIX_TURNS; pub use helix::require_unfolded_screw_section; pub use helix::sweep_helix_mesh; +pub use hole_ligament::HoleLigament; +pub use hole_ligament::Ligament; +pub use hole_ligament::hole_ligament; +pub use hole_ligament::line_behind; +pub use hole_ligament::line_coaxial; pub use iges_in::MAX_IGES_BYTES; pub use iges_in::iges_import; pub use iges_in::iges_native_system; diff --git a/crates/ui-egui/src/agent_chat/gate.rs b/crates/ui-egui/src/agent_chat/gate.rs index 35d4575ccb5..0241a3f1ade 100644 --- a/crates/ui-egui/src/agent_chat/gate.rs +++ b/crates/ui-egui/src/agent_chat/gate.rs @@ -1240,6 +1240,19 @@ mod tests { assert_eq!(request("ui.render", &json!({"width": 400}), 0), Verdict::Run { change: false }); } + /// A motion study made from a trajectory file reads that file, so the agent chat asks first and + /// names it; the same study made from keys runs as a change (#24217). + #[test] + fn a_motion_study_read_from_a_file_asks_first() { + let from_file = json!({"file": "C:/runs/arm.csv", "columns": {"a": "Hinge"}}); + assert!(matches!(exec("motion.study", from_file), Verdict::Ask(a) if a.contains("motion.study") && a.contains("arm.csv"))); + // A bare name asks too: `file` is a file by its name alone. + assert!(matches!(exec("motion.study", json!({"file": "arm", "columns": {"a": "Hinge"}})), Verdict::Ask(_))); + let batch = json!({"commands": [{"command": "motion.study", "params": {"file": "arm.json", "columns": {"a": "Hinge"}}}]}); + assert!(matches!(request("engine.batch", &batch, 0), Verdict::Ask(a) if a.contains("arm.json"))); + assert_eq!(exec("motion.study", json!({"steps": 10, "keys": []})), Verdict::Run { change: true }); + } + /// A real `assembly.propagate` saves designs: it asks whatever the paths look like (a relative /// `root` included), in a batch and spelled in another case. #[test] diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index 866307d223c..7e294c0a6a0 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -624,6 +624,8 @@ fn study_model_preview( name: String::new(), steps: 0, keys: Vec::new(), + duration_s: None, + sample_rate_hz: None, configs: sorted_configs, params: sorted_params, }; diff --git a/solidcore/crates/solidcore-kernel/src/eval.rs b/solidcore/crates/solidcore-kernel/src/eval.rs index 693bfe20523..f6b705022e0 100644 --- a/solidcore/crates/solidcore-kernel/src/eval.rs +++ b/solidcore/crates/solidcore-kernel/src/eval.rs @@ -27,6 +27,7 @@ pub mod form_guide_curves; pub mod form_transform; pub mod forms_view_queries; pub mod geometry; +pub mod hole_ligament; pub mod label; pub mod normal_section; pub mod outline; diff --git a/solidcore/crates/solidcore-kernel/src/eval/hole_ligament.rs b/solidcore/crates/solidcore-kernel/src/eval/hole_ligament.rs new file mode 100644 index 00000000000..dc42d3899d2 --- /dev/null +++ b/solidcore/crates/solidcore-kernel/src/eval/hole_ligament.rs @@ -0,0 +1,406 @@ +//! The solid wall around a round hole, and the line helpers a fastener check asks of a hole's +//! axis: how far a hole's walls lie from the rest of the body's boundary (a fastener's edge +//! distance), and whether a part is coaxial with, or seated behind, a fastener's axis. +//! +//! The body gives this module what only its own faces can tell ([`HoleBody`]: each face's +//! cylinder or cone about an axis, a plane's normal, the nearest points between sets of faces, +//! a point's distance to a face, a face's outward normal, whether a point lies outside the +//! body); every decision and every number worked out from them is here. +//! +//! The hole is the internal cylinders and cones about one axis that run on from one another (a +//! bore, its countersink or counterbore, a drill point). The wall is measured from them to every +//! other face of the body except the planes square to the axis (the faces a through hole starts +//! and ends on, a counterbore's floor, the floor under a blind hole): it is the wall around the +//! hole, not the floor under a blind hole. The nearest other face is the outer boundary or +//! another hole. Every other face is measured, so a hole that breaks out of a side, or into a +//! cross hole, has a wall of 0, as has a hole entering a curved face about its own axis, met +//! along a circle (a dome, an external cone, a torus on the axis). +//! +//! A nearest pair is a wall only with material between its ends. The face's outward normal at +//! the far point must face away from the hole, and the point a little past it (1e-3 mm, at least +//! 1e-4 of the body's size, on from the hole) must be outside the body. A wall rising beside the +//! hole, a rib, a boss, the concave foot where one meets the plate (the plate runs on under it: +//! that point is on the boundary) cross open air, so that face is dropped and the wall measured +//! again, unless the distance is 0. A pair that cannot be told stands. +//! +//! Tolerances: a hole's axis is the fastener's when its direction agrees within 1e-6 (unit +//! vectors, about 1e-6 rad) and it lies within 1e-5 of the body's size (at least 1e-5 mm) of the +//! fastener's line; pieces of a hole join when they meet within 1e-4 of the body's size. +//! +//! Not upstream: SolidCraft's fastener checks (tangency-labs/solidcraft#24216, MIT OR +//! Apache-2.0), moved here from the application's kernel adapter. +//! +//! Deviations: none (no upstream counterpart). No recursion. + +use std::collections::BTreeSet; + +use super::vec::{v3, VecExt}; +use crate::math::Vec3; + +/// Most faces looked through to name the face the wall ends on. +pub const MAX_NAMED: usize = 2000; + +/// Most faces dropped, one by one, for facing the hole instead of away from it. +pub const MAX_ROUNDS: usize = 64; + +/// A hole's axis is a fastener's when the unit directions agree within this. +const AXIS_AGREES: f64 = 1e-6; +/// A hole's piece lies about the fastener's line within this fraction of the body's size. +const OFF_AXIS: f64 = 1e-5; +/// Pieces of a hole join when they meet within this fraction of the body's size. +const JOIN: f64 = 1e-4; +/// A plane is square to the axis within this (a STEP plane is a little imprecise). +const SQUARE: f64 = 1e-4; +/// The face the wall ends on is named when the far point is this near it, as a fraction of the +/// body's size. +const ON_FACE: f64 = 1e-7; +/// A wall nearer than this fraction of the body's size is a touch, never dropped. +const TOUCH: f64 = 1e-6; +/// How far past the far point the open-air probe goes, at least, in mm. +const PAST_MIN: f64 = 1e-3; +/// How far past the far point the open-air probe goes, at least, as a fraction of the body's size. +const PAST_FRACTION: f64 = 1e-4; + +// ---- the line helpers ---------------------------------------------------------------------- + +/// Whether `direction` is `axis` or its opposite, each a unit vector, within `tol`. +#[must_use] +pub fn parallel(direction: [f64; 3], axis: [f64; 3], tol: f64) -> bool { + let (direction, axis) = (v3(direction), v3(axis)); + (direction - axis).len() < tol || (direction + axis).len() < tol +} + +/// How far `point` stands from `origin` along `axis`: the dot product of `point - origin` with +/// `axis`, which is the distance for a unit `axis`; negative behind `origin`. +#[must_use] +pub fn distance_along(origin: [f64; 3], axis: [f64; 3], point: [f64; 3]) -> f64 { + v3(point).distance_along(v3(origin), v3(axis)) +} + +/// Whether `point` lies within `tol` mm of the line through `origin` along the unit `axis`. +#[must_use] +pub fn on_line(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], tol: f64) -> bool { + let (origin, axis, point) = (v3(origin), v3(axis), v3(point)); + let along = point.distance_along(origin, axis); + (point - origin - axis * along).len() < tol +} + +/// Whether a part seated at `point`, its own axis `direction`, is coaxial with the line through +/// `origin` along `axis`: `direction` is `axis` either way round within `axis_tol` +/// ([`parallel`]) and `point` is within `line_tol` mm of the line ([`on_line`]). +#[must_use] +pub fn coaxial( + origin: [f64; 3], + axis: [f64; 3], + point: [f64; 3], + direction: [f64; 3], + axis_tol: f64, + line_tol: f64, +) -> bool { + parallel(direction, axis, axis_tol) && on_line(origin, axis, point, line_tol) +} + +/// Whether `point` is at or behind `origin` along `axis`, to within `tol` mm: not in front of +/// it, the way the tool along `axis` goes. +#[must_use] +pub fn behind(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], tol: f64) -> bool { + distance_along(origin, axis, point) <= tol +} + +// ---- the body the wall is measured in ------------------------------------------------------- + +/// One face of a body read as a piece of a round hole: a cylinder, or a cone, about an axis. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Piece { + /// A point on the face's axis. + pub axis_point: [f64; 3], + /// The face's unit axis. + pub axis: [f64; 3], + /// The radius (a cone's larger end). + pub radius: f64, + /// Where the face starts along its axis, from `axis_point`. + pub start: f64, + /// Where the face ends along its axis, from `axis_point`. + pub end: f64, + /// Whether the material lies outside the face (it is a hole, not a post). + pub internal: bool, + /// A cylinder (a cone is `false`). + pub cylinder: bool, +} + +/// The closest points between the hole's faces and the body's other faces. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Near { + /// The distance, in mm. + pub distance: f64, + /// On the hole's faces. + pub from: [f64; 3], + /// On the other faces. + pub to: [f64; 3], +} + +/// What a body tells of itself for [`hole_ligament`]: the faces' shapes and the exact distances. +/// Faces are indices in the body's face order. +pub trait HoleBody { + /// Why a measurement failed. + type Error; + + /// How many faces the body has. + fn face_count(&self) -> usize; + + /// The face as a cylinder or cone about an axis, bounded by circular rims square to it; + /// `None` for any other face. + fn piece(&self, face: usize) -> Option; + + /// The face's unit normal when it lies on a plane. + fn plane_normal(&self, face: usize) -> Option<[f64; 3]>; + + /// The closest points between the `hole` faces and the `others`, on the exact faces; `None` + /// when there are none to give. + /// + /// # Errors + /// When the body cannot give the distance. + fn closest(&self, hole: &[usize], others: &[usize]) -> Result, Self::Error>; + + /// How far `at` is from the face; `None` when that cannot be told. + fn distance_to_face(&self, at: [f64; 3], face: usize) -> Option; + + /// The face's outward normal at `at`, a point of it; `None` when that cannot be told. + fn outward(&self, face: usize, at: [f64; 3]) -> Option<[f64; 3]>; + + /// Whether `at` is outside the body; `true` when that cannot be told. + fn is_outside(&self, at: [f64; 3]) -> bool; +} + +/// A hole in a body, and the wall around it. +#[derive(Clone, Debug, PartialEq)] +pub struct HoleLigament { + /// The hole's faces (indices in the body's face order): its cylinders and cones. + pub faces: Vec, + /// The radius of the hole's narrowest cylinder (0 for a hole with only cones). + pub radius: f64, + /// How far along the axis the hole lies from `origin` (0 when `origin` is within it). + pub gap: f64, + /// The nearest other face with material behind it; `None` when the body has no face to + /// measure to, or every face looked at had open air behind it (`dropped` says how many). + pub nearest: Option, + /// How many faces were set aside for having no material between them and the hole. + pub dropped: usize, +} + +/// The shortest distance from a hole's faces to the body's other faces. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ligament { + /// The wall's thickness, in mm. + pub distance: f64, + /// On the hole's faces. + pub from: [f64; 3], + /// On the other face. + pub to: [f64; 3], + /// The other face, when it could be named (its index in the body's face order). + pub face: Option, +} + +/// Faces that meet along the axis: one hole. +struct Run { + /// Where it starts along the axis. + lo: f64, + /// Where it ends along the axis. + hi: f64, + /// Its faces. + faces: Vec, + /// Its narrowest cylinder's radius (infinite with only cones). + radius: f64, +} + +/// One face about the axis: its face, its stretch along the axis, its radius. +struct Stretch { + face: usize, + lo: f64, + hi: f64, + radius: f64, +} + +/// The hole of a body of `size` (the diagonal of its bounding box, in mm) about the line +/// through `origin` along the unit `axis` whose nearest end lies within `reach` mm of `origin` +/// along the axis, and the wall around it. Only cylinders and cones up to `max_radius` count as +/// the hole (a larger bore on the same axis, such as the inside of a cup the fastener goes +/// through the floor of, is not the fastener's hole and is measured to like any other face). +/// `None` when no such hole is about that line. +/// +/// A hole entering an inclined face is not found at all: a piece of the hole needs two circular +/// rims square to the axis, so the body's [`HoleBody::piece`] gives none. A counterbore entering +/// an inclined face is no piece of the hole either, so only the bore is read. +/// +/// # Errors +/// What the body's [`HoleBody::closest`] gives. +pub fn hole_ligament( + body: &B, + size: f64, + origin: [f64; 3], + axis: [f64; 3], + reach: f64, + max_radius: f64, +) -> Result, B::Error> { + let scale = size.max(1.0); + let (origin, axis) = (v3(origin), v3(axis)); + let along = |p: Vec3| p.distance_along(origin, axis); + let off_axis = |p: Vec3| (p - origin - axis * along(p)).len(); + // +1 when `v` runs along the axis, -1 against it, none when it is not about the axis. + let sense = |v: Vec3| -> Option { + if (v - axis).len() < AXIS_AGREES { + Some(1.0) + } else if (v + axis).len() < AXIS_AGREES { + Some(-1.0) + } else { + None + } + }; + // Each internal cylinder or cone about the axis. + let mut pieces: Vec = Vec::new(); + for face in 0..body.face_count() { + let Some(c) = body.piece(face) else { continue }; + let axis_point = v3(c.axis_point); + if !c.internal || c.radius > max_radius || off_axis(axis_point) > OFF_AXIS * scale { + continue; + } + let Some(sign) = sense(v3(c.axis)) else { + continue; + }; + let base = along(axis_point); + let (a, b) = (base + sign * c.start, base + sign * c.end); + let radius = if c.cylinder { c.radius } else { f64::INFINITY }; + pieces.push(Stretch { + face, + lo: a.min(b), + hi: a.max(b), + radius, + }); + } + // Pieces that meet along the axis are one hole. + pieces.sort_by(|x, y| x.lo.total_cmp(&y.lo)); + let join = JOIN * scale; + let mut holes: Vec = Vec::new(); + for Stretch { + face, + lo, + hi, + radius, + } in pieces + { + let meets = holes.last().is_some_and(|hole| lo <= hole.hi + join); + match holes.last_mut() { + Some(hole) if meets => { + hole.hi = hole.hi.max(hi); + hole.faces.push(face); + hole.radius = hole.radius.min(radius); + } + _ => holes.push(Run { + lo, + hi, + faces: vec![face], + radius, + }), + } + } + let gap_to = |lo: f64, hi: f64| { + if lo > 0.0 { + lo + } else if hi < 0.0 { + -hi + } else { + 0.0 + } + }; + let Some((gap, Run { faces, radius, .. })) = holes + .into_iter() + .map(|hole| (gap_to(hole.lo, hole.hi), hole)) + .filter(|(gap, _)| *gap <= reach) + .min_by(|x, y| x.0.total_cmp(&y.0)) + else { + return Ok(None); + }; + let radius = if radius.is_finite() { radius } else { 0.0 }; + // The wall is measured to every face but the hole's own and the planes square to the axis. + let skip: BTreeSet = faces.iter().copied().collect(); + let square = |face: usize| { + body.plane_normal(face).is_some_and(|normal| { + let normal = v3(normal); + (normal - axis).len() < SQUARE || (normal + axis).len() < SQUARE + }) + }; + let mut others: Vec = (0..body.face_count()) + .filter(|face| !skip.contains(face) && !square(*face)) + .collect(); + let none = |dropped: usize| HoleLigament { + faces: faces.clone(), + radius, + gap, + nearest: None, + dropped, + }; + let mut dropped = 0; + for _ in 0..MAX_ROUNDS { + if others.is_empty() { + return Ok(Some(none(dropped))); + } + let Some(near) = body.closest(&faces, &others)? else { + return Ok(Some(none(dropped))); + }; + // The face the wall ends on: the one the far point lies on. + let mut face = None; + let mut best = f64::INFINITY; + for &other in others.iter().take(MAX_NAMED) { + let Some(distance) = body.distance_to_face(near.to, other) else { + continue; + }; + if distance < best { + best = distance; + face = Some(other); + } + if best <= ON_FACE * scale { + break; + } + } + // Material lies between the hole and the far point when the face looks away from the hole + // and the point just past it is outside the body: otherwise (a wall rising beside the + // hole, or the concave foot of one) the pair crosses open air and the face is dropped. A + // touch (distance 0), and a face or point that cannot tell, stand. + let (from, to) = (v3(near.from), v3(near.to)); + let across = face + .and_then(|f| body.outward(f, near.to)) + .map(|normal| to.distance_along(from, v3(normal))); + let faces_away = across.is_none_or(|d| d > 0.0); + let past_is_outside = || { + let step = (to - from) * (1.0 / near.distance); + let past = to + step * PAST_MIN.max(PAST_FRACTION * scale); + body.is_outside([past.x, past.y, past.z]) + }; + match face { + Some(f) if near.distance > TOUCH * scale && !(faces_away && past_is_outside()) => { + others.retain(|o| *o != f); + dropped += 1; + } + _ => { + let nearest = Ligament { + distance: near.distance, + from: near.from, + to: near.to, + face, + }; + return Ok(Some(HoleLigament { + faces, + radius, + gap, + nearest: Some(nearest), + dropped, + })); + } + } + } + Ok(Some(none(dropped))) +} + +#[cfg(test)] +#[path = "hole_ligament_tests.rs"] +mod tests; diff --git a/solidcore/crates/solidcore-kernel/src/eval/hole_ligament_tests.rs b/solidcore/crates/solidcore-kernel/src/eval/hole_ligament_tests.rs new file mode 100644 index 00000000000..2880bb2ffd5 --- /dev/null +++ b/solidcore/crates/solidcore-kernel/src/eval/hole_ligament_tests.rs @@ -0,0 +1,397 @@ +//! Tests for [`super`]: the line helpers, and the wall around a hole measured in a body that +//! answers from a table. The plate is the 60 x 30 x 10 mm one the application's kernel tests cut +//! holes in (x 0 to 60, y 0 to 30, z 0 to 10); every number is worked out by hand from it. + +use super::{ + behind, coaxial, distance_along, hole_ligament, on_line, parallel, HoleBody, HoleLigament, + Near, Piece, +}; + +/// One face of the table body. +#[derive(Clone, Copy, Default)] +struct Face { + /// The cylinder or cone it is, if it is one. + piece: Option, + /// The plane's unit normal, if it is a plane. + plane: Option<[f64; 3]>, + /// The nearest points between the hole and this face. + foot: Option, + /// The outward normal at the foot. + outward: Option<[f64; 3]>, +} + +/// A body whose faces answer from a table: the nearest of the other faces' feet is the closest +/// pair, a point is on a face when it is the face's foot, and `outside` says where the air is. +struct Table { + faces: Vec, + outside: fn([f64; 3]) -> bool, +} + +impl HoleBody for Table { + type Error = (); + + fn face_count(&self) -> usize { + self.faces.len() + } + + fn piece(&self, face: usize) -> Option { + self.faces.get(face).and_then(|f| f.piece) + } + + fn plane_normal(&self, face: usize) -> Option<[f64; 3]> { + self.faces.get(face).and_then(|f| f.plane) + } + + fn closest(&self, _hole: &[usize], others: &[usize]) -> Result, ()> { + Ok(others + .iter() + .filter_map(|o| self.faces.get(*o).and_then(|f| f.foot)) + .min_by(|a, b| a.distance.total_cmp(&b.distance))) + } + + fn distance_to_face(&self, at: [f64; 3], face: usize) -> Option { + let foot = self.faces.get(face)?.foot?; + let d = [at[0] - foot.to[0], at[1] - foot.to[1], at[2] - foot.to[2]]; + Some((d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()) + } + + fn outward(&self, face: usize, _at: [f64; 3]) -> Option<[f64; 3]> { + self.faces.get(face)?.outward + } + + fn is_outside(&self, at: [f64; 3]) -> bool { + (self.outside)(at) + } +} + +/// Where the plate's air is: past its ends and sides. +fn outside_plate(p: [f64; 3]) -> bool { + !(0.0..=60.0).contains(&p[0]) || !(0.0..=30.0).contains(&p[1]) || !(0.0..=10.0).contains(&p[2]) +} + +/// A vertical hole's cylinder or cone face: about the vertical line through (`x`, 15), from `z0` +/// to `z1`. +fn bore(x: f64, radius: f64, z0: f64, z1: f64, cylinder: bool) -> Face { + let piece = Piece { + axis_point: [x, 15.0, 0.0], + axis: [0.0, 0.0, 1.0], + radius, + start: z0, + end: z1, + internal: true, + cylinder, + }; + Face { + piece: Some(piece), + ..Face::default() + } +} + +/// A plane square to the axis, its foot `d` mm from the hole. +fn floor(d: f64) -> Face { + let foot = Near { + distance: d, + from: [8.0, 15.0, 4.0], + to: [8.0, 15.0, 4.0 - d], + }; + Face { + plane: Some([0.0, 0.0, 1.0]), + foot: Some(foot), + ..Face::default() + } +} + +/// A wall at the end of the plate the hole's nearest point looks at, `d` mm away along -x, its +/// normal pointing away from the plate. +fn end_wall(d: f64) -> Face { + let foot = Near { + distance: d, + from: [d, 15.0, 5.0], + to: [0.0, 15.0, 5.0], + }; + Face { + plane: Some([-1.0, 0.0, 0.0]), + foot: Some(foot), + outward: Some([-1.0, 0.0, 0.0]), + piece: None, + } +} + +/// The hole's own query: its origin on the plate's top, axis up, 2 mm of reach, any radius. +fn ask(body: &Table, x: f64, max_radius: f64) -> Option { + hole_ligament( + body, + 60.0, + [x, 15.0, 10.0], + [0.0, 0.0, 1.0], + 2.0, + max_radius, + ) + .unwrap() +} + +/// A through hole 8 mm from the end of the plate: 8 - 3.2 to the end; the top and bottom do not +/// count, however near the table puts them. +#[test] +fn a_through_hole_has_the_wall_to_the_end() { + let body = Table { + faces: vec![ + bore(8.0, 3.2, 0.0, 10.0, true), + floor(0.5), + floor(0.5), + end_wall(4.8), + ], + outside: outside_plate, + }; + let hole = ask(&body, 8.0, 100.0).expect("a hole"); + assert!( + (hole.radius - 3.2).abs() < 1e-9 && hole.gap.abs() < 1e-9, + "{hole:?}" + ); + assert_eq!(hole.faces, vec![0]); + let near = hole.nearest.expect("a wall"); + assert!( + (near.distance - 4.8).abs() < 1e-6 && near.face == Some(3), + "{near:?}" + ); + assert_eq!(hole.dropped, 0); + // No hole about another line. + assert!(ask(&body, 30.0, 100.0).is_none()); +} + +/// A counterbore and its bore are one hole, whose narrowest cylinder gives the radius; the wall +/// is the nearer one, and the floor is not a wall. +#[test] +fn a_counterbore_is_one_hole_measured_from_its_wider_wall() { + let body = Table { + faces: vec![ + bore(8.0, 3.2, 0.0, 4.0, true), + bore(8.0, 5.5, 4.0, 10.0, true), + floor(1.0), + end_wall(2.5), + ], + outside: outside_plate, + }; + let hole = ask(&body, 8.0, 100.0).expect("a hole"); + assert_eq!(hole.faces, vec![0, 1]); + assert!((hole.radius - 3.2).abs() < 1e-9, "{hole:?}"); + assert!((hole.nearest.expect("a wall").distance - 2.5).abs() < 1e-9); +} + +/// A hole of cones only has radius 0; a cone joins the cylinder it runs on from. +#[test] +fn a_countersink_joins_its_bore_and_a_cone_alone_has_no_radius() { + let body = Table { + faces: vec![ + bore(8.0, 3.2, 0.0, 6.0, true), + bore(8.0, 6.0, 6.0, 10.0, false), + end_wall(2.0), + ], + outside: outside_plate, + }; + let hole = ask(&body, 8.0, 100.0).expect("a hole"); + assert_eq!(hole.faces, vec![0, 1]); + assert!((hole.radius - 3.2).abs() < 1e-9, "{hole:?}"); + let cone = Table { + faces: vec![bore(8.0, 6.0, 0.0, 10.0, false), end_wall(2.0)], + outside: outside_plate, + }; + assert!(ask(&cone, 8.0, 100.0).expect("a hole").radius.abs() < 1e-12); +} + +/// A bore wider than `max_radius` on the same axis is not the hole; with room for it, it is, and +/// joins the narrow one. +#[test] +fn a_wider_bore_on_the_axis_is_not_the_hole() { + let body = Table { + faces: vec![ + bore(30.0, 3.2, 0.0, 4.0, true), + bore(30.0, 12.0, 4.0, 10.0, true), + ], + outside: outside_plate, + }; + let narrow = hole_ligament(&body, 60.0, [30.0, 15.0, 4.0], [0.0, 0.0, 1.0], 2.0, 5.0) + .unwrap() + .expect("a hole"); + assert_eq!(narrow.faces, vec![0]); + assert!((narrow.radius - 3.2).abs() < 1e-9, "{narrow:?}"); + let wide = hole_ligament(&body, 60.0, [30.0, 15.0, 4.0], [0.0, 0.0, 1.0], 2.0, 100.0) + .unwrap() + .expect("a hole"); + assert_eq!(wide.faces, vec![0, 1]); +} + +/// A hole the origin is further from along the axis than `reach` is not found; a hole whose axis +/// runs the other way round still is, and its stretch is read against the axis. +#[test] +fn reach_and_the_sense_of_the_axis_decide_which_hole_is_found() { + let up = Table { + faces: vec![bore(8.0, 3.2, 0.0, 10.0, true)], + outside: outside_plate, + }; + // From 5 mm above the top the hole's nearest end is 5 away: out of reach 2, within 6. + let at = [8.0, 15.0, 15.0]; + assert!(hole_ligament(&up, 60.0, at, [0.0, 0.0, 1.0], 2.0, 100.0) + .unwrap() + .is_none()); + let found = hole_ligament(&up, 60.0, at, [0.0, 0.0, 1.0], 6.0, 100.0) + .unwrap() + .expect("a hole"); + assert!((found.gap - 5.0).abs() < 1e-9, "{found:?}"); + // The same line taken downwards: the stretch is 0 to -10 from the axis point, so from 5 mm + // below the bottom, along down, the gap is 5 again. + let below = [8.0, 15.0, -5.0]; + let down = hole_ligament(&up, 60.0, below, [0.0, 0.0, -1.0], 6.0, 100.0) + .unwrap() + .expect("a hole"); + assert!((down.gap - 5.0).abs() < 1e-9, "{down:?}"); + // A slanted axis finds none: the hole's cylinder lies off that line. + let slanted = [0.6, 0.0, 0.8]; + assert!( + hole_ligament(&up, 60.0, [8.0, 15.0, 10.0], slanted, 6.0, 100.0) + .unwrap() + .is_none() + ); +} + +/// A hole that breaks out of the end of the plate has no wall: a touch stands whatever lies past +/// it. +#[test] +fn a_hole_that_breaks_out_of_a_side_has_a_wall_of_zero() { + let body = Table { + faces: vec![bore(2.0, 3.2, 0.0, 10.0, true), end_wall(0.0)], + outside: |_| false, + }; + let near = ask(&body, 2.0, 100.0) + .expect("a hole") + .nearest + .expect("a wall"); + assert!( + near.distance.abs() < 1e-12 && near.face == Some(1), + "{near:?}" + ); +} + +/// A riser joined to the plate 0.8 mm from the hole's rim is no wall: nothing but air lies +/// between them. Its near face looks at the hole and is dropped; its far face meets the plate top +/// in a concave foot, where the point just past it is on the boundary, not outside, so it is +/// dropped too; the wall is to the side, 15 - 3.2 = 11.8. +#[test] +fn a_wall_rising_beside_the_hole_is_not_a_thin_wall() { + let wall = |d: f64, to: [f64; 3], normal: [f64; 3]| { + let foot = Near { + distance: d, + from: [43.2, 15.0, 10.0], + to, + }; + Face { + foot: Some(foot), + outward: Some(normal), + ..Face::default() + } + }; + let side = |y: f64, normal: [f64; 3]| { + let foot = Near { + distance: 11.8, + from: [40.0, 15.0 + normal[1] * 3.2, 5.0], + to: [40.0, y, 5.0], + }; + Face { + foot: Some(foot), + outward: Some(normal), + ..Face::default() + } + }; + let body = Table { + faces: vec![ + bore(40.0, 3.2, 0.0, 10.0, true), + wall(0.8, [44.0, 15.0, 10.0], [-1.0, 0.0, 0.0]), + wall(4.8, [48.0, 15.0, 10.0], [1.0, 0.0, 0.0]), + side(0.0, [0.0, -1.0, 0.0]), + side(30.0, [0.0, 1.0, 0.0]), + ], + outside: outside_plate, + }; + let hole = ask(&body, 40.0, 100.0).expect("a hole"); + let near = hole.nearest.expect("a wall"); + assert!( + (near.distance - 11.8).abs() < 1e-9 && near.face == Some(3), + "{near:?}" + ); + assert_eq!(hole.dropped, 2); +} + +/// When every face has open air behind it nothing is a wall, and the faces set aside are counted; +/// a body with no other face has nothing to measure to. +#[test] +fn a_hole_with_only_open_air_around_it_has_no_wall() { + let foot = Near { + distance: 2.0, + from: [0.0, 0.0, 5.0], + to: [2.0, 0.0, 5.0], + }; + let facing = Face { + foot: Some(foot), + outward: Some([-1.0, 0.0, 0.0]), + ..Face::default() + }; + let body = Table { + faces: vec![bore(8.0, 3.2, 0.0, 10.0, true), facing, facing], + outside: outside_plate, + }; + let hole = ask(&body, 8.0, 100.0).expect("a hole"); + assert!(hole.nearest.is_none()); + assert_eq!(hole.dropped, 2); + let alone = Table { + faces: vec![bore(8.0, 3.2, 0.0, 10.0, true)], + outside: outside_plate, + }; + let hole = ask(&alone, 8.0, 100.0).expect("a hole"); + assert!(hole.nearest.is_none() && hole.dropped == 0, "{hole:?}"); +} + +/// Two axes are parallel either way round within the tolerance, and no further. +#[test] +fn axes_are_parallel_either_way_round_within_the_tolerance() { + let z = [0.0, 0.0, 1.0]; + assert!(parallel(z, z, 1e-6)); + assert!(parallel([0.0, 0.0, -1.0], z, 1e-6)); + assert!(parallel([5e-7, 0.0, 1.0], z, 1e-6)); + assert!(!parallel([2e-6, 0.0, 1.0], z, 1e-6)); + assert!(!parallel([1.0, 0.0, 0.0], z, 1e-6)); +} + +/// The distance along an axis is signed, and a longer axis scales it. +#[test] +fn the_distance_along_an_axis_is_signed_and_ignores_the_sideways_offset() { + let o = [1.0, 2.0, 3.0]; + assert!((distance_along(o, [0.0, 0.0, 1.0], [9.0, 9.0, 7.0]) - 4.0).abs() < 1e-12); + assert!((distance_along(o, [0.0, 0.0, 1.0], [1.0, 2.0, 0.0]) + 3.0).abs() < 1e-12); + assert!((distance_along(o, [0.0, 0.0, 2.0], [1.0, 2.0, 4.0]) - 2.0).abs() < 1e-12); +} + +/// A point is on a line within the tolerance, on either side of the origin. +#[test] +fn a_point_is_on_the_line_within_the_tolerance() { + let (o, z) = ([1.0, 2.0, 3.0], [0.0, 0.0, 1.0]); + assert!(on_line(o, z, [1.0, 2.0, 50.0], 1e-3)); + assert!(on_line(o, z, [1.0005, 2.0, -50.0], 1e-3)); + assert!(!on_line(o, z, [1.002, 2.0, 3.0], 1e-3)); + // A slanted line: the point at the same height off the line is not on it. + let s = [0.6, 0.0, 0.8]; + assert!(on_line(o, s, [4.0, 2.0, 7.0], 1e-3)); + assert!(!on_line(o, s, [4.0, 2.0, 7.1], 1e-3)); +} + +/// A part is coaxial when its axis agrees either way round and it sits on the line; a part is +/// behind when it is at or behind the origin along the axis, with the tolerance's slack. +#[test] +fn coaxial_needs_both_the_direction_and_the_line_and_behind_is_the_tools_way() { + let (o, z) = ([0.0, 0.0, 10.0], [0.0, 0.0, 1.0]); + assert!(coaxial(o, z, [0.0, 0.0, 4.0], [0.0, 0.0, -1.0], 1e-6, 1e-3)); + assert!(!coaxial(o, z, [0.5, 0.0, 4.0], z, 1e-6, 1e-3)); + assert!(!coaxial(o, z, [0.0, 0.0, 4.0], [1.0, 0.0, 0.0], 1e-6, 1e-3)); + assert!(behind(o, z, [3.0, 0.0, 4.0], 1e-3)); + assert!(behind(o, z, [0.0, 0.0, 10.0005], 1e-3)); + assert!(!behind(o, z, [0.0, 0.0, 11.0], 1e-3)); +} diff --git a/solidcore/crates/solidcore-ops/src/hole_ligament.rs b/solidcore/crates/solidcore-ops/src/hole_ligament.rs new file mode 100644 index 00000000000..51814357b21 --- /dev/null +++ b/solidcore/crates/solidcore-ops/src/hole_ligament.rs @@ -0,0 +1,64 @@ +//! The solid wall around a round hole ([`hole_ligament`]), and the line helpers a fastener +//! check asks of a hole's axis ([`parallel`], [`on_line`], [`coaxial`], [`behind`]). The kernel +//! does the work ([`solidcore::eval::hole_ligament`]): it reads the hole off the body's faces, +//! measures from them to the body's other faces and decides which of those have material behind +//! them. The body gives it only what its own faces tell ([`HoleBody`]: the faces' shapes, the +//! exact distances); nothing here computes. + +use solidcore::eval::hole_ligament as k; + +pub use k::{HoleBody, HoleLigament, Ligament, Near, Piece, MAX_NAMED, MAX_ROUNDS}; + +/// The hole of a body of `size` (the diagonal of its bounding box, in mm) about the line +/// through `origin` along the unit `axis` whose nearest end lies within `reach` mm of `origin` +/// along the axis, and the wall around it: the shortest distance from the hole's cylinders and +/// cones to the body's other faces that have material behind them, leaving out the planes +/// square to the axis. Only cylinders and cones up to `max_radius` count as the hole. `None` +/// when no such hole is about that line. +/// +/// # Errors +/// What `body`'s [`HoleBody::closest`] gives. +pub fn hole_ligament( + body: &B, + size: f64, + origin: [f64; 3], + axis: [f64; 3], + reach: f64, + max_radius: f64, +) -> Result, B::Error> { + k::hole_ligament(body, size, origin, axis, reach, max_radius) +} + +/// Whether `direction` is `axis` or its opposite, each a unit vector, within `tol`. +#[must_use] +pub fn parallel(direction: [f64; 3], axis: [f64; 3], tol: f64) -> bool { + k::parallel(direction, axis, tol) +} + +/// Whether `point` lies within `tol` mm of the line through `origin` along the unit `axis`. +#[must_use] +pub fn on_line(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], tol: f64) -> bool { + k::on_line(origin, axis, point, tol) +} + +/// Whether a part seated at `point`, its own axis `direction`, is coaxial with the line through +/// `origin` along `axis`: `direction` is `axis` either way round within `axis_tol` and `point` +/// is within `line_tol` mm of the line. +#[must_use] +pub fn coaxial( + origin: [f64; 3], + axis: [f64; 3], + point: [f64; 3], + direction: [f64; 3], + axis_tol: f64, + line_tol: f64, +) -> bool { + k::coaxial(origin, axis, point, direction, axis_tol, line_tol) +} + +/// Whether `point` is at or behind `origin` along `axis`, to within `tol` mm: not in front of +/// it, the way a tool along `axis` goes. +#[must_use] +pub fn behind(origin: [f64; 3], axis: [f64; 3], point: [f64; 3], tol: f64) -> bool { + k::behind(origin, axis, point, tol) +} diff --git a/solidcore/crates/solidcore-ops/src/lib.rs b/solidcore/crates/solidcore-ops/src/lib.rs index 919e2f21688..3d2acd91f3b 100644 --- a/solidcore/crates/solidcore-ops/src/lib.rs +++ b/solidcore/crates/solidcore-ops/src/lib.rs @@ -87,6 +87,7 @@ pub mod gap_wedge; pub mod heal; pub mod history; pub mod hlr; +pub mod hole_ligament; pub mod joint_offset; pub mod joint_turn; pub mod keep_edge; diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 18a4a3e011d..2a53f1eb532 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -282,6 +282,7 @@ inspect.colored_components display: component colours inspect.compare_picture display analysis: a picture compared with the outline inspect.curvature_map display analysis: shading inspect.environment_map display analysis: shading +inspect.fastener_checks read-only query: exact edge distance and tool clearance, tested in crates/engine/src/cmd/fastener_checks_tests.rs inspect.fastener_rationalize read-only query: tested in crates/engine/src/cmd/fastener_rationalize_tests.rs inspect.free_occurrences read-only query: tested in crates/engine/src/cmd/free_occurrences_tests.rs inspect.hole_stacks read-only query: tested in crates/engine/src/cmd/hole_stacks_tests.rs