use std::collections::{BTreeMap, BTreeSet};
use haecceity::Part;
use haecceity::geom::{Bounds, Surface};
use haecceity::p21::{self, Attribute, Document, RawEntity};
use haecceity::pmi::{
self, Anchor, AngleUnit, AttributeValue, AuxiliaryClassification, DatumId, DimTolerance,
Dimension, DimensionId, DimensionKind, EdgeIndex, FaceIndex, Feature, FeatureId,
GeneralTolerance, GeometricTolerance, GroupKind, LengthUnit, LocationKind, NoteOwner,
PartIdentifiers, PartPmi, PartProvenance, Quantity, SizeKind, ToleranceKind, ToleranceModifier,
ToleranceTarget, Value,
};
use haecceity::step::{PartDefinition, read_part_definitions};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub mod graphical;
pub const PMI_SCHEMA: &str = "draftwright.pmi/1";
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Category {
Dimension,
GeometricTolerance,
Datum,
ManufacturingRequirement,
SurfaceLabel,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Extracted,
PartiallyExtracted,
NotExtracted,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Source {
pub id: String,
pub category: Category,
pub entity: String,
pub instances: Vec<u64>,
pub outcome: Outcome,
pub reason: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Record {
pub source_id: String,
pub category: Category,
pub kind: String,
pub type_code: Option<u32>,
pub part: usize,
pub part21_id: u64,
pub value: Option<f64>,
pub upper_tol: Option<f64>,
pub lower_tol: Option<f64>,
pub lower_bound: Option<f64>,
pub upper_bound: Option<f64>,
pub fit: Option<String>,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authored_depth_label: Option<String>,
pub datum_refs: Vec<String>,
pub gtol_modifiers: Vec<String>,
pub basic: bool,
pub faces: Vec<usize>,
pub face_ids: Vec<u64>,
pub face_groups: Vec<Vec<usize>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub edge_groups: Vec<Vec<usize>>,
pub edges: Vec<usize>,
pub ref_bbox: Option<[f64; 6]>,
pub dominant_axis: String,
pub instances: Vec<u64>,
pub blockers: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<(String, Field)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub geometry: Option<Geometry>,
}
const SPECIFY_WRITTEN: &str = "Specify-written PMI (specify-core:written:v1).";
const SPECIFY_MARKER: &str = "specify-core:written:v1";
pub(crate) fn specify_written(report: &Report, source: &str) -> bool {
report
.sources
.iter()
.any(|s| s.id == source && s.reason.starts_with(SPECIFY_WRITTEN))
}
pub(crate) fn specify_general(report: &Report, r: &Record) -> bool {
r.category == Category::Dimension
&& !r.basic
&& r.upper_tol.is_none()
&& r.lower_tol.is_none()
&& r.lower_bound.is_none()
&& r.upper_bound.is_none()
&& r.fit.is_none()
&& match r.fields.iter().find(|(k, _)| k == "specify origin") {
Some((_, Field::Text(origin))) => origin == "general_tolerance",
Some(_) => false,
None => specify_written(report, &r.source_id),
}
}
pub(crate) fn datum_referenced(r: &Record) -> bool {
r.fields.iter().any(|(k, _)| k == "reference datum")
}
fn specify_root(doc: &Document, r: &Record) -> bool {
let root = r.part21_id;
let direct = match r.kind.as_str() {
"internal_thread" | "external_thread" => text_of(doc, root, "THREAD", 1) == SPECIFY_MARKER,
"knurl" => text_of(doc, root, "TURNED_KNURL", 0) == SPECIFY_MARKER,
_ => false,
};
let dimension = r.category == Category::Dimension
&& r.instances.iter().any(|&rep| {
attributes(doc, rep, "SHAPE_DIMENSION_REPRESENTATION").is_some()
&& doc.referrers(rep).iter().any(|&id| {
text_of(doc, id, "DESCRIPTION_ATTRIBUTE", 0) == SPECIFY_MARKER
&& ref_of(doc, id, "DESCRIPTION_ATTRIBUTE", 1) == Some(rep)
})
});
direct
|| dimension
|| r.instances.iter().any(|&link| {
ref_of(doc, link, "PROPERTY_DEFINITION_REPRESENTATION", 0) == Some(root)
&& attributes(doc, root, "PROPERTY_DEFINITION").is_some()
&& doc.referrers(link).iter().any(|&id| {
text_of(doc, id, "DESCRIPTION_ATTRIBUTE", 0) == SPECIFY_MARKER
&& ref_of(doc, id, "DESCRIPTION_ATTRIBUTE", 1) == Some(link)
})
})
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Field {
Text(String),
Length(f64),
}
const MISSING_NOMINAL: &str = "the file states no nominal value (haecceity reads it without one)";
const MEASURED_NOMINAL: &str = "geometry (no stated value)";
pub(crate) fn nominal_measured(r: &Record) -> bool {
r.fields.iter().any(|(key, value)| {
key == "nominal source" && *value == Field::Text(MEASURED_NOMINAL.into())
})
}
fn missing_nominal_finding(f: &pmi::Finding) -> bool {
f.kind == pmi::FindingKind::Nonconformance
&& f.detail
.starts_with("a dimension without a dimensional_characteristic_representation:")
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Accounting {
pub semantic: usize,
pub consumed: usize,
pub reported: usize,
pub presentation: usize,
pub validation: usize,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Report {
pub schema: String,
pub parts: Vec<String>,
pub sources: Vec<Source>,
pub records: Vec<Record>,
pub accounting: Accounting,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub materials: Vec<Material>,
#[serde(flatten)]
pub reader: Box<ReaderEvidence>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub drawn: Option<usize>,
#[serde(skip)]
pub spec_problems: Vec<crate::model::Problem>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ReaderEvidence {
#[serde(
default,
rename = "reader_problems",
skip_serializing_if = "Vec::is_empty"
)]
pub problems: Vec<crate::model::Problem>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub callouts: Vec<graphical::Callout>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Material {
pub source_id: String,
pub part: usize,
pub designation: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl Material {
pub fn census_id(&self) -> String {
format!("material:{}:0", self.part)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Identities {
pub ids: BTreeMap<String, String>,
pub shared: BTreeMap<String, (String, Vec<String>)>,
}
impl Identities {
pub fn id(&self, source: &str) -> Result<&str, String> {
if let Some(id) = self.ids.get(source) {
return Ok(id);
}
match self.shared.get(source) {
Some((identity, others)) => Err(format!(
"its identity (pmi:{identity}: what it requires, of which faces, against which datums) is also {}'s, so its drawing item could not be told from theirs and none of them is drawn",
others.join(", ")
)),
None => Err(format!("the reading has no record {source}")),
}
}
pub fn source(&self, id: &str) -> Option<&str> {
self.ids
.iter()
.find(|(_, i)| i.as_str() == id)
.map(|(s, _)| s.as_str())
}
}
fn escaped(text: &str) -> String {
let mut out = String::new();
for b in text.bytes() {
if b.is_ascii_alphanumeric() || b"_.-".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
pub fn identity(r: &Record, parts: usize) -> String {
let join = |v: &[String]| v.iter().map(|x| escaped(x)).collect::<Vec<_>>().join(",");
let numbers = |v: &[usize]| {
v.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
};
let mut out = format!("{}.{}", category_name(r.category), escaped(&r.kind));
if r.basic {
out += ".basic";
}
if parts > 1 {
out += &format!(":p{}", r.part);
}
if !r.faces.is_empty() {
out += &format!(":f{}", numbers(&r.faces));
}
if !r.edges.is_empty() {
out += &format!(":e{}", numbers(&r.edges));
}
if !r.datum_refs.is_empty() {
out += &format!(":ref={}", join(&r.datum_refs));
}
if !r.gtol_modifiers.is_empty() {
out += &format!(":mod={}", join(&r.gtol_modifiers));
}
let labelled = r.category == Category::Datum
|| r.category == Category::SurfaceLabel
|| r.kind == "common_label";
if labelled {
out += &format!(":t={}", escaped(&r.label));
}
out
}
impl Report {
pub fn identities(&self) -> Identities {
fn group<'a>(
records: Vec<&'a Record>,
key: &dyn Fn(&Record) -> String,
) -> BTreeMap<String, Vec<&'a Record>> {
let mut by: BTreeMap<String, Vec<&Record>> = BTreeMap::new();
for r in records {
by.entry(key(r)).or_default().push(r);
}
by
}
let parts = self.parts.len();
let mut out = Identities::default();
for (base, records) in group(self.records.iter().collect(), &|r| identity(r, parts)) {
let labelled = records.len() > 1 && !base.contains(":t=");
let by = if labelled {
group(records, &|r| {
format!(
"{base}:t={}",
escaped(if nominal_measured(r) { "" } else { &r.label })
)
})
} else {
BTreeMap::from([(base, records)])
};
for (identity, records) in by {
if let [one] = records.as_slice() {
out.ids
.insert(one.source_id.clone(), format!("pmi:{identity}"));
continue;
}
for r in &records {
let others = records
.iter()
.filter(|o| o.source_id != r.source_id)
.map(|o| o.source_id.clone());
out.shared
.insert(r.source_id.clone(), (identity.clone(), others.collect()));
}
}
}
out
}
pub fn title_material(&self) -> Option<&Material> {
match self.materials.as_slice() {
[m] if self.owns(m) && !m.designation.trim().is_empty() => Some(m),
_ => None,
}
}
pub fn owns(&self, m: &Material) -> bool {
self.parts.len() == 1 || self.drawn == Some(m.part)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DerivedTarget {
pub kind: DerivedKind,
pub point: [f64; 3],
pub direction: [f64; 3],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub radius: Option<f64>,
pub faces: Vec<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DerivedKind {
Axis,
MedianPlane,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GeometryRefusal {
NominalMismatch { measured: f64, nominal: f64 },
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Geometry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refusal: Option<GeometryRefusal>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<Option<DerivedTarget>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sites: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub alternatives: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub axis: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub normal: Option<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stations: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_witnesses: BTreeMap<String, [[f64; 3]; 2]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cylinders: Vec<crate::pmi_lowering::Cylinder>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hole_depths: Vec<crate::pmi_lowering::HoleDepth>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub axis_points: Vec<Vec<AxisPoint>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub axis_point_reasons: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub angle: Option<crate::dims::angular::Angle>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reasons: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub face_on: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AxisPoint {
pub point: [f64; 3],
pub faces: Vec<usize>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Reading {
Read(Report),
Refused(String),
}
const SEMANTIC: [&str; 6] = [
"DIMENSIONAL_SIZE",
"DIMENSIONAL_LOCATION",
"GEOMETRIC_TOLERANCE",
"DATUM",
"DATUM_FEATURE",
"DATUM_SYSTEM",
];
#[derive(Default)]
pub struct Reader {
source: Option<[u8; 32]>,
reading: Option<Reading>,
reads: usize,
}
impl Reader {
pub fn reads(&self) -> usize {
self.reads
}
pub fn attach(&mut self, bytes: &[u8], part: &Part) -> Option<Reading> {
let bytes = match crate::model::step_bytes(bytes) {
Ok(b) => b,
Err(e) => return Some(Reading::Refused(e)),
};
let bytes = &*bytes;
let source = Sha256::digest(bytes).into();
if self.source != Some(source) {
self.reads += 1;
self.reading = attached(bytes, read(bytes, part));
self.source = Some(source);
}
self.reading.clone()
}
}
pub fn attach(bytes: &[u8], part: &Part) -> Option<Reading> {
Reader::default().attach(bytes, part)
}
pub(crate) fn attach_with(
bytes: &[u8],
part: &Part,
defs: Result<&[PartDefinition], &str>,
chosen: Option<usize>,
) -> (Option<Reading>, Option<crate::bom::Metadata>) {
match defs
.map_err(str::to_string)
.and_then(|defs| read_with_metadata(bytes, part, defs, chosen))
{
Ok(read) => (attached(bytes, read.pmi), read.bom),
Err(error) => (attached(bytes, Err(error)), None),
}
}
fn attached(bytes: &[u8], read: Result<Report, String>) -> Option<Reading> {
match read {
Ok(r) => {
let a = &r.accounting;
let any = !r.records.is_empty()
|| !r.sources.is_empty()
|| a.semantic + a.presentation + a.reported > 0;
any.then_some(Reading::Read(r))
}
Err(e) => {
let text = String::from_utf8_lossy(bytes);
let named = SEMANTIC.iter().any(|n| {
text.match_indices(n).any(|(i, _)| {
let after = text[i + n.len()..].trim_start();
let before = text[..i].trim_end();
after.starts_with('(') && (before.ends_with('=') || before.ends_with('('))
})
});
named.then_some(Reading::Refused(e))
}
}
}
pub fn read(bytes: &[u8], part: &Part) -> Result<Report, String> {
read_part(bytes, part, None)
}
pub fn read_part(bytes: &[u8], part: &Part, chosen: Option<usize>) -> Result<Report, String> {
let bytes = &*crate::model::step_bytes(bytes)?;
let defs = read_part_definitions(bytes).map_err(|e| format!("cannot read the parts: {e}"))?;
read_with(bytes, part, &defs, chosen)
}
fn read_with(
bytes: &[u8],
part: &Part,
defs: &[PartDefinition],
chosen: Option<usize>,
) -> Result<Report, String> {
read_with_metadata(bytes, part, defs, chosen).and_then(|read| read.pmi)
}
struct WithMetadata {
pmi: Result<Report, String>,
bom: Option<crate::bom::Metadata>,
}
fn read_with_metadata(
bytes: &[u8],
part: &Part,
defs: &[PartDefinition],
chosen: Option<usize>,
) -> Result<WithMetadata, String> {
let doc = Document::parse(bytes.to_vec()).map_err(|e| format!("cannot read Part 21: {e}"))?;
let metadata = chosen
.or_else(|| (defs.len() == 1).then_some(0))
.and_then(|i| defs.get(i))
.and_then(|d| crate::bom::read(&doc, std::slice::from_ref(d)).pop());
let report = pmi::read(&doc, defs)
.map_err(|e| e.to_string())
.and_then(|read| report_part(&doc, defs, part, &read, chosen));
Ok(WithMetadata {
pmi: report,
bom: metadata,
})
}
pub fn report(
doc: &Document,
defs: &[PartDefinition],
part: &Part,
read: &pmi::PmiRead,
) -> Result<Report, String> {
report_part(doc, defs, part, read, None)
}
pub fn report_part(
doc: &Document,
defs: &[PartDefinition],
part: &Part,
read: &pmi::PmiRead,
chosen: Option<usize>,
) -> Result<Report, String> {
let drawing = Drawing::new(part, defs, chosen)?;
let drawn = |p: usize| chosen.is_none_or(|k| k == p);
let mut records = Vec::new();
let mut sources = Vec::new();
let mut legacy_presentations: BTreeMap<u64, BTreeSet<String>> = BTreeMap::new();
for (p, (pmi, prov)) in read.parts.iter().zip(&read.provenance.parts).enumerate() {
if !drawn(p) {
continue;
}
let r = PartReader {
doc,
p,
pmi,
prov,
identifiers: &read.identifiers.parts[p],
def: Some(&defs[p]),
drawing: &drawing,
numbers: characteristic_numbers(doc, pmi, prov),
};
r.read(&mut records, &mut sources, &mut legacy_presentations);
}
let mut attached = vec![false; read.findings.len()];
let mut reader_problems = read
.findings
.iter()
.filter(|f| {
f.part.is_none_or(|p| drawn(p.0))
&& (repaired_read(f) || f.kind == pmi::FindingKind::Fact)
})
.map(|f| {
let fact = f.kind == pmi::FindingKind::Fact;
let code = if fact {
"pmi_read_fact"
} else {
"pmi_read_nonconformance"
};
crate::model::Problem {
id: format!("p:{code}:{}:{}", f.ids.first().unwrap_or(&0), f.detail),
code: code.into(),
severity: if fact { "info" } else { "warning" }.into(),
message: if fact {
format!("The STEP reader preserved a PMI statement: {}.", f.detail)
} else {
format!(
"The STEP reader interpreted a nonconforming PMI statement: {}.",
f.detail
)
},
refs: f.ids.iter().map(|id| format!("#{id}")).collect(),
..Default::default()
}
})
.collect::<Vec<_>>();
for record in &records {
if nominal_measured(record) {
let units = if record.kind == "angular" {
"deg"
} else {
"mm"
};
let detail = read.findings.iter().find(|f| {
f.part == Some(pmi::PartId(record.part))
&& f.ids.contains(&record.part21_id)
&& missing_nominal_finding(f)
}).map_or("a dimension without a dimensional_characteristic_representation: no value is stated", |f| f.detail.as_str());
reader_problems.push(crate::model::Problem {
id: format!("p:pmi_read_fact:{}:measured_nominal", record.source_id),
code: "pmi_read_fact".into(),
severity: "info".into(),
message: format!("PMI dimension {}: {detail}. Its nominal {} {} was measured from the referenced geometry; the file states no nominal, and only explicitly stated tolerances are retained.", record.source_id, fmt(record.value.expect("measured nominal"), None), units),
refs: vec![record.source_id.clone(), format!("#{}", record.part21_id)],
..Default::default()
});
}
}
for record in &mut records {
for (i, f) in read.findings.iter().enumerate() {
if repaired_read(f) || f.kind == pmi::FindingKind::Fact {
attached[i] = true;
continue;
}
let on = f.part == Some(pmi::PartId(record.part))
&& f.ids
.first()
.is_some_and(|id| record.instances.binary_search(id).is_ok());
if on {
if nominal_measured(record) && missing_nominal_finding(f) {
attached[i] = true;
continue;
}
if f.detail.contains("more than one id_attribute")
&& !requirement_id_owner(doc, record, f.ids[0])
{
continue;
}
attached[i] = true;
if f.detail.contains("more than one id_attribute") {
record.fields.retain(|(name, _)| name != "id");
record
.fields
.push(("id ambiguity".into(), Field::Text(f.detail.clone())));
continue;
}
record.blockers.push(format!(
"haecceity {} on #{} ({}): {}",
f.kind.as_str(),
f.ids[0],
f.entity,
f.detail
));
}
}
}
for (f, _) in read.findings.iter().zip(&attached).filter(|(_, a)| !**a) {
if f.part.is_some_and(|p| !drawn(p.0)) {
continue;
}
if repaired_read(f) || f.kind == pmi::FindingKind::Fact {
continue;
}
let subject = f.ids.first().copied().unwrap_or(0);
let bom_fact = crate::bom::accounts_for(doc, subject, defs);
let bookkeeping = is_legacy_answers(doc, subject) || bom_fact;
sources.push(Source {
id: format!("finding:#{subject}"),
category: category_of_entity(&f.entity),
entity: f.entity.clone(),
instances: f.ids.clone(),
outcome: if bookkeeping {
Outcome::Extracted
} else {
Outcome::NotExtracted
},
reason: if bom_fact {
"File-stated BOM property or BOM bookkeeping (not a drawing requirement)".into()
} else if bookkeeping {
format!(
"Draftwright stored answers (not a drawing requirement); {}",
f.detail
)
} else {
format!("haecceity {}: {}", f.kind.as_str(), f.detail)
},
});
}
attach_record_geometry(part, &mut records);
records.sort_by_key(|r| (r.category, r.part));
let mut record_sources: Vec<Source> = records
.iter()
.map(|r| Source {
id: r.source_id.clone(),
category: r.category,
entity: entity_name(doc, r.part21_id),
instances: r.instances.clone(),
outcome: if r.blockers.is_empty() {
Outcome::Extracted
} else {
Outcome::PartiallyExtracted
},
reason: if specify_root(doc, r) {
format!("{SPECIFY_WRITTEN} {}", r.blockers.join("; "))
} else if r.blockers.is_empty() && crate::pmi_lowering::no_part_requirement(r) {
"info: no requirement stated; read, with no drawing needed".into()
} else {
r.blockers.join("; ")
},
})
.collect();
record_sources.append(&mut sources);
let materials = read
.parts
.iter()
.zip(&read.provenance.parts)
.enumerate()
.filter(|(p, _)| drawn(*p))
.filter_map(|(p, (pmi, prov))| {
let m = pmi.material.as_ref()?;
let source_id = prov
.material
.iter()
.find(|&&id| entity_name(doc, id) == "property_definition")
.map_or_else(|| format!("material:{p}:0"), |id| format!("material:#{id}"));
Some(Material {
source_id,
part: p,
designation: m.id.clone(),
name: m.name.clone(),
})
})
.collect();
let a = &read.accounting;
let readers: Vec<_> = read
.parts
.iter()
.zip(&read.provenance.parts)
.enumerate()
.map(|(p, (pmi, prov))| PartReader {
doc,
p,
pmi,
prov,
identifiers: &read.identifiers.parts[p],
def: Some(&defs[p]),
drawing: &drawing,
numbers: characteristic_numbers(doc, pmi, prov),
})
.collect();
let callouts = read
.callouts
.iter()
.filter_map(|c| {
let targets = c.links.iter().flat_map(|l| &l.targets).collect::<Vec<_>>();
if !targets.is_empty() && targets.iter().all(|t| !drawn(t.part.0)) {
return None;
}
Some(graphical::Callout {
id: c.id,
name: c.name.clone(),
legacy_sources: legacy_presentations
.get(&c.id)
.map(|s| s.iter().cloned().collect())
.unwrap_or_default(),
links: c
.links
.iter()
.map(|l| graphical::Link {
association: l.association,
definition: l.definition,
entity: l.entity.clone(),
sources: record_sources
.iter()
.filter(|s| {
s.outcome == Outcome::NotExtracted
&& s.instances.first() == Some(&l.definition)
})
.map(|s| s.id.clone())
.collect(),
targets: l
.targets
.iter()
.filter(|t| drawn(t.part.0))
.map(|t| {
let p = t.part.0;
graphical::Target {
part: p,
item: format!("{:?}", t.item),
sources: readers[p].presented_sources(
&t.item,
l.definition,
&records,
&record_sources,
),
}
})
.collect(),
})
.collect(),
})
})
.collect();
Ok(Report {
schema: PMI_SCHEMA.into(),
parts: defs.iter().map(|d| d.name.clone()).collect(),
drawn: chosen,
sources: record_sources,
records,
accounting: Accounting {
semantic: a.semantic,
consumed: a.consumed,
reported: a.reported,
presentation: a.presentation,
validation: a.validation,
},
materials,
reader: Box::new(ReaderEvidence {
problems: reader_problems,
callouts,
}),
spec_problems: Vec::new(),
})
}
fn attach_record_geometry(part: &Part, records: &mut [Record]) {
for r in records.iter_mut() {
r.geometry = match r.category {
Category::GeometricTolerance => Some(tolerance_geometry(part, r)),
Category::Datum => Some(datum_geometry(part, r)),
Category::Dimension => Some(crate::pmi_lowering::dimension_geometry(part, r)),
Category::SurfaceLabel => Some(crate::pmi_lowering::label_geometry(part, r)),
Category::ManufacturingRequirement if crate::pmi_lowering::owned_kind(&r.kind) => {
Some(crate::pmi_lowering::requirement_geometry(part, r))
}
Category::ManufacturingRequirement if r.kind == "surface_finish" => {
Some(finish_geometry(part, r))
}
_ => None,
};
}
for r in records.iter_mut() {
if crate::dims::symbolic_bore(r)
&& r.blockers
== [format!(
"the ISO 286 class {} is stated without limits; they are not computed",
r.fit.as_deref().expect("symbolic class")
)]
{
r.blockers.clear();
}
}
}
#[doc(hidden)]
pub fn from_model(part: &Part, model: &PartPmi) -> Result<Report, String> {
model.validate().map_err(|errors| {
errors
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("; ")
})?;
let doc = Document::parse(b"ISO-10303-21;HEADER;FILE_DESCRIPTION((''),'2;1');FILE_NAME('','','',(''),(''),'','');FILE_SCHEMA(('AP242'));ENDSEC;DATA;ENDSEC;END-ISO-10303-21;".to_vec()).map_err(|e| e.to_string())?;
let drawing = Drawing {
part,
chosen: Some(0),
faces: BTreeMap::new(),
edges: BTreeMap::new(),
};
let prov = PartProvenance::default();
let identifiers = PartIdentifiers::default();
let r = PartReader {
doc: &doc,
p: 0,
pmi: model,
prov: &prov,
identifiers: &identifiers,
def: None,
drawing: &drawing,
numbers: BTreeMap::new(),
};
let mut records = Vec::new();
records.extend((0..model.dimensions.len()).map(|i| r.dimension(DimensionId(i))));
records.extend((0..model.tolerances.len()).map(|i| r.tolerance(i)));
records.extend((0..model.datums.len()).map(|i| r.datum(DatumId(i))));
let mut used = Used {
notes: vec![false; model.notes.len()],
general: vec![false; model.general.len()],
attributes: vec![false; model.attributes.len()],
threads: vec![false; model.threads.len()],
knurls: vec![false; model.knurls.len()],
textures: vec![false; model.surface_textures.len()],
};
records.extend(r.semantic_threads(&mut used));
records.extend(r.semantic_knurls(&mut used, false));
records.extend(r.semantic_textures(&mut used));
for general in &model.general {
let GeneralTolerance::Class { text, .. } = general else {
return Err("caller general tolerance tables are not yet lowered".into());
};
let mut item = r.record(
Category::ManufacturingRequirement,
0,
&[],
Support::default(),
vec![],
);
item.kind = "general_tolerances".into();
item.label = text.clone();
item.fields = vec![("tolerance class".into(), Field::Text(text.clone()))];
records.push(item);
}
for attribute in &model.attributes {
if attribute.name == "semantic text" && attribute.on.is_none() {
let mut item = r.record(
Category::ManufacturingRequirement,
0,
&[],
Support::default(),
vec![],
);
item.kind = "general_note".into();
for (key, value) in &attribute.items {
match (key.as_str(), value) {
("general note", AttributeValue::Text(text)) => item.label = text.clone(),
("note index", AttributeValue::Integer(index)) => item
.fields
.push(("note index".into(), Field::Text(index.to_string()))),
_ => {}
}
}
records.push(item);
}
if attribute.name == "manufacturing process" && attribute.on.is_none() {
let mut item = r.record(
Category::ManufacturingRequirement,
0,
&[],
Support::default(),
vec![],
);
item.kind = "general_note".into();
item.label = attribute
.items
.iter()
.filter_map(|(_, v)| match v {
AttributeValue::Text(text) => Some(format!("PROCESS: {text}")),
_ => None,
})
.collect::<Vec<_>>()
.join("; ");
records.push(item);
}
}
for (index, record) in records.iter_mut().enumerate() {
record.source_id = format!("caller:{}:{index}", category_name(record.category));
}
attach_record_geometry(part, &mut records);
if let Some(why) = records
.iter()
.flat_map(|r| &r.blockers)
.find(|b| b.starts_with(UNRESOLVED))
{
return Err(why.clone());
}
let sources = records
.iter()
.map(|r| Source {
id: r.source_id.clone(),
category: r.category,
entity: "caller PMI".into(),
instances: vec![],
outcome: if r.blockers.is_empty() {
Outcome::Extracted
} else {
Outcome::PartiallyExtracted
},
reason: r.blockers.join("; "),
})
.collect();
let materials = model
.material
.iter()
.map(|m| Material {
source_id: "material:0:0".into(),
part: 0,
designation: m.id.clone(),
name: m.name.clone(),
})
.collect();
Ok(Report {
schema: PMI_SCHEMA.into(),
parts: vec!["part".into()],
drawn: None,
accounting: Accounting {
semantic: records.len(),
consumed: records.len(),
reported: 0,
presentation: 0,
validation: 0,
},
records,
sources,
materials,
reader: Box::default(),
spec_problems: vec![],
})
}
fn repaired_read(f: &pmi::Finding) -> bool {
f.kind == pmi::FindingKind::Nonconformance
&& (matches!(f.detail.as_str(),
"plus/minus deviations were stated reversed; upper and lower bounds swapped (tolerance_value WR1)"
| "dimension limits were stated reversed; upper and lower limits swapped"
| "runout_zone_definition without an orientation angle on a non-runout tolerance; read the explicitly stated zone form without a runout angle")
|| ((f.detail.starts_with("duplicate source identifier ")
|| f.detail.starts_with("empty source identifier "))
&& f.detail.ends_with("retained as identifier metadata, with content-derived JSON ids for empty or repeated item ids")))
}
struct Drawing<'a> {
part: &'a Part,
chosen: Option<usize>,
faces: BTreeMap<u64, Vec<(usize, usize)>>,
edges: BTreeMap<u64, Vec<(usize, usize)>>,
}
impl<'a> Drawing<'a> {
fn new(part: &'a Part, defs: &[PartDefinition], chosen: Option<usize>) -> Result<Self, String> {
let mut faces: BTreeMap<u64, Vec<(usize, usize)>> = BTreeMap::new();
for f in 0..part.faces.len() {
let s = part.face_source(f).ok_or_else(|| {
format!("face {f} of the drawing's part was not read from a file")
})?;
faces.entry(s.entity).or_default().push((s.instance, f));
}
let mut edges: BTreeMap<u64, Vec<(usize, usize)>> = BTreeMap::new();
for e in 0..part.edges.len() {
if let Some(s) = part.edge_source(e) {
edges.entry(s.entity).or_default().push((s.instance, e));
}
}
let counted: usize = match chosen {
Some(k) => defs.get(k).map_or(0, |d| d.faces.len()),
None => defs
.iter()
.map(|d| d.faces.len() * d.placements.len())
.sum(),
};
if counted != part.faces.len() {
return Err(format!(
"the file's parts have {counted} placed faces and the drawing's part {}: they \
were not read from the same file",
part.faces.len()
));
}
Ok(Drawing {
part,
chosen,
faces,
edges,
})
}
fn resolve(
map: &BTreeMap<u64, Vec<(usize, usize)>>,
def: &PartDefinition,
entity: u64,
) -> Vec<usize> {
let placed: BTreeSet<usize> = def
.placements
.iter()
.flat_map(|p| p.instances.iter().copied())
.collect();
map.get(&entity)
.into_iter()
.flatten()
.filter(|(i, _)| placed.contains(i))
.map(|&(_, f)| f)
.collect()
}
}
#[derive(Default)]
struct Support {
faces: BTreeSet<usize>,
face_ids: BTreeSet<u64>,
edges: BTreeSet<usize>,
instances: BTreeSet<u64>,
geometry: BTreeSet<String>,
all_around: bool,
unresolved: Vec<String>,
}
struct Used {
notes: Vec<bool>,
general: Vec<bool>,
attributes: Vec<bool>,
threads: Vec<bool>,
knurls: Vec<bool>,
textures: Vec<bool>,
}
struct Structured {
attr: usize,
pdef: u64,
kind: String,
feature: Option<FeatureId>,
items: BTreeSet<u64>,
fields: Vec<(String, Field)>,
blockers: Vec<String>,
}
struct Presentation {
callouts: Vec<u64>,
items: BTreeSet<u64>,
ambiguous: bool,
reasons: Vec<String>,
}
fn is_draftwright_record(a: &pmi::AttributeSet) -> bool {
let item = match a.name.as_str() {
"pmi-assist answers" | "draftwright editor project" => a.name.as_str(),
"specify characteristic numbers" => "history",
_ => return false,
};
a.on.is_none()
&& matches!(a.items.as_slice(), [(name, AttributeValue::Text(_))] if name == item)
}
fn characteristic_value(a: &pmi::AttributeSet) -> Option<String> {
if a.name != "characteristic number" {
return None;
}
match a.items.as_slice() {
[(name, AttributeValue::Text(n))]
if name == "characteristic number"
&& !n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
&& n.bytes().any(|b| b != b'0') =>
{
Some(n.clone())
}
[(name, AttributeValue::Integer(n))] if name == "characteristic number" && *n > 0 => {
Some(n.to_string())
}
_ => None,
}
}
fn requirement_id_owner(doc: &Document, r: &Record, owner: u64) -> bool {
match r.category {
Category::Datum => {
attributes(doc, owner, "DATUM").is_some() && text_of(doc, owner, "DATUM", 4) == r.label
}
Category::ManufacturingRequirement => match r.kind.as_str() {
"internal_thread" | "external_thread" | "knurl" => {
ref_of(doc, owner, "PRODUCT_DEFINITION_SHAPE", 2) == Some(r.part21_id)
}
"surface_finish" | "surface_texture" => {
text_of(doc, owner, "PROPERTY_DEFINITION", 0) == "surface texture"
}
_ => owner == r.part21_id,
},
_ => owner == r.part21_id,
}
}
fn characteristic_owner(doc: &Document, owner: u64) -> bool {
let supported = |name: &str| {
[
"dimensional_size",
"dimensional_location",
"geometric_tolerance",
"datum_feature",
]
.iter()
.any(|root| haecceity::express::is_a(&name.to_ascii_lowercase(), root))
};
match doc.get(owner) {
Some(RawEntity::Simple { name, .. }) => supported(name),
Some(RawEntity::Complex { parts, .. }) => parts.iter().any(|p| supported(&p.name)),
None => false,
}
}
fn characteristic_numbers(
doc: &Document,
pmi: &PartPmi,
prov: &PartProvenance,
) -> BTreeMap<(Category, u64), BTreeSet<String>> {
let mut numbers: BTreeMap<(Category, u64), BTreeSet<String>> = BTreeMap::new();
for (i, a) in pmi.attributes.iter().enumerate() {
let Some(number) = characteristic_value(a) else {
continue;
};
let category = match a.on {
Some(NoteOwner::Dimension(_)) => Category::Dimension,
Some(NoteOwner::Tolerance(_)) => Category::GeometricTolerance,
Some(NoteOwner::Feature(_)) => Category::Datum,
_ => continue,
};
if let Some(owner) = prov.attributes.get(i).and_then(|ids| {
ids.iter()
.find_map(|&id| ref_of(doc, id, "PROPERTY_DEFINITION", 2))
}) {
numbers.entry((category, owner)).or_default().insert(number);
}
}
numbers
}
fn is_legacy_answers(doc: &Document, id: u64) -> bool {
const NAME: &str = "pmi-assist answers";
if text_of(doc, id, "PROPERTY_DEFINITION", 0) != NAME
|| text_of(doc, id, "PROPERTY_DEFINITION", 1) != "schema 1"
|| !ref_of(doc, id, "PROPERTY_DEFINITION", 2)
.is_some_and(|owner| attributes(doc, owner, "PRODUCT_DEFINITION").is_some())
{
return false;
}
let reps = representations(doc, id);
let [rep] = reps.iter().copied().collect::<Vec<_>>()[..] else {
return false;
};
let items = refs_of(doc, rep, "REPRESENTATION", 1);
matches!(items.as_slice(), [item]
if text_of(doc, *item, "DESCRIPTIVE_REPRESENTATION_ITEM", 0) == NAME
&& matches!(attributes(doc, *item, "DESCRIPTIVE_REPRESENTATION_ITEM"), Some(a) if matches!(a.get(1), Some(Attribute::String(_)))))
}
struct PartReader<'a> {
doc: &'a Document,
p: usize,
pmi: &'a PartPmi,
prov: &'a PartProvenance,
identifiers: &'a PartIdentifiers,
def: Option<&'a PartDefinition>,
drawing: &'a Drawing<'a>,
numbers: BTreeMap<(Category, u64), BTreeSet<String>>,
}
impl PartReader<'_> {
fn presented_sources(
&self,
item: &pmi::PresentedItem,
definition: u64,
records: &[Record],
sources: &[Source],
) -> Vec<String> {
use pmi::PresentedItem as I;
let (kind, index, own) = match item {
I::Dimension(id) => return vec![self.dimension(*id).source_id],
I::Tolerance(id) => return vec![self.tolerance(id.0).source_id],
I::Datum(id) => return vec![self.datum(*id).source_id],
I::Feature(id) => {
let mut ids: Vec<_> = self
.pmi
.datums
.iter()
.enumerate()
.filter(|(_, d)| d.feature() == Some(*id))
.map(|(i, _)| self.datum(DatumId(i)).source_id)
.collect();
ids.extend(
records
.iter()
.filter(|r| {
r.part == self.p
&& (matches!(r.kind.as_str(), "common_label" | "surface_label")
|| r.category == Category::ManufacturingRequirement)
&& (r.part21_id == definition
|| ref_of(self.doc, r.part21_id, "PROPERTY_DEFINITION", 2)
== Some(definition))
})
.map(|r| r.source_id.clone()),
);
ids.sort();
ids.dedup();
return ids;
}
I::Note(i) => ("note", *i, self.prov.notes.get(*i)),
I::Attribute(i) => ("attribute_set", *i, self.prov.attributes.get(*i)),
I::SurfaceTexture(i) => ("surface_texture", *i, self.prov.surface_textures.get(*i)),
I::General(i) => ("general_tolerance", *i, self.prov.general.get(*i)),
I::Thread(i) => ("thread", *i, self.prov.threads.get(*i)),
I::Knurl(i) => ("knurl", *i, self.prov.knurls.get(*i)),
I::DatumTarget(i) => ("datum_target", i.0, self.prov.datum_targets.get(i.0)),
I::Material => {
return vec![self.property(&self.prov.material).map_or_else(
|| format!("material:{}:0", self.p),
|id| format!("material:#{id}"),
)];
}
};
let own = own.map_or(&[][..], Vec::as_slice);
let definition_root = matches!(item, I::Thread(_) | I::Knurl(_) | I::SurfaceTexture(_));
let root = match item {
I::Thread(_) | I::Knurl(_) => own.first().copied(),
I::SurfaceTexture(_) => self
.subject(own, &|n| n == "SURFACE_TEXTURE_REPRESENTATION")
.or_else(|| own.first().copied()),
_ => self.property(own),
};
let mut ids: Vec<_> = records
.iter()
.filter(|r| {
r.part == self.p
&& root.is_some_and(|root| {
if definition_root {
r.part21_id == root
} else {
r.instances.contains(&root)
}
})
})
.map(|r| r.source_id.clone())
.collect();
if let Some(root) = root {
ids.extend(
sources
.iter()
.filter(|s| {
s.id.split_once(":#")
.and_then(|(_, id)| id.parse::<u64>().ok())
== Some(root)
})
.map(|s| s.id.clone()),
);
}
let census = format!("{kind}:{}:{index}", self.p);
if sources.iter().any(|s| s.id == census) {
ids.push(census);
}
ids.sort();
ids.dedup();
ids
}
fn read(
&self,
records: &mut Vec<Record>,
sources: &mut Vec<Source>,
legacy: &mut BTreeMap<u64, BTreeSet<String>>,
) {
for d in 0..self.pmi.dimensions.len() {
self.keep(self.dimension(DimensionId(d)), records, sources);
}
for t in 0..self.pmi.tolerances.len() {
self.keep(self.tolerance(t), records, sources);
}
for d in 0..self.pmi.datums.len() {
self.keep(self.datum(DatumId(d)), records, sources);
}
let mut used = Used {
notes: vec![false; self.pmi.notes.len()],
general: vec![false; self.pmi.general.len()],
attributes: vec![false; self.pmi.attributes.len()],
threads: vec![false; self.pmi.threads.len()],
knurls: vec![false; self.pmi.knurls.len()],
textures: vec![false; self.pmi.surface_textures.len()],
};
for r in self.semantic_knurls(&mut used, true) {
self.keep(r, records, sources);
}
for r in self.semantic_threads(&mut used) {
self.keep(r, records, sources);
}
for r in self.semantic_textures(&mut used) {
self.keep(r, records, sources);
}
for r in self.part_notes(&mut used) {
self.keep(r, records, sources);
}
for r in self.requirements(sources, &mut used, legacy) {
self.keep(r, records, sources);
}
for r in self.labels(sources, &mut used) {
self.keep(r, records, sources);
}
self.not_projected(sources, &used);
}
fn part_notes(&self, used: &mut Used) -> Vec<Record> {
let mut out = Vec::new();
let normalized = |s: &str| {
s.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase()
};
for (i, a) in self.pmi.attributes.iter().enumerate() {
if used.attributes[i] || normalized(&a.name) != "semantic text" {
continue;
}
let notes: Vec<_> = a
.items
.iter()
.filter(|(kind, _)| {
crate::pmi_lowering::part_note_kind(&normalized(kind)).is_some()
|| normalized(kind) == "semantic text"
})
.collect();
if notes.is_empty() {
continue;
}
let ids = self.prov.attributes.get(i).map_or(&[][..], Vec::as_slice);
let Some(pdef) = self.property(ids) else {
continue;
};
used.attributes[i] = true;
let mut blockers = Vec::new();
if notes.len() != 1 {
blockers.push("part semantic text must state one note per attribute set".into());
}
let (kind, value) = notes[0];
let (category, kind, support) = match a.on {
None => (
Category::ManufacturingRequirement,
crate::pmi_lowering::part_note_kind(&normalized(kind))
.unwrap_or("general_note"),
Support::default(),
),
Some(NoteOwner::Feature(f)) => {
(Category::SurfaceLabel, "flag_note", self.support(&[f]))
}
_ => {
blockers.push("semantic text attached to a dimension or tolerance needs an explicit annotation owner".into());
(
Category::ManufacturingRequirement,
"semantic_text",
Support::default(),
)
}
};
let mut r = self.record(category, pdef, ids, support, blockers);
r.kind = kind.into();
if let AttributeValue::Text(text) = value {
r.label = text.clone();
} else {
r.blockers
.push("part semantic text note is not text".into());
}
for (name, value) in &a.items {
let name = normalized(name);
if matches!(name.as_str(), "order" | "index" | "note index") {
let index = match value {
AttributeValue::Text(t) => t.trim().parse::<u64>().ok(),
AttributeValue::Integer(n) => u64::try_from(*n).ok(),
_ => None,
}
.filter(|&n| name != "note index" || n > 0);
if let Some(index) = index {
r.fields
.push(("note order".into(), Field::Text(index.to_string())));
} else {
r.blockers.push(if name == "note index" {
"part note index is not a positive integer".into()
} else {
"part note order/index is not a non-negative integer".into()
});
}
}
}
out.push(r);
}
out
}
fn semantic_knurls(&self, used: &mut Used, confirm_pitch: bool) -> Vec<Record> {
let mut out = Vec::new();
for (index, k) in self.pmi.knurls.iter().enumerate() {
let pattern = match k.pattern {
pmi::KnurlPattern::Straight => "straight",
pmi::KnurlPattern::Diamond => "diamond",
pmi::KnurlPattern::Diagonal => continue,
};
let own = self
.prov
.knurls
.get(index)
.map(Vec::as_slice)
.unwrap_or_default();
let mut r = self.record(
Category::ManufacturingRequirement,
own.first().copied().unwrap_or(0),
own,
self.support(&[k.feature]),
Vec::new(),
);
r.source_id = format!("manufacturing_requirement:#{}", r.part21_id);
r.kind = "knurl".into();
r.label = "knurl".into();
let (pitch, diameter) = (k.diametral_pitch.mm(), k.major_diameter.mm());
r.fields = vec![
("pattern".into(), Field::Text(pattern.into())),
("pitch".into(), Field::Length(pitch)),
("maximum diameter".into(), Field::Length(diameter)),
];
let teeth = std::f64::consts::PI * diameter / pitch;
match k.number_of_teeth {
_ if !confirm_pitch => {}
Some(n) if (teeth - f64::from(n.0)).abs() <= 1.0 => {}
Some(n) => r.blockers.push(format!(
"turned knurl pitch {pitch} and tooth count {} disagree: \
π·{diameter}/{pitch} is {teeth:.1} teeth",
n.0
)),
None => r
.blockers
.push("turned knurl has no tooth count to confirm its pitch".into()),
}
used.knurls[index] = true;
out.push(r);
}
out
}
fn semantic_threads(&self, used: &mut Used) -> Vec<Record> {
let mut out = Vec::new();
for (index, thread) in self.pmi.threads.iter().enumerate() {
if thread.form != "M" {
continue;
}
let side = match thread.side {
pmi::ThreadSide::Internal => "internal",
pmi::ThreadSide::External => "external",
};
let attributes: Vec<_> = self
.pmi
.attributes
.iter()
.enumerate()
.filter(|(_, a)| {
a.name == "thread manufacturing"
&& a.on == Some(NoteOwner::Feature(thread.feature))
})
.collect();
let [(attribute_index, attribute)] = attributes.as_slice() else {
continue;
};
let own = self
.prov
.threads
.get(index)
.map(Vec::as_slice)
.unwrap_or_default();
let mut instances = own.to_vec();
instances.extend(
self.prov
.attributes
.get(*attribute_index)
.into_iter()
.flatten(),
);
instances.sort_unstable();
instances.dedup();
let mut r = self.record(
Category::ManufacturingRequirement,
own.first().copied().unwrap_or(0),
&instances,
self.support(&[thread.feature]),
Vec::new(),
);
r.source_id = format!("manufacturing_requirement:#{}", r.part21_id);
r.kind = format!("{side}_thread");
let designation = thread.qualifier.clone().unwrap_or_default();
r.label = format!("{side} thread");
r.fields = vec![
("thread side".into(), Field::Text(side.into())),
("designation".into(), Field::Text(designation)),
(
"nominal size".into(),
Field::Text(format!("M{}", thread.major_diameter.mm())),
),
("fit class".into(), Field::Text(thread.fit_class.clone())),
(
"hand".into(),
Field::Text(
if thread.hand == pmi::Hand::Left {
"left"
} else {
"right"
}
.into(),
),
),
];
if thread.fit_class.is_empty() {
r.blockers
.push("semantic thread has no stated fit class".into());
}
for (name, value) in &attribute.items {
let value = match value {
AttributeValue::Text(s) => Some(Field::Text(s.clone())),
AttributeValue::Measure(v) => v.as_length().map(|l| Field::Length(l.mm())),
_ => None,
};
if let Some(value) = value {
r.fields.push((name.clone(), value));
}
}
used.threads[index] = true;
used.attributes[*attribute_index] = true;
out.push(r);
}
out
}
fn semantic_textures(&self, used: &mut Used) -> Vec<Record> {
let mut out = Vec::new();
for (index, t) in self.pmi.surface_textures.iter().enumerate() {
let own = self
.prov
.surface_textures
.get(index)
.map(Vec::as_slice)
.unwrap_or_default();
let subject = self
.subject(own, &|n| n == "SURFACE_TEXTURE_REPRESENTATION")
.or_else(|| own.first().copied())
.unwrap_or(0);
let support = t.on.map(|f| self.support(&[f])).unwrap_or_default();
let mut r = self.record(
Category::ManufacturingRequirement,
subject,
own,
support,
Vec::new(),
);
r.source_id = format!("manufacturing_requirement:#{}", r.part21_id);
let stated: Vec<String> = t
.parameters
.iter()
.map(|p| format!("{} {} µm", p.characteristic, fmt_g3(p.value.mm() * 1000.0)))
.collect();
if t.on.is_none() {
r.kind = "surface_texture".into();
r.label = format!("{} unless otherwise specified", stated.join(", "));
} else {
r.kind = "surface_finish".into();
r.label = stated.join(", ");
}
r.fields = std::iter::once((
"material removal".to_string(),
Field::Text(t.material_removal.term().into()),
))
.chain(
t.parameters
.iter()
.map(|p| (p.characteristic.clone(), Field::Length(p.value.mm()))),
)
.collect();
used.textures[index] = true;
out.push(r);
}
out
}
fn identifier(&self, r: &Record) -> Option<&str> {
let p = self.prov;
let i = self.identifiers;
let groups = match r.category {
Category::Dimension if r.kind != "common_label" => vec![(&p.dimensions, &i.dimensions)],
Category::GeometricTolerance => vec![(&p.tolerances, &i.tolerances)],
Category::Datum => {
return self
.pmi
.datums
.iter()
.zip(&i.datums)
.find_map(|(datum, id)| {
(datum.label().as_str() == r.label)
.then_some(id.as_deref())
.flatten()
});
}
Category::ManufacturingRequirement => match r.kind.as_str() {
"internal_thread" | "external_thread" => vec![(&p.threads, &i.threads)],
"knurl" => vec![(&p.knurls, &i.knurls)],
"surface_finish" | "surface_texture" => {
vec![(&p.surface_textures, &i.surface_textures)]
}
_ => vec![
(&p.notes, &i.notes),
(&p.attributes, &i.attributes),
(&p.general, &i.general),
],
},
_ => vec![(&p.attributes, &i.attributes)],
};
groups.into_iter().find_map(|(provenance, identifiers)| {
provenance.iter().zip(identifiers).find_map(|(ids, value)| {
ids.contains(&r.part21_id)
.then_some(value.as_deref())
.flatten()
})
})
}
fn keep(&self, mut record: Record, records: &mut Vec<Record>, sources: &mut Vec<Source>) {
if let Some(id) = self
.identifier(&record)
.filter(|id| crate::characteristics::numeric(id))
{
record.fields.push(("id".into(), Field::Text(id.into())));
}
if matches!(
record.category,
Category::Dimension | Category::GeometricTolerance | Category::Datum
) && let Some(values) = self.numbers.get(&(record.category, record.part21_id))
&& values.len() == 1
&& let Some(number) = values.first()
{
record
.fields
.push(("characteristic number".into(), Field::Text(number.clone())));
}
if let Some(why) = record.blockers.iter().find(|b| b.starts_with(UNRESOLVED))
&& !record
.fields
.iter()
.any(|(k, _)| k == "characteristic number" || k == "id")
{
sources.push(Source {
id: record.source_id.clone(),
category: record.category,
entity: entity_name(self.doc, record.part21_id),
instances: record.instances.clone(),
outcome: Outcome::NotExtracted,
reason: why.clone(),
});
} else {
records.push(record);
}
}
fn not_projected(&self, sources: &mut Vec<Source>, used: &Used) {
let pmi = self.pmi;
let prov = self.prov;
let none: Vec<bool> = Vec::new();
type Group<'g> = (&'g str, Category, usize, &'g [Vec<u64>], &'g [bool]);
let groups: [Group; 9] = [
(
"standard",
Category::Other,
pmi.standards.len(),
&prov.standards,
&none,
),
(
"general_tolerance",
Category::ManufacturingRequirement,
pmi.general.len(),
&prov.general,
&used.general,
),
(
"thread",
Category::ManufacturingRequirement,
pmi.threads.len(),
&prov.threads,
&used.threads,
),
(
"knurl",
Category::ManufacturingRequirement,
pmi.knurls.len(),
&prov.knurls,
&used.knurls,
),
(
"surface_texture",
Category::ManufacturingRequirement,
pmi.surface_textures.len(),
&prov.surface_textures,
&used.textures,
),
(
"note",
Category::ManufacturingRequirement,
pmi.notes.len(),
&prov.notes,
&used.notes,
),
(
"attribute_set",
Category::Other,
pmi.attributes.len(),
&prov.attributes,
&used.attributes,
),
(
"datum_target",
Category::Datum,
pmi.datum_targets.len(),
&prov.datum_targets,
&none,
),
(
"tolerance_relation",
Category::GeometricTolerance,
pmi.tolerance_relations.len(),
&prov.tolerance_relations,
&none,
),
];
for (item, category, n, ids, used) in groups {
for i in (0..n).filter(|&i| !used.get(i).copied().unwrap_or(false)) {
let instances = ids.get(i).cloned().unwrap_or_default();
let bookkeeping = item == "attribute_set"
&& (is_draftwright_record(&pmi.attributes[i])
|| instances.iter().any(|&id| {
crate::bom::accounts_for(
self.doc,
id,
std::slice::from_ref(self.def.expect("file PMI context")),
)
})
|| (pmi.attributes[i].name == "specify pmi origin"
&& matches!(pmi.attributes[i].on, Some(NoteOwner::Dimension(_))))
|| (characteristic_value(&pmi.attributes[i]).is_some()
&& ids.get(i).is_some_and(|instances| {
instances.iter().any(|&id| {
let owner = ref_of(self.doc, id, "PROPERTY_DEFINITION", 2);
owner.is_some_and(|owner| {
[
Category::Dimension,
Category::GeometricTolerance,
Category::Datum,
]
.into_iter()
.any(|category| {
self.numbers
.get(&(category, owner))
.is_some_and(|values| values.len() == 1)
}) && characteristic_owner(self.doc, owner)
})
})
})));
sources.push(Source {
id: format!("{item}:{}:{i}", self.p),
category,
entity: instances
.first()
.map_or_else(String::new, |&id| entity_name(self.doc, id)),
instances,
outcome: if bookkeeping {
Outcome::Extracted
} else {
Outcome::NotExtracted
},
reason: if bookkeeping {
format!(
"Draftwright record {:?} (not a drawing requirement)",
pmi.attributes[i].name
)
} else {
format!("{NOT_PROJECTED} ({})", item.replace('_', " "))
},
});
}
}
if pmi.material.is_some() {
sources.push(Source {
id: format!("material:{}:0", self.p),
category: Category::Other,
entity: prov
.material
.first()
.map_or_else(String::new, |&id| entity_name(self.doc, id)),
instances: prov.material.clone(),
outcome: Outcome::NotExtracted,
reason: format!("{NOT_PROJECTED} (material)"),
});
}
}
fn support(&self, features: &[FeatureId]) -> Support {
let mut s = Support::default();
let mut seen = BTreeSet::new();
let mut todo: Vec<FeatureId> = features.to_vec();
while let Some(f) = todo.pop() {
if !seen.insert(f) {
continue;
}
if let Some(ids) = self.prov.features.get(f.0) {
s.instances.extend(ids);
}
match self.pmi.features.get(f.0) {
Some(Feature::Items(anchors)) => {
for a in anchors {
self.anchor(*a, &mut s);
}
}
Some(Feature::Group { members, kind }) => {
s.all_around |= *kind == GroupKind::AllAround;
todo.extend(members);
}
Some(Feature::Derived { from, geometry, .. }) => {
if geometry.is_none() {
s.unresolved
.push("derived feature has no resolved geometry".into());
}
todo.extend(from);
}
None => s
.unresolved
.push(format!("{UNRESOLVED}: feature {} is not the part's", f.0)),
}
}
s
}
fn target(&self, feature: FeatureId) -> Result<Option<DerivedTarget>, String> {
self.target_inner(feature, &mut BTreeSet::new())
}
fn target_inner(
&self,
feature: FeatureId,
seen: &mut BTreeSet<FeatureId>,
) -> Result<Option<DerivedTarget>, String> {
if !seen.insert(feature) {
return Err("derived target contains a cycle".into());
}
let result = (|| {
let geometry = match self.pmi.features.get(feature.0) {
Some(Feature::Derived {
geometry: Some(id), ..
}) => &self.pmi.derived_geometry[id.0],
Some(Feature::Derived { geometry: None, .. }) => {
return Err("derived feature has no resolved geometry".into());
}
Some(Feature::Group { members, .. }) => {
let targets = members
.iter()
.map(|&m| self.target_inner(m, seen))
.collect::<Result<Vec<_>, _>>()?;
if targets.iter().all(Option::is_none) {
return Ok(None);
}
return match targets.as_slice() {
[one] => Ok(one.clone()),
_ => Err("derived target group has no single axis or plane".into()),
};
}
_ => return Ok(None),
};
let mut support = Support::default();
for &face in &geometry.deriving_faces {
self.anchor(Anchor::Face(face), &mut support);
}
if !support.unresolved.is_empty() {
return Err(support.unresolved.join("; "));
}
let point = geometry.point.each_ref().map(|l| l.mm());
let direction = geometry.direction.0.each_ref().map(|d| d.to_f64());
let (point, direction) = if self.drawing.chosen.is_some() {
(point, direction)
} else {
let [placement] = self.def.expect("file PMI context").placements.as_slice() else {
return Err("derived target has more than one occurrence placement".into());
};
let m = &placement.placement;
let rotate =
|v: [f64; 3]| [0, 1, 2].map(|i| (0..3).map(|j| m[i][j] * v[j]).sum::<f64>());
let p = rotate(point);
([0, 1, 2].map(|i| p[i] + m[i][3]), rotate(direction))
};
Ok(Some(DerivedTarget {
kind: match geometry.kind {
pmi::DerivedGeometryKind::Axis => DerivedKind::Axis,
pmi::DerivedGeometryKind::MedianPlane => DerivedKind::MedianPlane,
},
point,
direction,
radius: geometry.radius.as_ref().map(|r| r.mm()),
faces: support.faces.into_iter().collect(),
}))
})();
seen.remove(&feature);
result
}
fn axis_points(
&self,
feature: FeatureId,
seen: &mut BTreeSet<FeatureId>,
) -> Result<Option<Vec<AxisPoint>>, String> {
if !seen.insert(feature) {
return Err("derived point group contains a cycle".into());
}
let result = (|| {
let geometry = match self.pmi.features.get(feature.0) {
Some(Feature::Group { members, .. }) => {
let mut points = Vec::new();
for &member in members {
let Some(found) = self.axis_points(member, seen)? else {
return Ok(None);
};
points.extend(found);
}
return Ok(Some(points));
}
Some(Feature::Items(_)) => return Ok(Some(Vec::new())),
Some(Feature::Derived { geometry, .. }) => {
let named = self.prov.features.get(feature.0).into_iter().flatten().any(|&id| {
matches!(self.doc.get(id), Some(RawEntity::Simple { name, attributes, .. })
if name == "DERIVED_SHAPE_ASPECT" && matches!(attributes.first(), Some(Attribute::String(n)) if n.trim().eq_ignore_ascii_case("axis point")))
});
if !named {
return Ok(None);
}
&self.pmi.derived_geometry[geometry
.ok_or("axis point has no resolved deriving axis")?
.0]
}
None => return Err("axis point is not the part's feature".into()),
};
let axis = self
.target(feature)?
.ok_or("axis point has no proven deriving axis")?;
if axis.kind != DerivedKind::Axis {
return Err("axis point is not derived from an axis".into());
}
let mut points = Vec::new();
for id in &geometry.supplemental {
let item = &self.pmi.geometry[id.0];
let [(name, attrs)] = item.item.leaves.as_slice() else {
continue;
};
if name != "CARTESIAN_POINT" {
continue;
}
let [
pmi::GeometryValue::Text(_),
pmi::GeometryValue::List(coords),
] = attrs.as_slice()
else {
continue;
};
let factor = item
.length_unit
.as_ref()
.ok_or("axis point has no supplemental length unit")?
.millimetres();
let values: Option<Vec<f64>> = coords
.iter()
.map(|v| match v {
pmi::GeometryValue::Real(v) => Some(v.to_f64() * factor),
pmi::GeometryValue::Integer(v) => Some(*v as f64 * factor),
_ => None,
})
.collect();
let point: [f64; 3] = values
.ok_or("axis point coordinates are not numeric")?
.try_into()
.map_err(|_| "axis point needs three coordinates")?;
if point.iter().any(|v| !v.is_finite()) {
return Err("axis point is not finite".into());
}
let point = if self.drawing.chosen.is_some() {
point
} else {
let [placement] = self
.def
.ok_or("axis point has no source placement")?
.placements
.as_slice()
else {
return Err("axis point has more than one occurrence placement".into());
};
let m = &placement.placement;
[0, 1, 2].map(|i| (0..3).map(|j| m[i][j] * point[j]).sum::<f64>() + m[i][3])
};
let delta = [0, 1, 2].map(|k| point[k] - axis.point[k]);
let t: f64 = (0..3).map(|k| delta[k] * axis.direction[k]).sum();
if (0..3).any(|k| (delta[k] - t * axis.direction[k]).abs() > 1e-6) {
return Err("supplemental axis point is off its deriving axis".into());
}
points.push(AxisPoint {
point,
faces: axis.faces.clone(),
});
}
if points.len() != 1 {
return Err("axis point needs one explicit supplemental point".into());
}
Ok(Some(points))
})();
seen.remove(&feature);
result
}
fn targets(&self, features: &[FeatureId], r: &mut Record) {
let mut axis_point_reasons = Vec::new();
let mut axis_points: Vec<Vec<AxisPoint>> = features
.iter()
.map(|&f| {
if r.kind != "linear" || r.type_code != Some(2) {
return Vec::new();
}
match self.axis_points(f, &mut BTreeSet::new()) {
Ok(points) => points.unwrap_or_default(),
Err(why) => {
axis_point_reasons.push(why);
Vec::new()
}
}
})
.collect();
let targets: Vec<_> = features
.iter()
.enumerate()
.map(|(i, &f)| match self.target(f) {
Ok(t) => t,
Err(_) if !axis_points[i].is_empty() => None,
Err(why) => {
r.blockers.push(why);
None
}
})
.collect();
if axis_points.iter().all(Vec::is_empty) {
axis_points.clear();
}
if targets.iter().any(Option::is_some)
|| !axis_points.is_empty()
|| !axis_point_reasons.is_empty()
{
r.geometry = Some(Geometry {
targets,
axis_points,
axis_point_reasons,
..Geometry::default()
});
}
}
fn anchor(&self, a: Anchor, s: &mut Support) {
if self.def.is_none() {
match a {
Anchor::Face(i) if i.0 < self.drawing.part.faces.len() => {
s.faces.insert(i.0);
}
Anchor::Edge(i) if i.0 < self.drawing.part.edges.len() => {
s.edges.insert(i.0);
}
_ => s.unresolved.push(format!(
"{UNRESOLVED}: caller anchor {a:?} is not on this part"
)),
}
return;
}
let p = self.p;
match a {
Anchor::Face(i) => match self.def.expect("file PMI context").faces.get(i.0) {
Some(&entity) => {
let found = Drawing::resolve(
&self.drawing.faces,
self.def.expect("file PMI context"),
entity,
);
if found.is_empty() {
s.unresolved.push(format!(
"{UNRESOLVED}: face {} of part {p} (#{entity}) is none of the \
drawing's faces",
i.0
));
}
s.faces.extend(found);
s.face_ids.insert(entity);
}
None => s.unresolved.push(format!(
"{UNRESOLVED}: part {p} has no face {} ({} faces)",
i.0,
self.def.expect("file PMI context").faces.len()
)),
},
Anchor::Edge(i) => match self.def.expect("file PMI context").edges.get(i.0) {
Some(&entity) => {
let found = Drawing::resolve(
&self.drawing.edges,
self.def.expect("file PMI context"),
entity,
);
if found.is_empty() {
s.unresolved.push(format!(
"{UNRESOLVED}: edge {} of part {p} (#{entity}) is none of the \
drawing's edges",
i.0
));
}
s.edges.extend(found);
}
None => s.unresolved.push(format!(
"{UNRESOLVED}: part {p} has no edge {} ({} edges)",
i.0,
self.def.expect("file PMI context").edges.len()
)),
},
Anchor::Geometry(g) => {
let entity = self
.pmi
.geometry
.get(g.0)
.map_or_else(|| format!("geometry {}", g.0), |x| x.item.entity());
if let Some(ids) = self.prov.geometry.get(g.0) {
s.instances.extend(ids);
}
s.geometry.insert(entity);
}
}
}
fn record(
&self,
category: Category,
part21_id: u64,
own: &[u64],
support: Support,
mut blockers: Vec<String>,
) -> Record {
let Support {
faces,
face_ids,
edges,
mut instances,
geometry,
unresolved,
..
} = support;
instances.extend(own);
blockers.splice(0..0, unresolved);
if !geometry.is_empty() {
blockers.push(format!(
"applies to supplemental geometry ({}), not only the part's faces and edges",
geometry.into_iter().collect::<Vec<_>>().join(", ")
));
}
let faces: Vec<usize> = faces.into_iter().collect();
let ref_bbox = bbox(self.drawing.part, &faces);
Record {
source_id: format!("{}:#{part21_id}", category_name(category)),
category,
kind: String::new(),
type_code: None,
part: self.p,
part21_id,
value: None,
upper_tol: None,
lower_tol: None,
lower_bound: None,
upper_bound: None,
fit: None,
label: String::new(),
authored_depth_label: None,
datum_refs: Vec::new(),
gtol_modifiers: Vec::new(),
basic: false,
dominant_axis: ref_bbox.map_or("?", dominant).into(),
ref_bbox,
faces,
face_ids: face_ids.into_iter().collect(),
face_groups: Vec::new(),
edge_groups: Vec::new(),
edges: edges.into_iter().collect(),
instances: instances.into_iter().collect(),
blockers,
fields: Vec::new(),
geometry: None,
}
}
fn subject(&self, ids: &[u64], leaves: &dyn Fn(&str) -> bool) -> Option<u64> {
ids.iter().copied().find(|&id| {
self.doc.get(id).is_some_and(|e| match e {
RawEntity::Simple { name, .. } => leaves(name),
RawEntity::Complex { parts, .. } => parts.iter().any(|p| leaves(&p.name)),
})
})
}
fn dimension(&self, id: DimensionId) -> Record {
let d: &Dimension = &self.pmi.dimensions[id.0];
let own = self
.prov
.dimensions
.get(id.0)
.map_or(&[][..], Vec::as_slice);
let part21_id = self
.subject(own, &|n| {
matches!(
n,
"DIMENSIONAL_SIZE"
| "ANGULAR_SIZE"
| "DIMENSIONAL_SIZE_WITH_PATH"
| "DIMENSIONAL_LOCATION"
| "ANGULAR_LOCATION"
| "DIMENSIONAL_LOCATION_WITH_PATH"
| "DIRECTED_DIMENSIONAL_LOCATION"
)
})
.or_else(|| own.first().copied())
.unwrap_or(0);
let mut blockers = Vec::new();
let (groups, kind, code): (Vec<FeatureId>, &str, Option<u32>) = match &d.kind {
DimensionKind::Size {
feature,
kind,
path,
angle,
} => {
if path.is_some() {
blockers.push("the dimension's path is not carried".into());
}
let (k, c) = if angle.is_some() {
("angular", Some(28))
} else {
size_kind(kind)
};
(vec![*feature], k, c)
}
DimensionKind::Location {
from,
to,
kind,
path,
directed,
angle,
} => {
if path.is_some() {
blockers.push("the dimension's path is not carried".into());
}
if *directed {
blockers.push("the dimension's direction (from, to) is not carried".into());
}
let (k, c) = if angle.is_some() {
("angular", Some(11))
} else {
location_kind(kind)
};
(vec![*from, *to], k, c)
}
};
if let DimensionKind::Size {
kind: SizeKind::Other(n),
..
}
| DimensionKind::Location {
kind: LocationKind::Other(n),
angle: None,
..
} = &d.kind
{
blockers.push(format!("dimension kind {n:?} is not one draftwright knows"));
}
if let DimensionKind::Size { angle: Some(a), .. }
| DimensionKind::Location { angle: Some(a), .. } = &d.kind
&& *a != pmi::AngleSelection::Equal
{
blockers.push(format!("the angle selection {a:?} is not carried"));
}
if let Some(q) = &d.qualifier
&& !matches!(
q,
pmi::Qualifier::Maximum | pmi::Qualifier::Minimum | pmi::Qualifier::Average
)
{
blockers.push(format!("the value qualifier {q:?} is not carried"));
}
for m in &d.modifiers {
blockers.push(format!("the dimension modifier {m:?} is not carried"));
}
if let Some(p) = &d.principle {
blockers.push(format!("the tolerance principle {p:?} is not carried"));
}
let face_groups: Vec<Vec<usize>> = groups
.iter()
.map(|g| self.support(&[*g]).faces.into_iter().collect())
.collect();
let edge_groups: Vec<Vec<usize>> = groups
.iter()
.map(|g| self.support(&[*g]).edges.into_iter().collect())
.collect();
let support = self.support(&groups);
let mut r = self.record(Category::Dimension, part21_id, own, support, blockers);
r.kind = kind.into();
r.type_code = code;
r.face_groups = face_groups;
if edge_groups.iter().any(|g| !g.is_empty()) {
r.edge_groups = edge_groups;
}
r.value = d.nominal.as_ref().map(measure);
if d.nominal.is_none() {
r.blockers.push(MISSING_NOMINAL.into());
}
match &d.tolerance {
DimTolerance::None => {}
DimTolerance::Basic => r.basic = true,
DimTolerance::Deviations(b) => {
r.upper_tol = Some(measure(b.upper()));
r.lower_tol = Some(measure(b.lower()));
}
DimTolerance::Limits(b) => {
r.lower_bound = Some(measure(b.lower()));
r.upper_bound = Some(measure(b.upper()));
}
DimTolerance::Fit { class, limits } => {
r.fit = Some(class.to_string());
match limits {
Some(b) => {
r.lower_bound = Some(measure(b.lower()));
r.upper_bound = Some(measure(b.upper()));
}
None => r.blockers.push(format!(
"the ISO 286 class {class} is stated without limits; they are not computed"
)),
}
}
}
r.label = dimension_label(&r, d);
if let Some(suffix) = d.qualifier.as_ref().and_then(|q| match q {
pmi::Qualifier::Maximum => Some("MAX"),
pmi::Qualifier::Minimum => Some("MIN"),
pmi::Qualifier::Average => Some("AVG"),
_ => None,
}) {
r.label += &format!(" {suffix}");
}
let origins: Vec<_> = self
.pmi
.attributes
.iter()
.filter(|a| a.name == "specify pmi origin" && a.on == Some(NoteOwner::Dimension(id)))
.collect();
if let [origin] = origins.as_slice() {
let values: Vec<_> = origin.items.iter().filter(|(k, _)| k == "origin").collect();
if let [(.., AttributeValue::Text(value))] = values.as_slice()
&& matches!(
value.as_str(),
"general_tolerance" | "requirement" | "imported"
)
{
r.fields
.push(("specify origin".into(), Field::Text(value.clone())));
}
}
let mut todo = groups.clone();
let mut seen = BTreeSet::new();
while let Some(feature) = todo.pop() {
if !seen.insert(feature) {
continue;
}
for datum in &self.pmi.datums {
if datum.feature() == Some(feature)
|| datum.feature().is_some_and(|d| {
let reference = self.support(&[feature]);
let datum = self.support(&[d]);
!reference.faces.is_empty()
&& reference.faces == datum.faces
&& reference.edges == datum.edges
})
{
if r.fields.iter().any(|(key, value)| {
key == "reference datum" && *value == Field::Text(datum.label().to_string())
}) {
continue;
}
r.fields.push((
"reference datum".into(),
Field::Text(datum.label().to_string()),
));
}
}
if let Some(Feature::Group { members, .. }) = self.pmi.features.get(feature.0) {
todo.extend(members);
}
}
self.targets(&groups, &mut r);
if !r.basic
&& r.kind == "linear"
&& r.type_code == Some(2)
&& r.blockers.is_empty()
&& r.value.is_some_and(|v| v.is_finite() && v > 0.)
&& let Some(label) = hole_depth_label(d)
&& label != r.label
{
r.authored_depth_label = Some(label);
}
if r.value.is_none() && r.blockers == [MISSING_NOMINAL] {
let geometry = crate::pmi_lowering::dimension_geometry(self.drawing.part, &r);
if let Some(value) = crate::pmi_lowering::measured_value(&r.kind, &geometry) {
r.value = Some(value);
r.blockers.clear();
r.fields.push((
"nominal source".into(),
Field::Text(MEASURED_NOMINAL.into()),
));
r.label = dimension_label(&r, d);
if let Some(suffix) = d.qualifier.as_ref().and_then(|q| match q {
pmi::Qualifier::Maximum => Some("MAX"),
pmi::Qualifier::Minimum => Some("MIN"),
pmi::Qualifier::Average => Some("AVG"),
_ => None,
}) {
r.label += &format!(" {suffix}");
}
}
}
r
}
fn tolerance(&self, t: usize) -> Record {
let g: &GeometricTolerance = &self.pmi.tolerances[t];
let own = self.prov.tolerances.get(t).map_or(&[][..], Vec::as_slice);
let part21_id = self
.subject(own, &|n| {
n == "GEOMETRIC_TOLERANCE"
|| ToleranceKind::of_entity(&n.to_ascii_lowercase()).is_some()
})
.or_else(|| own.first().copied())
.unwrap_or(0);
let mut blockers = Vec::new();
let (features, dimension): (Vec<FeatureId>, Option<DimensionId>) = match &g.target {
ToleranceTarget::Feature(f) => (vec![*f], None),
ToleranceTarget::Dimension(d) => {
(dimension_features(&self.pmi.dimensions[d.0]), Some(*d))
}
ToleranceTarget::Relation {
relating, related, ..
} => (vec![*relating, *related], None),
ToleranceTarget::WholePart => (Vec::new(), None),
};
if let ToleranceTarget::Relation { name, .. } = &g.target {
blockers.push(format!("applies to a shape aspect relationship {name:?}"));
}
let support = self.support(&features);
let all_around = support.all_around;
let mut modifiers: Vec<String> = Vec::new();
if all_around {
modifiers.push("all_around".into());
}
if g.target == ToleranceTarget::WholePart
|| g.auxiliary.contains(&AuxiliaryClassification::AllOver)
{
modifiers.push("all_over".into());
}
let material = |m: &ToleranceModifier| {
matches!(
m,
ToleranceModifier::MaximumMaterialRequirement
| ToleranceModifier::LeastMaterialRequirement
)
};
for m in g.modifiers.iter().filter(|m| !material(m)) {
modifiers.push(m.as_enum().to_ascii_lowercase());
}
if let Some(z) = &g.zone {
if z.form.is_diametral() {
modifiers.push("diameter_zone".into());
} else if z.form.is_spherical() {
modifiers.push("spherical_diameter_zone".into());
}
if z.projected.is_some() {
blockers.push("the projected tolerance zone is not carried".into());
}
if z.non_uniform.is_some() {
blockers.push("the non-uniform tolerance zone is not carried".into());
}
if z.runout_angle.is_some() {
blockers.push("the runout zone angle is not carried".into());
}
if z.affected_plane.is_some() {
blockers.push("the affected plane is not carried".into());
}
}
for m in g.modifiers.iter().filter(|m| material(m)) {
modifiers.push(m.as_enum().to_ascii_lowercase());
}
let mut unique = BTreeSet::new();
modifiers.retain(|m| unique.insert(m.clone()));
if g.unit_basis.is_some() {
blockers.push("the unit-basis (per unit area or length) is not carried".into());
}
if g.maximum.is_some() {
blockers.push("the maximum tolerance value is not carried".into());
}
if g.unequal.is_some() {
blockers.push("the unequally disposed zone value is not carried".into());
}
if g.auxiliary
.contains(&AuxiliaryClassification::UnlessOtherwiseSpecified)
{
blockers.push("the 'unless otherwise specified' classification is not carried".into());
}
let mut datum_refs = Vec::new();
if let Some(system) = &g.datums {
for c in system.compartments() {
if c.references.len() > 1 {
blockers.push(format!(
"a compartment of {} datums (common datum) is carried as separate letters",
c.references.len()
));
}
if !c.modifiers.is_empty() {
blockers.push("datum compartment modifiers are not carried".into());
}
for reference in &c.references {
if !reference.modifiers.is_empty() {
blockers.push("datum reference modifiers are not carried".into());
}
match self.pmi.datums.get(reference.datum.0) {
Some(d) => datum_refs.push(d.label().to_string()),
None => blockers.push(format!(
"{UNRESOLVED}: datum {} is not the part's",
reference.datum.0
)),
}
}
}
}
if self
.pmi
.tolerance_relations
.iter()
.any(|rel| rel.relating.0 == t || rel.related.0 == t)
{
blockers.push(
"it is related to another tolerance (composite, …), which is not carried".into(),
);
}
let mut r = self.record(
Category::GeometricTolerance,
part21_id,
own,
support,
blockers,
);
if let Some(d) = dimension {
r.instances
.extend(self.prov.dimensions.get(d.0).into_iter().flatten());
r.instances.sort_unstable();
r.instances.dedup();
}
let (kind, code) = tolerance_kind(g.kind);
r.kind = kind.into();
r.type_code = Some(code);
r.value = g.magnitude.as_ref().map(measure);
match r.value {
Some(v) => r.label = format!("{kind} {}", fmt_g3(v)),
None => {
r.label = kind.into();
r.blockers.push("the tolerance states no magnitude".into());
}
}
r.datum_refs = datum_refs;
r.gtol_modifiers = modifiers;
self.targets(&features, &mut r);
r.blockers.dedup();
r
}
fn datum(&self, id: DatumId) -> Record {
let d = &self.pmi.datums[id.0];
let own = self.prov.datums.get(id.0).map_or(&[][..], Vec::as_slice);
let mut features: Vec<FeatureId> = d.feature().into_iter().collect();
let mut blockers = Vec::new();
for t in d.targets() {
match self.pmi.datum_targets.get(t.0) {
Some(target) => features.extend(target.on()),
None => blockers.push(format!(
"{UNRESOLVED}: datum target {} is not the part's",
t.0
)),
}
}
if !d.targets().is_empty() {
blockers.push(format!(
"established by {} datum target(s), which are not carried",
d.targets().len()
));
}
let support = self.support(&features);
let feature_ids: Vec<u64> = d
.feature()
.and_then(|f| self.prov.features.get(f.0))
.cloned()
.unwrap_or_default();
let part21_id = self
.subject(&feature_ids, &|n| n == "DATUM_FEATURE")
.or_else(|| self.subject(own, &|n| n == "DATUM_FEATURE"))
.or_else(|| self.subject(own, &|n| n == "DATUM"))
.or_else(|| own.first().copied())
.unwrap_or(0);
let part21_id = if d.feature().is_some()
&& self
.pmi
.datums
.iter()
.filter(|other| other.feature() == d.feature())
.count()
> 1
{
self.subject(own, &|n| n == "DATUM").unwrap_or(part21_id)
} else {
part21_id
};
let mut r = self.record(Category::Datum, part21_id, own, support, blockers);
r.kind = "datum".into();
r.label = d.label().to_string();
r
}
fn property(&self, ids: &[u64]) -> Option<u64> {
self.subject(ids, &|n| n == "PROPERTY_DEFINITION")
}
fn structured(&self, i: usize) -> Option<Structured> {
let a = &self.pmi.attributes[i];
let pdef = self.property(self.prov.attributes.get(i)?)?;
if text_of(self.doc, pdef, "PROPERTY_DEFINITION", 1) != "pmi-assist" {
return None;
}
let kind = a.name.to_lowercase().replace(' ', "_");
let mut blockers = Vec::new();
if !STRUCTURED_KINDS.contains(&kind.as_str()) {
blockers.push("structured manufacturing property kind is unsupported".into());
}
if !user_defined(self.doc, pdef) {
blockers.push(
"structured manufacturing property has no valid user-defined attribute association"
.into(),
);
}
let feature = match a.on {
Some(NoteOwner::Feature(f)) => Some(f),
_ => {
blockers.push("structured manufacturing property has no shape aspect".into());
None
}
};
let doc = self.doc;
let items = ref_of(doc, pdef, "PROPERTY_DEFINITION", 2)
.filter(|&t| attributes(doc, t, "SHAPE_ASPECT").is_some())
.map(|t| aspect_items(doc, t))
.unwrap_or_default();
let reps = representations(doc, pdef);
match reps.iter().collect::<Vec<_>>()[..] {
[&r] => match attributes(doc, r, "REPRESENTATION") {
Some(a) if a.len() >= 2 => {
for item in refs_of(doc, r, "REPRESENTATION", 1) {
if attributes(doc, item, "DESCRIPTIVE_REPRESENTATION_ITEM").is_none()
&& attributes(doc, item, "MEASURE_REPRESENTATION_ITEM").is_none()
{
blockers.push(format!(
"structured representation item #{item} is unsupported"
));
}
}
}
_ => blockers.push("structured manufacturing representation is malformed".into()),
},
_ => blockers.push(format!(
"structured manufacturing property has {} representations",
reps.len()
)),
}
let mut fields = Vec::new();
for (name, v) in &a.items {
let name = name.to_lowercase();
match v {
AttributeValue::Text(t) => fields.push((name, Field::Text(t.clone()))),
AttributeValue::Measure(Value {
quantity: Quantity::Length(l),
..
}) if l.mm().is_finite() && l.mm() > 0.0 => {
fields.push((name, Field::Length(l.mm())));
}
_ => blockers.push(format!(
"structured field {name:?} is neither text nor a positive length"
)),
}
}
let mut names = BTreeSet::new();
if !fields
.iter()
.all(|(n, _)| !n.is_empty() && names.insert(n.clone()))
{
blockers.push("structured manufacturing fields have duplicate or empty names".into());
}
Some(Structured {
attr: i,
pdef,
kind,
feature,
items,
fields,
blockers,
})
}
fn structured_support(&self, st: &Structured, blockers: &mut Vec<String>) -> Support {
let Some(f) = st.feature else {
return Support::default();
};
let s = self.support(&[f]);
if s.faces.is_empty() && s.edges.is_empty() && s.geometry.is_empty() {
blockers.push("structured manufacturing shape aspect has no geometry items".into());
}
s
}
fn presentation(&self, pdef: u64, named: &[(u64, String)]) -> Presentation {
let doc = self.doc;
let semantic = text_of(doc, pdef, "PROPERTY_DEFINITION", 1)
.trim()
.to_lowercase();
let reps = representations(doc, pdef);
let rep = match reps.iter().collect::<Vec<_>>()[..] {
[&r] => text_of(doc, r, "REPRESENTATION", 0).trim().to_lowercase(),
_ => String::new(),
};
let mut matched: Vec<u64> = named
.iter()
.filter(|(_, n)| !rep.is_empty() && n.to_lowercase() == rep)
.map(|&(c, _)| c)
.collect();
if matched.is_empty() {
let words = name_tokens(&semantic);
matched = named
.iter()
.filter(|(_, n)| !words.is_empty() && words.is_subset(&name_tokens(n)))
.map(|&(c, _)| c)
.collect();
}
let mut reasons = Vec::new();
let mut aspects: Vec<u64> = Vec::new();
let mut bare = Vec::new();
for &c in &matched {
let of = callout_aspects(doc, c);
if of.is_empty() {
bare.push(format!("#{c}"));
}
for a in of {
if ref_of(doc, a, "SHAPE_ASPECT", 2)
== Some(self.def.expect("file PMI context").shape)
&& !aspects.contains(&a)
{
aspects.push(a);
}
}
}
let mut items: BTreeSet<u64> = aspects.iter().flat_map(|&a| aspect_items(doc, a)).collect();
let ambiguous =
matches!(semantic.as_str(), "internal thread" | "external thread") && items.len() > 1;
if ambiguous {
reasons.push(AMBIGUOUS_CALLOUTS.to_string());
aspects.clear();
items.clear();
}
if !bare.is_empty() {
reasons.push(format!(
"matched semantic callout(s) have no shape-aspect association: {}",
bare.join(", ")
));
}
let empty: Vec<String> = aspects
.iter()
.filter(|&&a| aspect_items(doc, a).is_empty())
.map(|a| format!("#{a}"))
.collect();
if !empty.is_empty() {
reasons.push(format!(
"associated shape aspect(s) have no representation items: {}",
empty.join(", ")
));
}
Presentation {
callouts: matched,
items,
ambiguous,
reasons,
}
}
fn own_solid(&self, i: u64) -> bool {
["MANIFOLD_SOLID_BREP", "BREP_WITH_VOIDS"].iter().any(|e| {
ref_of(self.doc, i, e, 1).is_some_and(|shell| {
["CLOSED_SHELL", "OPEN_SHELL"].iter().any(|s| {
refs_of(self.doc, shell, s, 1)
.iter()
.any(|&f| self.def.expect("file PMI context").face_index(f).is_some())
})
})
})
}
fn item_support(&self, items: &BTreeSet<u64>) -> Support {
let mut s = Support::default();
for &i in items {
if let Some(f) = self.def.expect("file PMI context").face_index(i) {
self.anchor(Anchor::Face(FaceIndex(f)), &mut s);
} else if let Some(e) = self.def.expect("file PMI context").edge_index(i) {
self.anchor(Anchor::Edge(EdgeIndex(e)), &mut s);
} else if !self.own_solid(i) {
s.unresolved.push(format!(
"{UNRESOLVED}: presented item #{i} is neither a face nor an edge of part {}",
self.p
));
}
}
s
}
fn requirements(
&self,
sources: &mut Vec<Source>,
used: &mut Used,
legacy: &mut BTreeMap<u64, BTreeSet<String>>,
) -> Vec<Record> {
let pmi = self.pmi;
let doc = self.doc;
let structured: Vec<Structured> = (0..pmi.attributes.len())
.filter_map(|i| self.structured(i))
.collect();
for st in &structured {
used.attributes[st.attr] = true;
}
let mut paired = vec![false; structured.len()];
let classes: Vec<usize> = (0..pmi.general.len())
.filter(|&g| matches!(pmi.general[g], GeneralTolerance::Class { .. }))
.collect();
let named: Vec<(u64, String)> = doc
.ids()
.filter(|&c| attributes(doc, c, "DRAUGHTING_CALLOUT").is_some())
.map(|c| {
(
c,
text_of(doc, c, "DRAUGHTING_CALLOUT", 0).trim().to_string(),
)
})
.collect();
let pdefs: Vec<Option<u64>> = (0..pmi.notes.len())
.map(|n| {
let ids = self.prov.notes.get(n).map_or(&[][..], Vec::as_slice);
self.property(ids)
})
.collect();
let shown: Vec<Option<Presentation>> = pdefs
.iter()
.map(|p| p.map(|p| self.presentation(p, &named)))
.collect();
let ambiguous: Vec<Option<Designation>> = pmi
.notes
.iter()
.zip(&shown)
.filter(|(_, s)| s.as_ref().is_some_and(|s| s.ambiguous))
.map(|(n, _)| prose_designation(&n.text))
.collect();
let attribute_ids = |i: usize| self.prov.attributes.get(i).into_iter().flatten();
let mut out = Vec::new();
for (n, note) in pmi.notes.iter().enumerate() {
let ids = self.prov.notes.get(n).map_or(&[][..], Vec::as_slice);
used.notes[n] = true;
let (Some(pdef), Some(shown)) = (pdefs[n], &shown[n]) else {
sources.push(Source {
id: format!("note:{}:{n}", self.p),
category: Category::ManufacturingRequirement,
entity: String::new(),
instances: ids.to_vec(),
outcome: Outcome::NotExtracted,
reason: "manufacturing requirement has no property definition among its \
instances"
.into(),
});
continue;
};
if note.kind.trim().eq_ignore_ascii_case("semantic text") {
let (category, kind, support, blockers) = match note.on {
None => (Category::ManufacturingRequirement, "general_note", Support::default(), Vec::new()),
Some(NoteOwner::Feature(f)) => (Category::SurfaceLabel, "flag_note", self.support(&[f]), Vec::new()),
_ => (Category::ManufacturingRequirement, "semantic_text", Support::default(), vec!["semantic text attached to a dimension or tolerance needs an explicit annotation owner".into()]),
};
let mut r = self.record(category, pdef, ids, support, blockers);
r.kind = kind.into();
r.label = note.text.clone();
out.push(r);
continue;
}
for c in &shown.callouts {
legacy
.entry(*c)
.or_default()
.insert(format!("manufacturing_requirement:#{pdef}"));
}
if note.text.is_empty()
&& crate::pmi_lowering::part_note_kind(¬e.kind.to_lowercase()).is_none()
{
sources.push(Source {
id: format!("manufacturing_requirement:#{pdef}"),
category: Category::ManufacturingRequirement,
entity: entity_name(doc, pdef),
instances: ids.to_vec(),
outcome: Outcome::NotExtracted,
reason: "manufacturing requirement has no authoritative text".into(),
});
continue;
}
let words = note.kind.to_lowercase();
let words: Vec<&str> = words.split_whitespace().collect();
let kind = if let Some(kind) = crate::pmi_lowering::part_note_kind(&words.join(" ")) {
kind.to_string()
} else if words.is_empty() {
"manufacturing_requirement".to_string()
} else {
words.join("_")
};
let mut own = ids.to_vec();
let mut fields = Vec::new();
let mut pair = None;
if kind == "general_tolerances" {
let free: Vec<usize> = classes
.iter()
.copied()
.filter(|&g| !used.general[g])
.collect();
if let [g] = free[..]
&& let GeneralTolerance::Class { text, .. } = &pmi.general[g]
{
used.general[g] = true;
own.extend(self.prov.general.get(g).into_iter().flatten());
fields.push(("tolerance class".into(), Field::Text(text.clone())));
}
} else {
let mut free: Vec<usize> = (0..structured.len())
.filter(|&j| {
!paired[j]
&& structured[j].kind == kind
&& !shown.items.is_empty()
&& shown.items == structured[j].items
})
.collect();
if free.is_empty() && shown.items.is_empty() && shown.ambiguous {
let d = prose_designation(¬e.text);
if d.is_some() && ambiguous.iter().filter(|x| **x == d).count() == 1 {
free = (0..structured.len())
.filter(|&j| {
!paired[j]
&& structured[j].kind == kind
&& structured[j].items.len() == 1
&& structured_designation(&structured[j].fields) == d
})
.collect();
}
}
if let [j] = free[..] {
paired[j] = true;
pair = Some(j);
}
}
let mut blockers: Vec<String> = shown
.reasons
.iter()
.filter(|r| pair.is_none() || r.as_str() != AMBIGUOUS_CALLOUTS)
.cloned()
.collect();
let mut support = self.item_support(&shown.items);
if let Some(j) = pair {
let st = &structured[j];
own.extend(attribute_ids(st.attr));
if shown.items.is_empty() {
support = self.structured_support(st, &mut blockers);
}
blockers.extend(st.blockers.iter().cloned());
fields = st.fields.clone();
}
let mut r = self.record(
Category::ManufacturingRequirement,
pdef,
&own,
support,
blockers,
);
r.kind = kind;
r.label = note.text.clone();
r.fields = fields;
out.push(r);
}
for (j, st) in structured.iter().enumerate() {
if paired[j] {
continue;
}
let mut blockers = Vec::new();
let support = self.structured_support(st, &mut blockers);
blockers.extend(st.blockers.iter().cloned());
let own: Vec<u64> = attribute_ids(st.attr).copied().collect();
let mut r = self.record(
Category::ManufacturingRequirement,
st.pdef,
&own,
support,
blockers,
);
r.kind = st.kind.clone();
r.label = st.kind.replace('_', " ");
r.fields = st.fields.clone();
out.push(r);
}
for &g in &classes {
let GeneralTolerance::Class { text, .. } = &pmi.general[g] else {
continue;
};
if used.general[g] {
continue;
}
used.general[g] = true;
let ids = self.prov.general.get(g).map_or(&[][..], Vec::as_slice);
let Some(pdef) = self.property(ids) else {
sources.push(Source {
id: format!("general_tolerance:{}:{g}", self.p),
category: Category::ManufacturingRequirement,
entity: String::new(),
instances: ids.to_vec(),
outcome: Outcome::NotExtracted,
reason: "general tolerance has no property definition among its instances"
.into(),
});
continue;
};
let mut r = self.record(
Category::ManufacturingRequirement,
pdef,
ids,
Support::default(),
Vec::new(),
);
r.kind = "general_tolerances".into();
r.label = text.clone();
r.fields = vec![("tolerance class".into(), Field::Text(text.clone()))];
out.push(r);
}
out
}
fn labels(&self, sources: &mut Vec<Source>, used: &mut Used) -> Vec<Record> {
let doc = self.doc;
struct Candidate {
attr: usize,
pdef: u64,
surface: bool,
name: String,
text: String,
callouts: usize,
reasons: Vec<String>,
support: Support,
}
let mut candidates = Vec::new();
for (i, a) in self.pmi.attributes.iter().enumerate() {
if used.attributes[i] {
continue;
}
let Some(pdef) = self
.prov
.attributes
.get(i)
.and_then(|ids| self.property(ids))
else {
continue;
};
let Some(aspect) = ref_of(doc, pdef, "PROPERTY_DEFINITION", 2) else {
continue;
};
let surface = attributes(doc, aspect, "SHAPE_ASPECT").is_some()
&& text_of(doc, aspect, "SHAPE_ASPECT", 1) == "NOTE";
let common = !surface
&& a.name.to_lowercase() == "semantic text"
&& COMMON_LABEL_ASPECTS
.iter()
.any(|e| attributes(doc, aspect, e).is_some());
if !surface && !common {
continue;
}
used.attributes[i] = true;
let noun = if surface {
"surface label"
} else {
"common label"
};
let mut reasons = Vec::new();
let reps = representations(doc, pdef).len();
if reps != 1 {
reasons.push(format!("{noun} has {reps} linked representations"));
}
let texts: Vec<(&str, &str)> = a
.items
.iter()
.filter_map(|(k, v)| match v {
AttributeValue::Text(t) => Some((k.as_str(), t.as_str())),
_ => None,
})
.collect();
let (mut name, mut text) = ("", "");
if reps == 1 {
match texts[..] {
[(k, t)] => {
(name, text) = (k, t);
if !surface && name.is_empty() {
reasons.push("common label has no presentation name".into());
}
if text.is_empty() {
reasons.push(format!("{noun} has no authoritative text"));
}
}
_ => reasons.push(format!(
"linked representation has {} descriptive items",
texts.len()
)),
}
}
let shared = callouts(doc, pdef)
.intersection(&callouts(doc, aspect))
.count();
if surface && shared == 0 {
reasons.push("surface label has no shared semantic/presentation callout".into());
} else if !surface && shared != 1 {
reasons.push(format!(
"common label has {shared} shared semantic/presentation callouts"
));
}
let support = match a.on {
Some(NoteOwner::Feature(f)) => self.support(&[f]),
_ => Support::default(),
};
if support.faces.is_empty() && support.edges.is_empty() && support.geometry.is_empty() {
reasons.push(if surface {
"surface label shape aspect has no representation items".into()
} else {
"common-label shape aspect has no representation items".into()
});
}
candidates.push(Candidate {
attr: i,
pdef,
surface,
name: name.to_string(),
text: text.to_string(),
callouts: shared,
reasons,
support,
});
}
let mut named: BTreeMap<String, usize> = BTreeMap::new();
for c in candidates
.iter()
.filter(|c| !c.surface && !c.name.is_empty())
{
*named.entry(c.name.clone()).or_default() += 1;
}
let mut out = Vec::new();
for c in candidates {
let ids = self
.prov
.attributes
.get(c.attr)
.map_or(&[][..], Vec::as_slice);
let refused = if c.surface {
c.text.is_empty().then(|| c.reasons.join("; "))
} else if c.name.is_empty() || c.callouts == 0 {
Some(format!(
"not a common label draftwright reads (no named presentation of it): {}",
c.reasons.join("; ")
))
} else if named[&c.name] > 1 {
Some(format!(
"common-label correspondence is ambiguous for {:?}",
c.name
))
} else {
None
};
if let Some(reason) = refused {
sources.push(Source {
id: format!("attribute_set:{}:{}", self.p, c.attr),
category: if c.surface {
Category::SurfaceLabel
} else {
Category::Other
},
entity: entity_name(doc, c.pdef),
instances: ids.to_vec(),
outcome: Outcome::NotExtracted,
reason,
});
continue;
}
let category = if c.surface {
Category::SurfaceLabel
} else {
Category::Dimension
};
let mut r = self.record(category, c.pdef, ids, c.support, c.reasons);
if c.surface {
r.kind = "surface_label".into();
} else {
r.kind = "common_label".into();
r.type_code = Some(30);
}
r.label = c.text;
out.push(r);
}
out
}
}
const UNRESOLVED: &str = "unresolved";
pub(crate) fn reader_reason(reason: &str) -> String {
reason
.replace(" (haecceity reads it without one)", "")
.replace("haecceity", "the STEP reader")
}
pub(crate) fn public_reason(reason: &str) -> Option<String> {
let reason = reason
.rsplit_once("is not drawn: ")
.map_or(reason, |(_, why)| why);
let reason = reader_reason(reason);
let internal = crate::wording::carries_id(&reason).is_some()
|| [
"spec:",
"features/",
"faces/",
"dimensions/",
"annotations/",
"sheet/",
]
.iter()
.any(|path| reason.contains(path))
|| reason
.as_bytes()
.windows(2)
.any(|pair| pair[0] == b'#' && pair[1].is_ascii_digit());
(!internal).then(|| reason.trim().trim_end_matches('.').to_string())
}
const NOT_PROJECTED: &str = "read by haecceity; not projected to a draftwright record (the port \
projects dimensions, geometric tolerances, datums, manufacturing \
requirements, surface labels and common labels)";
const AMBIGUOUS_CALLOUTS: &str = "thread presentation callouts have multiple distinct supports";
const STRUCTURED_KINDS: [&str; 3] = ["internal_thread", "external_thread", "knurl"];
const COMMON_LABEL_ASPECTS: [&str; 3] = [
"SHAPE_ASPECT",
"DATUM_FEATURE",
"COMPOSITE_GROUP_SHAPE_ASPECT",
];
fn attributes<'d>(doc: &'d Document, id: u64, entity: &str) -> Option<&'d [Attribute]> {
match doc.get(id)? {
RawEntity::Simple {
name, attributes, ..
} => (name == entity).then_some(attributes.as_slice()),
RawEntity::Complex { parts, .. } => parts
.iter()
.find(|p| p.name == entity)
.map(|p| p.attributes.as_slice()),
}
}
fn text_of(doc: &Document, id: u64, entity: &str, k: usize) -> String {
match attributes(doc, id, entity).and_then(|a| a.get(k)) {
Some(Attribute::String(s)) => p21::decode(s).unwrap_or_else(|_| s.clone()),
_ => String::new(),
}
}
fn ref_of(doc: &Document, id: u64, entity: &str, k: usize) -> Option<u64> {
match attributes(doc, id, entity)?.get(k)? {
Attribute::EntityRef(r) => Some(*r),
_ => None,
}
}
fn refs_of(doc: &Document, id: u64, entity: &str, k: usize) -> Vec<u64> {
match attributes(doc, id, entity).and_then(|a| a.get(k)) {
Some(Attribute::EntityRef(r)) => vec![*r],
Some(Attribute::List(items)) => items
.iter()
.filter_map(|a| match a {
Attribute::EntityRef(r) => Some(*r),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
fn callouts(doc: &Document, subject: u64) -> BTreeSet<u64> {
const DMIA: &str = "DRAUGHTING_MODEL_ITEM_ASSOCIATION";
doc.referrers(subject)
.iter()
.filter(|&&a| ref_of(doc, a, DMIA, 2) == Some(subject))
.flat_map(|&a| refs_of(doc, a, DMIA, 4))
.filter(|&c| attributes(doc, c, "DRAUGHTING_CALLOUT").is_some())
.collect()
}
fn callout_aspects(doc: &Document, c: u64) -> Vec<u64> {
const DMIA: &str = "DRAUGHTING_MODEL_ITEM_ASSOCIATION";
let mut out = Vec::new();
for &a in doc.referrers(c) {
if refs_of(doc, a, DMIA, 4).contains(&c)
&& let Some(s) = ref_of(doc, a, DMIA, 2)
&& attributes(doc, s, "SHAPE_ASPECT").is_some()
&& !out.contains(&s)
{
out.push(s);
}
}
out
}
fn aspect_items(doc: &Document, aspect: u64) -> BTreeSet<u64> {
const GISU: &str = "GEOMETRIC_ITEM_SPECIFIC_USAGE";
doc.referrers(aspect)
.iter()
.filter(|&&g| ref_of(doc, g, GISU, 2) == Some(aspect))
.flat_map(|&g| refs_of(doc, g, GISU, 4))
.collect()
}
fn name_tokens(name: &str) -> BTreeSet<String> {
name.to_lowercase()
.replace(['_', '-'], " ")
.split_whitespace()
.filter_map(|raw| {
let mut w: String = raw.chars().filter(|c| c.is_alphanumeric()).collect();
if w.chars().count() > 3 && w.ends_with('s') && !w.ends_with("ss") {
w.pop();
}
(!w.is_empty() && w != "requirement").then_some(w)
})
.collect()
}
fn representations(doc: &Document, pdef: u64) -> BTreeSet<u64> {
const PDR: &str = "PROPERTY_DEFINITION_REPRESENTATION";
doc.referrers(pdef)
.iter()
.filter(|&&r| ref_of(doc, r, PDR, 0) == Some(pdef))
.filter_map(|&r| ref_of(doc, r, PDR, 1))
.collect()
}
fn user_defined(doc: &Document, pdef: u64) -> bool {
const GPA: &str = "GENERAL_PROPERTY_ASSOCIATION";
doc.referrers(pdef).iter().any(|&a| {
ref_of(doc, a, GPA, 3) == Some(pdef)
&& ref_of(doc, a, GPA, 2).is_some_and(|g| {
text_of(doc, g, "GENERAL_PROPERTY", 1).to_lowercase() == "user defined attribute"
})
})
}
#[derive(PartialEq)]
struct Designation(f64, f64, String, &'static str);
fn metric(s: &str) -> Option<(f64, f64, &str)> {
let s = s.strip_prefix(['M', 'm'])?;
let (nominal, rest) = number(s)?;
let rest = rest.trim_start().strip_prefix(['x', 'X'])?.trim_start();
let (pitch, rest) = number(rest)?;
Some((nominal, pitch, rest))
}
fn number(s: &str) -> Option<(f64, &str)> {
let int = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
if int == 0 {
return None;
}
let frac = s[int..]
.strip_prefix('.')
.map(|f| f.find(|c: char| !c.is_ascii_digit()).unwrap_or(f.len()))
.filter(|&n| n > 0)
.map_or(0, |n| n + 1);
let (n, rest) = s.split_at(int + frac);
Some((n.parse().ok()?, rest))
}
fn prose_designation(text: &str) -> Option<Designation> {
let (nominal, pitch, rest) = metric(text.trim())?;
let rest = rest.strip_prefix('-')?;
let end = rest
.find(|c: char| !c.is_ascii_alphanumeric())
.unwrap_or(rest.len());
let (fit, after) = rest.split_at(end);
let rest = after.trim_start();
if fit.is_empty() || rest.len() == after.len() {
return None;
}
let hand = rest.get(..2)?.to_ascii_uppercase();
let bounded = rest[2..]
.chars()
.next()
.is_none_or(|c| !(c.is_alphanumeric() || c == '_'));
let hand = match hand.as_str() {
"RH" if bounded => "RH",
"LH" if bounded => "LH",
_ => return None,
};
Some(Designation(nominal, pitch, fit.to_uppercase(), hand))
}
fn structured_designation(fields: &[(String, Field)]) -> Option<Designation> {
let get = |k: &str| {
fields.iter().find_map(|(n, v)| match v {
Field::Text(t) if n == k => Some(t.as_str()),
_ => None,
})
};
let (nominal, pitch, rest) = metric(get("designation")?)?;
if !rest.is_empty() {
return None;
}
let hand = match get("hand")?.to_lowercase().as_str() {
"rh" | "right" => "RH",
"lh" | "left" => "LH",
_ => return None,
};
Some(Designation(
nominal,
pitch,
get("fit class")?.to_uppercase(),
hand,
))
}
fn category_name(c: Category) -> &'static str {
match c {
Category::Dimension => "dimension",
Category::GeometricTolerance => "geometric_tolerance",
Category::Datum => "datum",
Category::ManufacturingRequirement => "manufacturing_requirement",
Category::SurfaceLabel => "surface_label",
Category::Other => "other",
}
}
fn category_of_entity(entity: &str) -> Category {
let leaves: Vec<&str> = entity.split('+').collect();
let has = |f: &dyn Fn(&str) -> bool| leaves.iter().any(|l| f(l));
if has(&|l| {
l.starts_with("dimensional_")
|| l.starts_with("angular_")
|| l == "directed_dimensional_location"
}) {
Category::Dimension
} else if has(&|l| l.ends_with("_tolerance") || l.starts_with("geometric_tolerance")) {
Category::GeometricTolerance
} else if has(&|l| l.starts_with("datum")) {
Category::Datum
} else {
Category::Other
}
}
fn entity_name(doc: &Document, id: u64) -> String {
match doc.get(id) {
Some(RawEntity::Simple { name, .. }) => name.to_ascii_lowercase(),
Some(RawEntity::Complex { parts, .. }) => parts
.iter()
.map(|p| p.name.to_ascii_lowercase())
.collect::<Vec<_>>()
.join("+"),
None => String::new(),
}
}
fn dimension_features(d: &Dimension) -> Vec<FeatureId> {
match &d.kind {
DimensionKind::Size { feature, .. } => vec![*feature],
DimensionKind::Location { from, to, .. } => vec![*from, *to],
}
}
fn measure(v: &Value) -> f64 {
match &v.quantity {
Quantity::Length(l) => in_mm(l, l.value.stated_places().unwrap_or(usize::MAX)),
Quantity::Angle(a) => match a.unit {
AngleUnit::Degree => a.value.to_f64(),
_ => a.rad().to_degrees(),
},
}
}
fn qualified(v: &Value) -> f64 {
match (&v.quantity, v.decimal_places) {
(Quantity::Length(l), Some(places)) => in_mm(l, usize::from(places)),
_ => measure(v),
}
}
fn in_mm(l: &pmi::Length, places: usize) -> f64 {
let mm = l.unit.millimetres();
let cap = 6 + mm.log10().round().max(0.0) as usize;
let places = places.min(cap);
let round = |x: f64, p: usize| {
let k = 10f64.powi(i32::try_from(p).unwrap_or(9));
(x * k).round() / k
};
round(round(l.value.to_f64(), places) * mm, places + 3)
}
fn size_kind(k: &SizeKind) -> (&'static str, Option<u32>) {
match k {
SizeKind::CurveLength => ("curve_length", Some(14)),
SizeKind::Diameter => ("diameter", Some(15)),
SizeKind::SphericalDiameter => ("diameter", Some(16)),
SizeKind::Radius => ("radius", Some(17)),
SizeKind::SphericalRadius => ("radius", Some(18)),
SizeKind::ToroidalMinorDiameter => ("type19", Some(19)),
SizeKind::ToroidalMajorDiameter => ("type20", Some(20)),
SizeKind::ToroidalMinorRadius => ("type21", Some(21)),
SizeKind::ToroidalMajorRadius => ("type22", Some(22)),
SizeKind::ToroidalHighMajorDiameter => ("type23", Some(23)),
SizeKind::ToroidalLowMajorDiameter => ("type24", Some(24)),
SizeKind::ToroidalHighMajorRadius => ("type25", Some(25)),
SizeKind::ToroidalLowMajorRadius => ("type26", Some(26)),
SizeKind::Thickness => ("thickness", Some(27)),
SizeKind::Other(_) => ("size", None),
}
}
fn location_kind(k: &LocationKind) -> (&'static str, Option<u32>) {
match k {
LocationKind::CurvedDistance => ("curved_dist", Some(1)),
LocationKind::LinearDistance => ("linear", Some(2)),
LocationKind::LinearDistanceCentreOuter => ("linear", Some(3)),
LocationKind::LinearDistanceCentreInner => ("linear", Some(4)),
LocationKind::LinearDistanceOuterCentre => ("linear", Some(5)),
LocationKind::LinearDistanceOuterOuter => ("linear", Some(6)),
LocationKind::LinearDistanceOuterInner => ("linear", Some(7)),
LocationKind::LinearDistanceInnerCentre => ("linear", Some(8)),
LocationKind::LinearDistanceInnerOuter => ("linear", Some(9)),
LocationKind::LinearDistanceInnerInner => ("linear", Some(10)),
LocationKind::LinearDistanceCentre
| LocationKind::LinearDistanceInner
| LocationKind::LinearDistanceOuter => ("linear", None),
LocationKind::Other(_) => ("location", None),
}
}
fn tolerance_kind(k: ToleranceKind) -> (&'static str, u32) {
match k {
ToleranceKind::Angularity => ("angularity", 1),
ToleranceKind::CircularRunout => ("circular_runout", 2),
ToleranceKind::Roundness => ("circularity", 3),
ToleranceKind::Coaxiality => ("coaxiality", 4),
ToleranceKind::Concentricity => ("concentricity", 5),
ToleranceKind::Cylindricity => ("cylindricity", 6),
ToleranceKind::Flatness => ("flatness", 7),
ToleranceKind::Parallelism => ("parallelism", 8),
ToleranceKind::Perpendicularity => ("perpendicularity", 9),
ToleranceKind::Position => ("position", 10),
ToleranceKind::LineProfile => ("profile_line", 11),
ToleranceKind::SurfaceProfile => ("profile_surface", 12),
ToleranceKind::Straightness => ("straightness", 13),
ToleranceKind::Symmetry => ("symmetry", 14),
ToleranceKind::TotalRunout => ("total_runout", 15),
}
}
pub(crate) fn placements_reason(r: &Record) -> Option<String> {
if r.source_id.starts_with("caller:") {
return None;
}
(r.faces.len() > r.face_ids.len()).then(|| {
format!(
"its {} faces are drawn in {} placements of the part; which placement to annotate is \
an open question",
r.face_ids.len(),
r.faces.len().div_ceil(r.face_ids.len().max(1))
)
})
}
fn principal(d: [f64; 3], tolerance: f64) -> Option<usize> {
let c = d.map(f64::abs);
let k = (0..3).fold(0, |k, i| if c[i] > c[k] { i } else { k });
let others = c[0] + c[1] + c[2] - c[k];
(c[k] >= 1e-6 && others <= tolerance * c[k]).then_some(k)
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FaceAttachment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bounds: Option<[f64; 6]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub axis: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub support: Vec<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sites: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub normal: Option<[f64; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exact_axis: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub face_on: Vec<[f64; 3]>,
}
pub(crate) fn face_attachment(part: &Part, f: usize) -> FaceAttachment {
let b = part.face_bounds(f);
let mut out = FaceAttachment {
bounds: Some([b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2]]),
..FaceAttachment::default()
};
let (kind, frame) = match &part.faces[f].surface {
Surface::Plane { frame } => ("plane", frame),
Surface::Cylinder { frame, .. } => ("cylinder", frame),
_ => return out,
};
out.surface = Some(kind.into());
if kind == "cylinder" {
let d = frame.z;
let k = (0..3).fold(0, |k, i| if d[i].abs() > d[k].abs() { i } else { k });
let exact =
(d[k].abs() - 1.0).abs() <= 1e-6 && (0..3).all(|i| i == k || d[i].abs() <= 1e-6);
out.exact_axis = exact.then_some(k);
} else {
out.normal = part.face_normal(f, 0.0, 0.0);
}
let Some(k) = principal(frame.z, 1e-6) else {
return out;
};
let o = frame.origin;
out.axis = Some(k);
out.support = if kind == "plane" {
vec![o[k]]
} else {
(0..3).filter(|&i| i != k).map(|i| o[i]).collect()
};
let found = face_sites(part, f, &b, kind, k);
if let Some(first) = found.first() {
out.sites.push(*first);
out.sites.extend(spread(&found, &b, 8));
} else if kind == "cylinder" {
out.face_on = face_on_sites(part, f, &b, k);
}
out
}
fn face_on_sites(part: &Part, f: usize, b: &Bounds, k: usize) -> Vec<[f64; 3]> {
let surface = &part.faces[f].surface;
let (Surface::Cylinder { frame, radius }, Some(domain)) = (surface, part.domain(f)) else {
return Vec::new();
};
let (depth, toward) = if k == 1 { (0, 1.0) } else { (1, -1.0) };
let lateral = 3 - k - depth;
let mut out = Vec::new();
for t in [0.5, 0.3, 0.7, 0.15, 0.85] {
for edge in [b.min[lateral], b.max[lateral]] {
let offset = 0.5 * (edge - frame.origin[lateral]);
if offset.is_nan() || offset.abs() >= *radius {
continue;
}
let mut s = frame.origin;
s[k] = b.min[k] + t * (b.max[k] - b.min[k]);
s[lateral] += offset;
s[depth] += toward * (radius * radius - offset * offset).sqrt();
if !b.contains(s, 1e-6) {
continue;
}
let Some((u, v)) = surface.parameters(s, None) else {
continue;
};
let p = surface.value(u, v);
let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt();
let facing = part
.face_normal(f, u, v)
.is_some_and(|n| n[depth] * toward > 1e-6);
let clear = (0..part.faces.len()).filter(|g| *g != f).all(|g| {
let o = part.face_bounds(g);
let ahead = if toward > 0.0 {
o.max[depth] > s[depth] + 1e-6
} else {
o.min[depth] < s[depth] - 1e-6
};
!(ahead
&& [k, lateral]
.iter()
.all(|&i| o.min[i] - 1e-6 <= s[i] && s[i] <= o.max[i] + 1e-6))
});
if d <= 1e-6 && domain.contains(u, v) && facing && clear {
out.push(s);
}
}
}
out
}
pub fn face_attachments(part: &Part) -> Vec<FaceAttachment> {
let finite = |v: &[f64]| v.iter().all(|x| x.is_finite());
(0..part.faces.len())
.map(|f| {
let mut a = face_attachment(part, f);
if !a.bounds.is_some_and(|b| finite(&b)) {
a.bounds = None;
}
if !a.sites.iter().all(|s| finite(s))
|| !a.face_on.iter().all(|s| finite(s))
|| !a.support.iter().all(|x| x.is_finite())
{
a.sites.clear();
a.face_on.clear();
a.support.clear();
a.axis = None;
}
if !a.normal.is_none_or(|n| finite(&n)) {
a.normal = None;
}
a
})
.collect()
}
fn att_centre(a: &FaceAttachment) -> [f64; 3] {
a.bounds.map_or([f64::NAN; 3], |b| {
[0, 1, 2].map(|k| 0.5 * (b[k] + b[k + 3]))
})
}
fn tolerance_geometry(part: &Part, r: &Record) -> Geometry {
let faces: Vec<FaceAttachment> = r.faces.iter().map(|&f| face_attachment(part, f)).collect();
let mut g = tolerance_geometry_of(r, &faces);
g.targets = r
.geometry
.as_ref()
.map_or_else(Vec::new, |g| g.targets.clone());
if let [Some(target)] = g.targets.as_slice() {
g.axis = exact_target_axis(target.direction).map(|k| AXIS_NAMES[k].into());
let centre = r
.ref_bbox
.map_or(target.point, |b| [0, 1, 2].map(|k| 0.5 * (b[k] + b[k + 3])));
let t: f64 = (0..3)
.map(|k| (centre[k] - target.point[k]) * target.direction[k])
.sum();
g.sites = vec![match target.kind {
DerivedKind::Axis => [0, 1, 2].map(|k| target.point[k] + t * target.direction[k]),
DerivedKind::MedianPlane => [0, 1, 2].map(|k| centre[k] - t * target.direction[k]),
}];
} else if let [Some(a), Some(b)] = g.targets.as_slice() {
let centre = r
.ref_bbox
.map_or([0.0; 3], |b| [0, 1, 2].map(|k| 0.5 * (b[k] + b[k + 3])));
match crate::pmi_lowering::derived_stations(a, b, centre) {
Ok(points) => {
g.sites = vec![[0, 1, 2].map(|k| 0.5 * (points[0][k] + points[1][k]))];
let direction = if b.kind == DerivedKind::Axis {
b.direction
} else {
a.direction
};
g.axis = exact_target_axis(direction).map(|k| AXIS_NAMES[k].into());
}
Err(why) => g.reasons.push(why.into()),
}
}
g
}
fn exact_target_axis(d: [f64; 3]) -> Option<usize> {
let k = principal(d, 1e-6)?;
((d[k].abs() - 1.0).abs() <= 1e-6).then_some(k)
}
pub(crate) fn tolerance_geometry_of(r: &Record, faces: &[FaceAttachment]) -> Geometry {
let reasons: Vec<String> = placements_reason(r).into_iter().collect();
let mut axes = BTreeSet::new();
let mut cylinders = r.edges.is_empty() && !r.faces.is_empty();
for a in faces {
match a.exact_axis {
Some(k) if a.surface.as_deref() == Some("cylinder") => {
axes.insert(k);
}
_ => cylinders = false,
}
}
let axis = (cylinders && axes.len() == 1)
.then(|| AXIS_NAMES[*axes.first().expect("one axis")].to_string());
Geometry {
sites: Vec::new(),
alternatives: Vec::new(),
axis,
surface: None,
normal: None,
reasons,
..Geometry::default()
}
}
const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"];
fn datum_geometry(part: &Part, r: &Record) -> Geometry {
let faces: Vec<FaceAttachment> = r.faces.iter().map(|&f| face_attachment(part, f)).collect();
datum_geometry_of(r, &faces)
}
pub(crate) fn datum_geometry_of(r: &Record, faces: &[FaceAttachment]) -> Geometry {
let mut reasons: Vec<String> = placements_reason(r).into_iter().collect();
let mut sites = Vec::new();
let mut axes = Vec::new();
let mut kinds = Vec::new();
let mut supports: Vec<Vec<f64>> = Vec::new();
let mut alternatives = Vec::new();
if r.faces.is_empty() {
reasons.push("referenced geometry is unavailable".into());
}
for a in faces {
sites.push(att_centre(a));
let Some(kind) = a.surface.as_deref() else {
reasons.push("one datum reference is neither planar nor cylindrical".into());
continue;
};
let Some(k) = a.axis else {
reasons.push("one datum reference surface is not axis-aligned".into());
continue;
};
supports.push(a.support.clone());
axes.push(k);
kinds.push(kind);
match a.sites.first() {
Some(site) => {
*sites.last_mut().expect("pushed") = *site;
if alternatives.is_empty() && sites.len() == 1 {
alternatives = a.sites[1..].to_vec();
}
}
None => reasons
.push("one datum reference face has no proven interior attachment point".into()),
}
}
let mut axis = None;
if axes.is_empty() {
reasons.push("datum reference surface is unavailable".into());
} else if kinds.iter().any(|k| *k != kinds[0]) {
reasons.push("datum reference faces mix planar and cylindrical surfaces".into());
} else if axes.iter().any(|a| *a != axes[0])
|| supports[1..].iter().any(|s| {
s.iter()
.zip(&supports[0])
.any(|(a, b)| (a - b).abs() > 1e-4)
})
{
let qualifier = if kinds[0] == "plane" {
"coplanar"
} else {
"coaxial"
};
reasons.push(format!("datum reference faces are not {qualifier}"));
} else {
axis = Some(AXIS_NAMES[axes[0]].to_string());
}
let surface =
(!kinds.is_empty() && kinds.iter().all(|k| *k == kinds[0])).then(|| kinds[0].to_string());
let mut normal = None;
if reasons.is_empty() && surface.as_deref() == Some("plane") {
let normals: Vec<[f64; 3]> = faces.iter().filter_map(|a| a.normal).collect();
if normals.len() != r.faces.len() {
reasons.push("datum reference surface has no usable normal".into());
} else if normals[1..]
.iter()
.any(|n| n[0] * normals[0][0] + n[1] * normals[0][1] + n[2] * normals[0][2] < 0.999)
{
reasons.push("datum reference faces disagree about outward normal".into());
} else {
normal = Some(normals[0]);
}
}
reasons.dedup();
Geometry {
sites,
alternatives,
axis,
surface,
normal,
reasons,
..Geometry::default()
}
}
fn finish_geometry(part: &Part, r: &Record) -> Geometry {
let faces: Vec<FaceAttachment> = r.faces.iter().map(|&f| face_attachment(part, f)).collect();
finish_geometry_of(r, &faces)
}
pub(crate) fn finish_geometry_of(r: &Record, faces: &[FaceAttachment]) -> Geometry {
let head_on = faces.iter().all(|a| a.sites.is_empty())
&& faces.iter().any(|a| !a.face_on.is_empty())
&& faces.iter().all(|a| {
a.surface.as_deref() == Some("cylinder")
&& a.exact_axis.is_some()
&& a.exact_axis == faces[0].exact_axis
&& a.support.len() == 2
&& a.support
.iter()
.zip(&faces[0].support)
.all(|(x, y)| (x - y).abs() <= 1e-4)
});
let mut g = if head_on {
let mut seen = r.clone();
let mut used = Vec::new();
seen.faces.clear();
for (f, a) in r.faces.iter().zip(faces) {
if !a.face_on.is_empty() {
seen.faces.push(*f);
used.push(FaceAttachment {
sites: a.face_on.clone(),
..a.clone()
});
}
}
let mut g = datum_geometry_of(&seen, &used);
g.face_on = true;
g
} else {
datum_geometry_of(r, faces)
};
for why in &mut g.reasons {
*why = why.replace("datum reference", "surface finish");
}
g
}
fn face_sites(part: &Part, f: usize, b: &Bounds, kind: &str, k: usize) -> Vec<[f64; 3]> {
let surface = &part.faces[f].surface;
let Some(domain) = part.domain(f) else {
return Vec::new();
};
let centre = b.centre();
if kind == "cylinder" {
let Surface::Cylinder { frame, radius } = surface else {
return Vec::new();
};
let radial = if k < 2 { 2 } else { 0 };
let signs = if k < 2 { [-1.0, 1.0] } else { [1.0, -1.0] };
let mut stations = vec![centre[k]];
if k == 2 {
stations.insert(0, centre[k] + ((b.max[2] - b.min[2]) / 4.0).min(10.0));
}
let on = |station: f64, sign: f64| {
let mut s = frame.origin;
s[k] = station;
s[radial] += sign * radius;
if !b.contains(s, 1e-6) {
return None;
}
let (u, v) = surface.parameters(s, None)?;
let p = surface.value(u, v);
let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt();
let e = 1e-9;
let inside = [(0.0, 0.0), (e, 0.0), (-e, 0.0), (0.0, e), (0.0, -e)]
.iter()
.any(|(du, dv)| domain.contains(u + du, v + dv));
(d <= 1e-6 && inside).then_some(s)
};
let Some((first, sign)) = stations
.iter()
.flat_map(|&st| signs.map(|sg| (st, sg)))
.find_map(|(st, sg)| on(st, sg).map(|s| (s, sg)))
else {
return Vec::new();
};
let mut out = vec![first];
for t in [0.3, 0.7, 0.15, 0.85, 0.05, 0.95] {
if let Some(s) = on(b.min[k] + t * (b.max[k] - b.min[k]), sign) {
out.push(s);
}
}
for station in stations
.into_iter()
.chain([0.3, 0.7, 0.15, 0.85, 0.05, 0.95].map(|t| b.min[k] + t * (b.max[k] - b.min[k])))
{
if let Some(s) = on(station, -sign) {
out.push(s);
}
}
return out;
}
let Some((u0, u1, v0, v1)) = part.uv_bounds(f) else {
return Vec::new();
};
if ![u0, u1, v0, v1].iter().all(|x| x.is_finite()) {
return Vec::new();
}
let hidden = if k == 1 { 0 } else { 1 };
for n in [13usize, 52, 208] {
let mut found: Vec<([f64; 2], [f64; 3])> = Vec::new();
for ui in 0..n {
let u = u0 + (ui as f64 + 0.5) * (u1 - u0) / n as f64;
for vi in 0..n {
let v = v0 + (vi as f64 + 0.5) * (v1 - v0) / n as f64;
if domain.contains(u, v) {
let p = surface.value(u, v);
let key = [
(p[hidden] - centre[hidden]).abs(),
(0..3).map(|i| (p[i] - centre[i]).powi(2)).sum(),
];
found.push((key, p));
}
}
}
if !found.is_empty() {
found.sort_by(|(ka, pa), (kb, pb)| {
ka[0]
.total_cmp(&kb[0])
.then(ka[1].total_cmp(&kb[1]))
.then(pa[0].total_cmp(&pb[0]))
.then(pa[1].total_cmp(&pb[1]))
.then(pa[2].total_cmp(&pb[2]))
});
return found.into_iter().map(|(_, p)| p).collect();
}
}
Vec::new()
}
fn spread(sites: &[[f64; 3]], b: &Bounds, n: usize) -> Vec<[f64; 3]> {
let gap = 0.1 * b.diagonal();
let mut kept: Vec<[f64; 3]> = sites.iter().take(1).copied().collect();
for s in sites.iter().skip(1) {
if kept.len() > n {
break;
}
let far = kept
.iter()
.all(|k| ((0..3).map(|i| (k[i] - s[i]).powi(2)).sum::<f64>()).sqrt() >= gap);
if far {
kept.push(*s);
}
}
kept.split_off(1.min(kept.len()))
}
fn bbox(part: &Part, faces: &[usize]) -> Option<[f64; 6]> {
let mut out: Option<[f64; 6]> = None;
for &f in faces {
let b = part.face_bounds(f);
if !(b.min.iter().chain(&b.max).all(|x| x.is_finite())) {
continue;
}
let o = out.get_or_insert([b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2]]);
for i in 0..3 {
o[i] = o[i].min(b.min[i]);
o[i + 3] = o[i + 3].max(b.max[i]);
}
}
out
}
pub(crate) fn dominant(b: [f64; 6]) -> &'static str {
let spans = [("X", b[3] - b[0]), ("Y", b[4] - b[1]), ("Z", b[5] - b[2])];
let mut best = spans[0];
for s in &spans[1..] {
if s.1.abs() > best.1.abs() {
best = *s;
}
}
if best.1.abs() > 1e-6 { best.0 } else { "?" }
}
fn dimension_label(r: &Record, d: &Dimension) -> String {
let Some(value) = r.value else {
return String::new();
};
let prefix = match (&d.kind, r.kind.as_str()) {
(
DimensionKind::Size {
kind: SizeKind::SphericalDiameter,
..
},
_,
) => "S⌀",
(_, "diameter") => "⌀",
(_, "radius") => "R",
_ => "",
};
if let Some(nominal) = &d.nominal
&& matches!(&nominal.quantity, Quantity::Length(l) if l.unit != LengthUnit::Millimetre)
{
let mm = |v: &Value| fmt_magnitude(qualified(v), None);
return match &d.tolerance {
DimTolerance::Limits(b)
| DimTolerance::Fit {
limits: Some(b), ..
} => format!("{prefix}{} - {prefix}{}", mm(b.lower()), mm(b.upper())),
DimTolerance::Deviations(b) => format!(
"{prefix}{}{}",
mm(nominal),
deviations(qualified(b.upper()), qualified(b.lower()), None)
),
_ => format!("{prefix}{}", mm(nominal)),
};
}
match (r.lower_bound, r.upper_bound, r.upper_tol, r.lower_tol) {
(Some(lo), Some(hi), _, _) => format!(
"{prefix}{} - {prefix}{}",
fmt_magnitude(lo, None),
fmt_magnitude(hi, None)
),
(_, _, Some(up), Some(lo)) => {
format!("{prefix}{}{}", fmt(value, None), deviations(up, lo, None))
}
_ => format!("{prefix}{}", fmt(value, None)),
}
}
fn hole_depth_label(d: &Dimension) -> Option<String> {
let nominal = d.nominal.as_ref()?;
if !matches!(nominal.quantity, Quantity::Length(_)) {
return None;
}
let text = |v: &Value| {
let places = match &v.quantity {
Quantity::Length(l) if l.unit == LengthUnit::Millimetre => {
v.decimal_places.map(usize::from)
}
_ => None,
};
fmt_magnitude(qualified(v), places)
};
let mut label = match &d.tolerance {
DimTolerance::Limits(b) => format!("{} - {}", text(b.lower()), text(b.upper())),
DimTolerance::Deviations(b) => {
let upper = qualified(b.upper());
let lower = qualified(b.lower());
let signed = |v: &Value| {
let n = qualified(v);
if n == 0. && v.decimal_places.is_none() {
return "0".into();
}
let sign = if n > 0. { "+" } else { "" };
format!("{sign}{}", text(v))
};
if upper > 1e-9 && upper == -lower {
format!("{} ±{}", text(nominal), text(b.upper()))
} else {
format!(
"{} {}/{}",
text(nominal),
signed(b.upper()),
signed(b.lower())
)
}
}
DimTolerance::Fit { .. } => return None,
_ => text(nominal),
};
if let Some(suffix) = d.qualifier.as_ref().and_then(|q| match q {
pmi::Qualifier::Maximum => Some("MAX"),
pmi::Qualifier::Minimum => Some("MIN"),
pmi::Qualifier::Average => Some("AVG"),
_ => None,
}) {
label += &format!(" {suffix}");
}
Some(label)
}
fn deviations(upper: f64, lower: f64, places: Option<usize>) -> String {
let signed = |v: f64| {
let sign = if v < 0.0 { "-" } else { "+" };
format!("{sign}{}", fmt_magnitude(v.abs(), places))
};
if upper > 1e-9 && upper == -lower {
format!(" ±{}", fmt_magnitude(upper, places))
} else if lower.abs() <= 1e-9 {
format!(" {}/0", signed(upper))
} else if upper.abs() <= 1e-9 {
format!(" 0/{}", signed(lower))
} else {
format!(" {}/{}", signed(upper), signed(lower))
}
}
pub fn fmt(v: f64, decimals: Option<usize>) -> String {
match decimals {
Some(d) => {
let s = format!("{v:.d$}");
if s.trim_start_matches('-')
.chars()
.all(|c| c == '0' || c == '.')
{
format!("{:.d$}", 0.0)
} else {
s
}
}
None => {
if crate::nominal::comparison() {
return crate::nominal::format(v);
}
let v = (v * 1e6).round() / 1e6;
for places in 0..=3 {
let text = format!("{v:.places$}");
if places == 3
|| text
.parse::<f64>()
.is_ok_and(|n| (n - v).abs() <= 1e-6 + 1e-12)
{
if places == 3
&& text
.parse::<f64>()
.is_ok_and(|n| (n - v).abs() > 1e-6 + 1e-12)
{
return if text.parse::<f64>() == Ok(0.) {
"0.000".into()
} else {
text
};
}
let text = if places == 0 {
text.as_str()
} else {
text.trim_end_matches('0').trim_end_matches('.')
};
return if text == "-0" {
"0".into()
} else {
text.into()
};
}
}
unreachable!()
}
}
}
pub fn fmt_magnitude(v: f64, decimals: Option<usize>) -> String {
match decimals {
Some(d) => round_decimal(&format!("{v}"), d),
None if v == 0.0 => format!("{v:.1}"),
None => {
let sci = format!("{v:.12e}");
plain(&sci)
}
}
}
pub fn fmt_g3(v: f64) -> String {
if v == 0.0 {
return "0".into();
}
let sci = format!("{v:.2e}");
let (mantissa, exp) = sci.split_once('e').expect("exponent");
let exp: i32 = exp.parse().expect("exponent");
if !(-4..3).contains(&exp) {
let m = mantissa.trim_end_matches('0').trim_end_matches('.');
let sign = if exp < 0 { '-' } else { '+' };
return format!("{m}e{sign}{:02}", exp.abs());
}
let places = usize::try_from(2 - exp).unwrap_or(0);
let s = format!("{v:.places$}");
if s.contains('.') {
s.trim_end_matches('0').trim_end_matches('.').into()
} else {
s
}
}
fn plain(sci: &str) -> String {
let (mantissa, exp) = sci.split_once('e').expect("exponent");
let exp: i64 = exp.parse().expect("exponent");
let negative = mantissa.starts_with('-');
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
let point = 1 + exp;
let mut s = if point <= 0 {
format!(
"0.{}{digits}",
"0".repeat(usize::try_from(-point).unwrap_or(0))
)
} else if usize::try_from(point).unwrap_or(0) >= digits.len() {
format!(
"{digits}{}",
"0".repeat(usize::try_from(point).unwrap_or(0) - digits.len())
)
} else {
let p = usize::try_from(point).unwrap_or(0);
format!("{}.{}", &digits[..p], &digits[p..])
};
if s.contains('.') {
s = s.trim_end_matches('0').trim_end_matches('.').to_string();
}
let s = s.trim_start_matches('0');
let s = if s.is_empty() || s.starts_with('.') {
format!("0{s}")
} else {
s.to_string()
};
if negative { format!("-{s}") } else { s }
}
fn round_decimal(text: &str, d: usize) -> String {
let negative = text.starts_with('-');
let body = text.trim_start_matches('-');
let (int, frac) = body.split_once('.').unwrap_or((body, ""));
let mut digits: Vec<u8> = int.bytes().chain(frac.bytes()).map(|b| b - b'0').collect();
let keep = int.len() + d;
if digits.len() < keep {
digits.resize(keep, 0);
}
let rest = digits.split_off(keep);
let up = match rest.first() {
Some(&r) if r > 5 => true,
Some(&5) => rest[1..].iter().any(|&x| x > 0) || digits.last().is_some_and(|x| x % 2 == 1),
_ => false,
};
if up {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, 1);
break;
}
i -= 1;
if digits[i] == 9 {
digits[i] = 0;
} else {
digits[i] += 1;
break;
}
}
}
let n_int = digits.len() - d;
let int: String = digits[..n_int]
.iter()
.map(|x| char::from(b'0' + x))
.collect();
let frac: String = digits[n_int..]
.iter()
.map(|x| char::from(b'0' + x))
.collect();
let sign = if negative && digits.iter().any(|&x| x > 0) {
"-"
} else {
""
};
if d == 0 {
format!("{sign}{int}")
} else {
format!("{sign}{int}.{frac}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caller_surface_texture_uses_the_ap242_lowering_and_rejects_foreign_faces() {
let bytes = crate::model::read_step_file(std::path::Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/surface_texture/plate_face_ra0_8.step.gz"
)))
.unwrap();
let part = haecceity::read_step(&bytes).unwrap();
let defs = haecceity::step::read_part_definitions(&bytes).unwrap();
let doc = Document::parse(bytes).unwrap();
let read = pmi::read(&doc, &defs).unwrap();
let mut model = read.parts[0].clone();
let imported = report(&doc, &defs, &part, &read).unwrap();
let caller = from_model(&part, &model).unwrap();
let signature = |report: &Report| {
report
.records
.iter()
.filter(|r| r.kind == "surface_finish")
.map(|r| {
(
r.kind.clone(),
r.label.clone(),
r.faces.clone(),
r.fields.clone(),
r.geometry.clone(),
)
})
.collect::<Vec<_>>()
};
assert!(!signature(&imported).is_empty());
assert_eq!(signature(&caller), signature(&imported));
let feature = pmi::FeatureId(model.features.len());
model
.features
.push(pmi::Feature::Items(vec![pmi::Anchor::Face(
pmi::FaceIndex(part.faces.len()),
)]));
model.surface_textures[0].on = Some(feature);
assert!(
from_model(&part, &model)
.unwrap_err()
.contains("caller anchor")
);
}
#[test]
fn caller_knurls_use_the_same_typed_conversion_as_ap242() {
for fixture in ["spindle_turned_knurl", "spindle_diamond_knurl"] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join(format!("tests/fixtures/turned_knurl/{fixture}.step.gz"));
let bytes = crate::model::read_step_file(&path).unwrap();
let part = haecceity::read_step(&bytes).unwrap();
let defs = haecceity::step::read_part_definitions(&bytes).unwrap();
let doc = Document::parse(bytes).unwrap();
let read = pmi::read(&doc, &defs).unwrap();
let imported = report(&doc, &defs, &part, &read).unwrap();
let caller = from_model(&part, &read.parts[0]).unwrap();
let signature = |report: &Report| {
report
.records
.iter()
.filter(|r| r.kind == "knurl")
.map(|r| {
(
r.label.clone(),
r.faces.clone(),
r.fields.clone(),
r.blockers.clone(),
r.geometry.clone(),
)
})
.collect::<Vec<_>>()
};
assert_eq!(signature(&caller).len(), 1, "{fixture}");
assert_eq!(signature(&caller), signature(&imported), "{fixture}");
}
}
#[test]
fn numbers_format_as_draftwright_formats_them() {
assert_eq!(fmt(35.0, None), "35");
assert_eq!(fmt(3.175, None), "3.175");
assert_eq!(fmt(0.25, Some(3)), "0.250");
assert_eq!(fmt(-0.0001, Some(2)), "0.00");
assert_eq!(fmt_magnitude(0.508, None), "0.508");
assert_eq!(fmt_magnitude(0.30000000000000004, None), "0.3");
assert_eq!(fmt_magnitude(100.0, None), "100");
assert_eq!(fmt_magnitude(0.0254, None), "0.0254");
assert_eq!(fmt_magnitude(0.02, Some(2)), "0.02");
assert_eq!(fmt_magnitude(0.125, Some(2)), "0.12");
assert_eq!(fmt_magnitude(0.135, Some(2)), "0.14");
assert_eq!(fmt_magnitude(9.995, Some(2)), "10.00");
assert_eq!(fmt_g3(0.381), "0.381");
assert_eq!(fmt_g3(1.016), "1.02");
assert_eq!(fmt_g3(0.38099999999999995), "0.381");
assert_eq!(fmt_g3(0.75), "0.75");
assert_eq!(fmt_g3(100.0), "100");
assert_eq!(fmt_g3(1234.0), "1.23e+03");
assert_eq!(fmt_g3(0.00001), "1e-05");
}
#[test]
fn converted_lengths_drop_the_writers_float_noise() {
let inch = |text: &str| {
measure(&Value::length(
pmi::Decimal::parse(text).unwrap(),
LengthUnit::Inch,
))
};
assert_eq!(fmt_magnitude(inch("0.01500000000006"), None), "0.381");
assert_eq!(fmt_magnitude(inch("0.06000000000024"), None), "1.524");
assert_eq!(fmt_magnitude(inch("0.016"), None), "0.4064");
assert_eq!(fmt_magnitude(inch("0.0001"), None), "0.00254");
assert_eq!(fmt_magnitude(inch("12.00"), None), "304.8");
let mm = Value::length(pmi::Decimal::parse("0.3").unwrap(), LengthUnit::Millimetre);
assert_eq!(measure(&mm), 0.3);
let metre = |text: &str| {
measure(&Value::length(
pmi::Decimal::parse(text).unwrap(),
LengthUnit::Metre,
))
};
assert_eq!(fmt_magnitude(metre("0.0000025"), None), "0.0025");
assert_eq!(fmt_magnitude(metre("2.5E-6"), None), "0.0025");
}
#[test]
fn deviations_keep_their_signs() {
assert_eq!(deviations(0.5, -0.5, None), " ±0.5");
assert_eq!(deviations(0.0, -0.2, None), " 0/-0.2");
assert_eq!(deviations(0.2, 0.0, None), " +0.2/0");
assert_eq!(deviations(0.05, -0.1, None), " +0.05/-0.1");
assert_eq!(deviations(-0.009, -0.025, None), " -0.009/-0.025");
}
#[test]
fn entities_fall_in_draftwright_categories() {
assert_eq!(category_of_entity("dimensional_size"), Category::Dimension);
assert_eq!(
category_of_entity(
"geometric_tolerance+geometric_tolerance_with_datum_reference+position_tolerance"
),
Category::GeometricTolerance
);
assert_eq!(category_of_entity("datum_feature"), Category::Datum);
assert_eq!(category_of_entity("shape_aspect"), Category::Other);
}
}