use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Map, Value};
use super::{Feature, HolePattern};
use crate::model::Analysis;
const IDENTITY: [[f64; 3]; 4] = [[0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Recess {
pub diameter: f64,
pub depth: Option<f64>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Countersink {
pub diameter: f64,
pub angle: Option<f64>,
}
type Drilling = (Vec<i64>, [i64; 3]);
type Segment<'a> = ([f64; 2], f64, &'a str);
#[derive(Clone, Debug, PartialEq)]
pub struct Hole<'a> {
pub feature: &'a Feature,
pub at: [f64; 3],
pub direction: [f64; 3],
pub principal: Option<(usize, i8)>,
pub diameter: f64,
pub through: bool,
pub bottom: Option<&'a str>,
pub depth: Option<f64>,
pub counterbore: Option<Recess>,
pub outer_steps: Vec<Recess>,
pub spotface: Option<Recess>,
pub countersink: Option<Countersink>,
pub frame: [[f64; 3]; 4],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Axis {
pub at: [f64; 3],
pub direction: [f64; 3],
}
pub fn principal(d: [f64; 3]) -> Option<usize> {
let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if n == 0.0 {
return None;
}
let along: Vec<usize> = (0..3).filter(|&k| (d[k] / n).abs() >= 1e-6).collect();
(along.len() == 1).then(|| along[0])
}
pub fn size_key(x: f64) -> i64 {
(x * 1e6).round() as i64
}
pub fn point(v: Option<&Value>) -> Option<[f64; 3]> {
let a = v?.as_array()?;
Some([
a.first()?.as_f64()?,
a.get(1)?.as_f64()?,
a.get(2)?.as_f64()?,
])
}
pub fn frame(analysis: &Analysis) -> [[f64; 3]; 4] {
analysis.recognition.as_ref().map_or(IDENTITY, |r| r.frame)
}
pub fn to_part(frame: &[[f64; 3]; 4], l: [f64; 3]) -> [f64; 3] {
[0, 1, 2].map(|k| frame[0][k] + (0..3).map(|j| l[j] * frame[j + 1][k]).sum::<f64>())
}
pub fn dir_to_part(frame: &[[f64; 3]; 4], d: [f64; 3]) -> [f64; 3] {
[0, 1, 2].map(|k| (0..3).map(|j| d[j] * frame[j + 1][k]).sum::<f64>())
}
fn sized(
p: &Map<String, Value>,
name: &str,
first: &str,
second: &str,
) -> Result<Option<(f64, Option<f64>)>, String> {
match p.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(r)) => {
let d = r
.get(first)
.and_then(Value::as_f64)
.ok_or_else(|| format!("its {name} has no {first}"))?;
Ok(Some((d, r.get(second).and_then(Value::as_f64))))
}
Some(v) => Err(format!("its {name} is {v}, not a record")),
}
}
fn outer_steps(p: &Map<String, Value>) -> Result<Vec<Recess>, String> {
match p.get("outer_steps") {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(steps)) => steps
.iter()
.map(|step| {
let r = step
.as_object()
.ok_or_else(|| format!("its outer step {step} is not a record"))?;
Ok(Recess {
diameter: r
.get("diameter")
.and_then(Value::as_f64)
.ok_or("its outer step has no diameter")?,
depth: r.get("depth").and_then(Value::as_f64),
})
})
.collect(),
Some(v) => Err(format!("its outer_steps is {v}, not a list")),
}
}
impl<'a> Hole<'a> {
pub fn read(f: &'a Feature, frame: &[[f64; 3]; 4]) -> Result<Hole<'a>, String> {
let p = &f.parameters;
let axis = point(p.get("axis")).ok_or("it has no axis")?;
let location = point(p.get("location")).ok_or("it has no location")?;
let d = dir_to_part(frame, axis);
let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if n == 0.0 {
return Err("its axis is a zero vector".into());
}
let direction = d.map(|c| c / n);
let bottom = p.get("bottom").and_then(Value::as_str);
let recess = |name: &str| {
sized(p, name, "diameter", "depth")
.map(|r| r.map(|(diameter, depth)| Recess { diameter, depth }))
};
Ok(Hole {
feature: f,
at: to_part(frame, location),
direction,
principal: principal(direction).map(|k| (k, if direction[k] > 0.0 { 1 } else { -1 })),
diameter: p
.get("diameter")
.and_then(Value::as_f64)
.ok_or("it has no diameter")?,
through: bottom == Some("through"),
bottom,
depth: p.get("depth").and_then(Value::as_f64),
counterbore: recess("cbore")?,
outer_steps: outer_steps(p)?,
spotface: recess("spotface")?,
countersink: sized(p, "csink", "major_diameter", "included_angle")?
.map(|(diameter, angle)| Countersink { diameter, angle }),
frame: *frame,
})
}
pub fn requirement(&self) -> Vec<i64> {
let opt = |v: Option<f64>| v.map_or(i64::MIN, size_key);
let mut k: Vec<i64> = self.direction.iter().map(|c| size_key(*c)).collect();
k.extend([
size_key(self.diameter),
self.through as i64,
if self.through { 0 } else { opt(self.depth) },
]);
for r in [self.counterbore, self.spotface] {
match r {
Some(r) => k.extend([1, size_key(r.diameter), opt(r.depth)]),
None => k.push(0),
}
}
for r in &self.outer_steps {
k.extend([2, size_key(r.diameter), opt(r.depth)]);
}
match self.countersink {
Some(c) => k.extend([1, size_key(c.diameter), opt(c.angle)]),
None => k.push(0),
}
k
}
pub fn recesses(&self) -> impl Iterator<Item = Recess> + '_ {
self.counterbore
.into_iter()
.chain(self.outer_steps.iter().rev().copied())
.chain(self.spotface)
}
pub fn opening_diameter(&self) -> f64 {
self.recesses()
.map(|r| r.diameter)
.chain(self.countersink.map(|c| c.diameter))
.fold(self.diameter, f64::max)
}
fn segment(&self) -> Option<(Drilling, [f64; 2])> {
let plain =
self.counterbore.is_none() && self.spotface.is_none() && self.countersink.is_none();
let depth = self.depth.filter(|d| d.is_finite() && *d > 0.0)?;
if !(self.through && plain) {
return None;
}
let d = self.direction;
let along: f64 = (0..3).map(|k| self.at[k] * d[k]).sum();
let line = [0, 1, 2].map(|k| ((self.at[k] - along * d[k]) * 1e3).round() as i64);
Some(((self.requirement(), line), [along, along + depth]))
}
}
pub fn continuations<'h, 'a: 'h>(
holes: impl IntoIterator<Item = &'h Hole<'a>>,
) -> BTreeSet<&'a str> {
let mut lines: BTreeMap<Drilling, Vec<Segment<'a>>> = BTreeMap::new();
for h in holes {
if let Some((line, span)) = h.segment() {
lines
.entry(line)
.or_default()
.push((span, h.diameter, h.feature.id.as_str()));
}
}
let mut out = BTreeSet::new();
for mut segments in lines.into_values() {
segments.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]));
let mut reach = f64::NEG_INFINITY;
for ([lo, hi], diameter, id) in segments {
if lo - reach < diameter {
out.insert(id);
}
reach = reach.max(hi);
}
}
out
}
pub fn drillings<'h, 'a: 'h>(holes: impl IntoIterator<Item = &'h Hole<'a>> + Clone) -> usize {
holes.clone().into_iter().count() - continuations(holes).len()
}
pub fn read(analysis: &Analysis) -> Vec<(&Feature, Result<Hole<'_>, String>)> {
let frame = frame(analysis);
analysis
.features
.iter()
.filter(|f| f.kind == "hole")
.map(|f| (f, Hole::read(f, &frame)))
.collect()
}
pub fn bosses(analysis: &Analysis) -> Vec<Axis> {
let frame = frame(analysis);
analysis
.features
.iter()
.filter_map(|f| {
let (place, direction) = match f.kind.as_str() {
"boss" => ("location", "axis"),
"turned_body" => ("axis_point", "axis"),
_ => return None,
};
let at = to_part(&frame, point(f.parameters.get(place))?);
let d = crate::lint::parameters::direction(&frame, f.parameters.get(direction))?;
let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
(n > 0.0).then(|| Axis {
at,
direction: d.map(|c| c / n),
})
})
.collect()
}
const CONCENTRIC: f64 = 0.5;
pub fn established(p: &HolePattern, holes: &[&Hole]) -> Result<Vec<usize>, String> {
established_with(p, holes, &[])
}
pub fn established_with(
p: &HolePattern,
holes: &[&Hole],
bosses: &[Axis],
) -> Result<Vec<usize>, String> {
let members: Vec<usize> = p
.members
.iter()
.map(|m| holes.iter().position(|h| &h.feature.id == m))
.collect::<Option<_>>()
.ok_or_else(|| {
format!(
"its pattern {} has a member that cannot be called out with it",
p.id
)
})?;
if members.len() < 2 {
return Err(format!("its pattern {} has one member", p.id));
}
let first = holes[members[0]].requirement();
if members.iter().any(|&m| holes[m].requirement() != first) {
return Err(format!(
"its pattern {} is not of identical holes, so each is called out as itself",
p.id
));
}
let Some(k) = principal(holes[members[0]].direction) else {
return Err(format!(
"its pattern {} lies in an oblique plane, so its holes are dimensioned singly",
p.id
));
};
let mut across: Vec<Vec<i64>> = members
.iter()
.map(|&m| {
(0..3)
.filter(|&i| i != k)
.map(|i| size_key(holes[m].at[i]))
.collect()
})
.collect();
across.sort();
across.dedup();
if across.len() < members.len() {
return Err(format!(
"its pattern {} has members on one axis line, apart only along the drilling direction, so its holes are dimensioned singly",
p.id
));
}
if p.arrangement == "bolt_circle" && members.len() < 5 {
let h = holes[members[0]];
let centre = point(p.parameters.get("center")).map(|c| to_part(&h.frame, c));
let others = holes
.iter()
.enumerate()
.filter(|(i, _)| !members.contains(i))
.map(|(_, o)| Axis {
at: o.at,
direction: o.direction,
});
let dot = |u: [f64; 3], v: [f64; 3]| u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
let concentric = |c: [f64; 3], a: &Axis| {
let d = [c[0] - a.at[0], c[1] - a.at[1], c[2] - a.at[2]];
let along = dot(d, a.direction);
dot(a.direction, h.direction).abs() >= 1.0 - 1e-6
&& (dot(d, d) - along * along).max(0.0).sqrt() <= CONCENTRIC
};
let corroborated = centre.is_some_and(|c| {
others
.chain(bosses.iter().copied())
.any(|a| concentric(c, &a))
});
if !corroborated {
return Err(format!(
"quiddity's bolt circle {} has fewer than five members and no hole or boss on its centre, which does not establish a circle (ISSUE-1596-a), so its holes are dimensioned singly",
p.id
));
}
}
Ok(members)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn feature(parameters: Value) -> Feature {
serde_json::from_value(json!({
"id": "f:hole:1", "kind": "hole", "faces": [0], "parameters": parameters,
"fingerprint": { "version": "test", "family": "holes", "subtype": "HoleRecord",
"sizes": {}, "position": [0.0, 0.0, 0.0], "neighbourhood": [] },
}))
.unwrap()
}
#[test]
fn a_principal_axis_is_exactly_one_component() {
assert_eq!(principal([0.0, 0.0, -1.0]), Some(2));
assert_eq!(principal([1e-9, 2.0, 0.0]), Some(1));
assert_eq!(principal([0.0, 0.01, 1.0]), None);
assert_eq!(principal([0.0; 3]), None);
}
#[test]
fn a_countersink_is_read_by_quidditys_field_names() {
let f = feature(json!({
"axis": [0.0, 0.0, -1.0], "location": [5.0, 5.0, 10.0], "diameter": 6.6,
"depth": 10.0, "bottom": "through", "cbore": null, "spotface": null,
"csink": { "major_diameter": 12.4, "included_angle": 90.0, "drill_diameter": 6.6,
"depth": 2.9, "axis": [0.0, 0.0, -1.0], "location": [5.0, 5.0, 10.0] },
}));
let h = Hole::read(&f, &IDENTITY).unwrap();
assert_eq!(
h.countersink,
Some(Countersink {
diameter: 12.4,
angle: Some(90.0)
})
);
assert_eq!(h.principal, Some((2, -1)));
let mut odd = f.clone();
odd.parameters["csink"] = json!({ "diameter": 12.4 });
assert_eq!(
Hole::read(&odd, &IDENTITY).unwrap_err(),
"its csink has no major_diameter"
);
}
#[test]
fn the_requirement_reads_depth_only_when_blind() {
let base = json!({ "axis": [0.0, 0.0, 1.0], "location": [0.0, 0.0, 0.0],
"diameter": 6.0, "depth": 5.0, "bottom": "through" });
let mut other = base.clone();
other["depth"] = json!(8.0);
let (a, b) = (feature(base.clone()), feature(other.clone()));
let key = |f: &Feature| Hole::read(f, &IDENTITY).unwrap().requirement();
assert_eq!(key(&a), key(&b));
let mut blind = (base, other);
blind.0["bottom"] = json!("flat");
blind.1["bottom"] = json!("flat");
assert_ne!(key(&feature(blind.0)), key(&feature(blind.1)));
}
#[test]
fn a_slit_splits_one_through_hole_but_a_wide_gap_leaves_two() {
let segment = |id: &str, x: f64, edit: &dyn Fn(&mut Value)| {
let mut p = json!({ "axis": [-1.0, 0.0, 0.0], "location": [x, -5.0, -11.0],
"diameter": 4.0, "depth": 8.9, "bottom": "through" });
edit(&mut p);
let mut f = feature(p);
f.id = id.into();
f
};
let none = |_: &mut Value| {};
fn read(fs: &[Feature]) -> Vec<Hole<'_>> {
fs.iter()
.map(|f| Hole::read(f, &IDENTITY).unwrap())
.collect()
}
let split = [
segment("f:hole:1", -0.6, &none),
segment("f:hole:4", 9.5, &none),
];
let holes = read(&split);
assert_eq!(continuations(&holes), BTreeSet::from(["f:hole:1"]));
assert_eq!(drillings(&holes), 1);
let lugs = [
segment("f:hole:1", -24.0, &none),
segment("f:hole:2", 28.0, &none),
];
assert_eq!(drillings(&read(&lugs)), 2);
let blind = |p: &mut Value| p["bottom"] = json!("flat");
let pair = [
segment("f:hole:1", -0.6, &blind),
segment("f:hole:4", 9.5, &blind),
];
assert_eq!(drillings(&read(&pair)), 2);
let bored = |p: &mut Value| p["cbore"] = json!({ "diameter": 8.0, "depth": 2.0 });
let pair = [
segment("f:hole:1", -0.6, &bored),
segment("f:hole:4", 9.5, &bored),
];
assert_eq!(drillings(&read(&pair)), 2);
let off = |p: &mut Value| p["location"][1] = json!(5.0);
let pair = [
segment("f:hole:1", -0.6, &none),
segment("f:hole:4", 9.5, &off),
];
assert_eq!(drillings(&read(&pair)), 2);
}
#[test]
fn a_small_bolt_circle_needs_something_round_on_its_centre() {
let frame = [
[5.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[1.0, 0.0, 0.0],
];
let hole = |id: &str, at: [f64; 3], diameter: f64| {
let mut f = feature(json!({ "axis": [0.0, 0.0, 1.0], "location": at,
"diameter": diameter, "depth": 5.0,
"bottom": "through" }));
f.id = id.into();
f
};
let mut fs: Vec<Feature> = [[70.0, 50.0], [50.0, 70.0], [30.0, 50.0], [50.0, 30.0]]
.iter()
.enumerate()
.map(|(i, c)| hole(&format!("f:hole:{}", i + 1), [c[0], c[1], 0.0], 6.0))
.collect();
fs.push(hole("f:hole:5", [50.0, 50.0, 0.0], 20.0));
let read: Vec<Hole> = fs.iter().map(|f| Hole::read(f, &frame).unwrap()).collect();
let all: Vec<&Hole> = read.iter().collect();
let circle = |members: &[&str]| HolePattern {
presentation_order: None,
legacy_id: None,
id: "f:hole_pattern:1".into(),
arrangement: "bolt_circle".into(),
members: members.iter().map(|m| m.to_string()).collect(),
faces: vec![],
parameters: json!({ "center": [50.0, 50.0, 0.0], "diameter": 40.0 })
.as_object()
.unwrap()
.clone(),
};
let four = circle(&["f:hole:1", "f:hole:2", "f:hole:3", "f:hole:4"]);
assert_eq!(established(&four, &all), Ok(vec![0, 1, 2, 3]));
let err = established(&four, &all[..4]).unwrap_err();
assert!(err.contains("fewer than five"), "{err}");
let boss = |at: [f64; 3], direction: [f64; 3]| Axis { at, direction };
assert_eq!(
established_with(
&four,
&all[..4],
&[boss([0.0, 50.0, 50.0], [-1.0, 0.0, 0.0])]
),
Ok(vec![0, 1, 2, 3])
);
assert!(
established_with(
&four,
&all[..4],
&[boss([0.0, 50.6, 50.0], [1.0, 0.0, 0.0])]
)
.is_err()
);
assert!(
established_with(
&four,
&all[..4],
&[boss([5.0, 50.0, 50.0], [0.0, 1.0, 0.0])]
)
.is_err()
);
let mut five = four.clone();
five.members.push("f:hole:5".into());
assert_eq!(
established(&five, &all).unwrap_err(),
"its pattern f:hole_pattern:1 is not of identical holes, so each is called out as itself"
);
let mut centreless = four.clone();
centreless.parameters.remove("center");
assert!(established(¢reless, &all).is_err());
}
#[test]
fn bosses_are_read_in_the_parts_frame() {
let mut a: Analysis = serde_json::from_value(json!({
"schema": "draftwright.analysis/2",
"binding": { "source_sha256": "", "part": "test", "face_count": 2, "loader": "test" },
"envelope": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]],
"features": [],
"iso_bounds": [0.0, 0.0, 0.0, 0.0],
"recognition": { "recogniser": "test",
"frame": [[5.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0],
[1.0, 0.0, 0.0]] },
}))
.unwrap();
for (i, p) in [
json!({ "axis": [0.0, 0.0, 2.0], "location": [50.0, 50.0, 1.0], "diameter": 30.0 }),
json!({ "diameter": 30.0 }),
]
.into_iter()
.enumerate()
{
let mut f = feature(p);
f.id = format!("f:boss:{}", i + 1);
f.kind = "boss".into();
a.features.push(f);
}
assert_eq!(
bosses(&a),
[Axis {
at: [6.0, 50.0, 50.0],
direction: [1.0, 0.0, 0.0]
}]
);
}
#[test]
fn an_oblique_or_coaxial_pattern_is_not_established() {
let hole = |id: &str, axis: [f64; 3], at: [f64; 3]| {
let mut f = feature(json!({ "axis": axis, "location": at, "diameter": 6.0,
"depth": 5.0, "bottom": "through" }));
f.id = id.into();
f
};
let pattern = |arrangement: &str| HolePattern {
presentation_order: None,
legacy_id: None,
id: "f:hole_pattern:1".into(),
arrangement: arrangement.into(),
members: vec!["f:hole:1".into(), "f:hole:2".into(), "f:hole:3".into()],
faces: vec![],
parameters: Map::new(),
};
let established_of = |fs: &[Feature], arrangement: &str| {
let read: Vec<Hole> = fs
.iter()
.map(|f| Hole::read(f, &IDENTITY).unwrap())
.collect();
established(&pattern(arrangement), &read.iter().collect::<Vec<_>>())
};
let z = [0.0, 0.0, 1.0];
let uneven = [
hole("f:hole:1", z, [0.0, 0.0, 0.0]),
hole("f:hole:2", z, [10.0, 3.0, 0.0]),
hole("f:hole:3", z, [25.0, 0.0, 0.0]),
];
assert_eq!(established_of(&uneven, "grid"), Ok(vec![0, 1, 2]));
let tilted = [0.0, 0.6, 0.8];
let oblique = [
hole("f:hole:1", tilted, [0.0, 0.0, 0.0]),
hole("f:hole:2", tilted, [10.0, 0.0, 0.0]),
hole("f:hole:3", tilted, [20.0, 0.0, 0.0]),
];
assert!(
established_of(&oblique, "linear")
.unwrap_err()
.contains("oblique")
);
let coaxial = [
hole("f:hole:1", z, [0.0, 0.0, 0.0]),
hole("f:hole:2", z, [0.0, 0.0, 10.0]),
hole("f:hole:3", z, [10.0, 0.0, 0.0]),
];
assert!(
established_of(&coaxial, "linear")
.unwrap_err()
.contains("one axis line")
);
}
}