use std::collections::BTreeMap;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use crate::layout::FRAME;
use crate::model::{Invalid, Problem};
use crate::output::Curve;
use crate::text::{Font, Laid, P, Segment};
pub(crate) fn default_number(analysis: &crate::model::Analysis) -> String {
let leading_number = |name: &str| {
let token = name
.trim_start()
.split(|c: char| !c.is_ascii_alphanumeric() && c != '-')
.next()
.unwrap_or_default();
(token.bytes().any(|c| c.is_ascii_digit())
&& token.split('-').all(|segment| !segment.is_empty()))
.then(|| token.to_string())
};
analysis
.product_name
.as_deref()
.and_then(leading_number)
.or_else(|| {
leading_number(
analysis
.source_stem
.as_deref()
.unwrap_or(&analysis.binding.part),
)
})
.unwrap_or_else(|| "DWG-001".into())
}
pub(crate) fn default_title(analysis: &crate::model::Analysis) -> String {
let meaningful = |name: &str| {
let compact: String = name
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect();
!compact.is_empty()
&& ![
"part", "body", "solid", "compound", "shape", "object", "model", "unnamed",
]
.iter()
.any(|prefix| {
compact
.strip_prefix(prefix)
.is_some_and(|suffix| suffix.chars().all(|c| c.is_ascii_digit()))
})
};
let name = analysis
.product_name
.as_deref()
.filter(|name| meaningful(name))
.unwrap_or(
analysis
.source_stem
.as_deref()
.unwrap_or(&analysis.binding.part),
);
name.replace(['_', '-'], " ")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_uppercase()
}
pub const FONT: &str = "IBMPlexSansCondensed-Regular.ttf";
pub const FONT_DATA: &[u8] = include_bytes!("../fonts/IBMPlexSansCondensed-Regular.ttf");
pub const ROW_H: f64 = 8.0;
pub const TEXT: f64 = 3.0;
pub const LABEL_TEXT: f64 = 1.5;
pub const LABEL_PAD: f64 = 0.8;
pub const MIN_TEXT: f64 = 1.8;
const FURNITURE_GAP: f64 = 3.0;
const PROJECTION_BAND_W: f64 = 16.0;
pub const PROJECTION_LINE: f64 = 0.15;
pub struct Cell {
pub field: &'static str,
pub width: f64,
pub label: &'static str,
}
const fn cell(field: &'static str, width: f64, label: &'static str) -> Cell {
Cell {
field,
width,
label,
}
}
pub const ROWS: [&[Cell]; 4] = [
&[
cell("legal_owner", 0.70, "LEGAL OWNER"),
cell("document_type", 0.30, "DOC. TYPE"),
],
&[
cell("title", 0.70, "TITLE"),
cell("drawing_number", 0.30, "DWG NO."),
],
&[
cell("material", 0.35, "MATERIAL"),
cell("general_tolerance", 0.35, "GEN. TOL."),
cell("units", 0.18, "UNITS"),
cell("format", 0.12, "FORMAT"),
],
&[
cell("designed_by", 0.35, "DRAWN BY"),
cell("approved_by", 0.35, "APPROVED BY"),
cell("date", 0.18, "DATE"),
cell("revision", 0.06, "REV"),
cell("sheet", 0.06, "SHEET"),
],
];
pub const KEYS: [(&str, &str); 11] = [
("title", "title"),
("number", "drawing_number"),
("material", "material"),
("tolerance", "general_tolerance"),
("drawn_by", "designed_by"),
("approved_by", "approved_by"),
("date", "date"),
("revision", "revision"),
("sheet", "sheet"),
("company", "legal_owner"),
("document_type", "document_type"),
];
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TitleCell {
pub field: String,
pub label: String,
#[serde(rename = "box")]
pub cell: [f64; 4],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
pub fn font() -> &'static Font {
static FONT: OnceLock<Font> = OnceLock::new();
FONT.get_or_init(|| Font::new(FONT_DATA.to_vec()).expect("the bundled font parses"))
}
pub fn check(title: &BTreeMap<String, String>) -> Result<(), Invalid> {
match title.keys().find(|k| !KEYS.iter().any(|(key, _)| key == k)) {
None => Ok(()),
Some(k) => Err(Invalid {
path: None,
also: Vec::new(),
message: format!(
"The title block has no cell for sheet/title/{k}, so it would not be drawn."
),
choices: KEYS.iter().map(|(key, _)| key.to_string()).collect(),
}),
}
}
pub fn ink(value: &str) -> String {
value.replace('⌀', "ø")
}
pub fn lay(value: &str, size: f64) -> Laid {
let value = ink(value);
if !value.contains('\n') {
return font().text(&value, size);
}
let face = ttf_parser::Face::parse(FONT_DATA, 0).expect("the bundled font parses");
let pitch = (face.ascender() as f64 - face.descender() as f64 + face.line_gap() as f64) * size
/ face.units_per_em() as f64;
let moved = |s: &Segment, d: P| {
let m = |p: P| [p[0] + d[0], p[1] + d[1]];
match *s {
Segment::Line(a, b) => Segment::Line(m(a), m(b)),
Segment::Quad(a, b, c) => Segment::Quad(m(a), m(b), m(c)),
Segment::Cubic(a, b, c, d) => Segment::Cubic(m(a), m(b), m(c), m(d)),
}
};
let mut lines = Vec::new();
for (row, line) in value.split('\n').enumerate() {
let laid = font().baseline(line, size);
let d = [-0.5 * font().advance(line, size), -(row as f64) * pitch];
lines.push((laid, d));
}
let (mut min, mut max) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
for (laid, d) in lines.iter().filter(|(l, _)| !l.contours.is_empty()) {
for k in 0..2 {
min[k] = min[k].min(laid.min[k] + d[k]);
max[k] = max[k].max(laid.max[k] + d[k]);
}
}
if min[0] > max[0] {
return font().text("", size);
}
let centre = [0.5 * (min[0] + max[0]), 0.5 * (min[1] + max[1])];
let contours = lines
.iter()
.flat_map(|(laid, d)| {
let d = [d[0] - centre[0], d[1] - centre[1]];
laid.contours
.iter()
.map(move |c| c.iter().map(|s| moved(s, d)).collect())
})
.collect();
let half = [0.5 * (max[0] - min[0]), 0.5 * (max[1] - min[1])];
Laid {
contours,
min: [-half[0], -half[1]],
max: half,
}
}
pub fn measure(value: &str) -> [f64; 2] {
let laid = lay(value, TEXT);
[laid.max[0] - laid.min[0], laid.max[1] - laid.min[1]]
}
pub fn value_size(value: &str, cell: [f64; 4]) -> f64 {
let [w, h] = measure(value);
let (cw, ch) = (cell[2] - cell[0], cell[3] - cell[1]);
if w <= cw + 1e-9 && h <= ch + 1e-9 {
return TEXT;
}
let room = ((cw - 2.0 * LABEL_PAD) / w).min((ch - 2.0 * LABEL_PAD) / h);
(TEXT * room).clamp(MIN_TEXT, TEXT)
}
pub fn cells(block: [f64; 4], title: &BTreeMap<String, String>, size: &str) -> Vec<TitleCell> {
let [x0, y0, x1, _] = block;
let width = x1 - x0;
let value = |field: &str| -> Option<String> {
if field == "designed_by" {
let author = title.get("drawn_by").map_or("", String::as_str);
return Some(attribution(author));
}
let v = match field {
"units" => "mm",
"format" => size,
_ => {
let key = KEYS.iter().find(|(_, f)| *f == field)?.0;
title.get(key)?.as_str()
}
};
let v = v.trim();
(!v.is_empty()).then(|| v.to_string())
};
let mut out = Vec::new();
for (i, row) in ROWS.iter().enumerate() {
let bottom = y0 + (ROWS.len() - 1 - i) as f64 * ROW_H;
let mut left = 0.0;
for (j, c) in row.iter().enumerate() {
let right = if j + 1 == row.len() {
width
} else {
left + c.width * width
};
out.push(TitleCell {
field: c.field.into(),
label: c.label.into(),
cell: [x0 + left, bottom, x0 + right, bottom + ROW_H],
value: value(c.field),
});
left = right;
}
}
out
}
pub fn attribution(author: &str) -> String {
let author = author.trim();
if author.is_empty() {
"draftwright".into()
} else {
format!("{author} / draftwright")
}
}
pub fn top(block: [f64; 4]) -> f64 {
block[1] + ROWS.len() as f64 * ROW_H
}
pub fn scale_note(block: [f64; 4], text: &str) -> [f64; 2] {
let laid = lay(text, TEXT);
let (w, h) = (laid.max[0] - laid.min[0], laid.max[1] - laid.min[1]);
let right = block[2] - 3.0 - PROJECTION_BAND_W;
[right - w / 2.0, top(block) + FURNITURE_GAP + h / 2.0]
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectionPlaced {
pub method: String,
pub curves: Vec<Curve>,
}
pub fn projection(block: [f64; 4], first_angle: bool) -> ProjectionPlaced {
let h = TEXT;
let (big, small, len) = (0.5 * h, 0.3 * h, 1.3 * h);
let (left, right) = (small, big);
let far = len + 0.5 * h + big;
let end = far + big;
let (x0, cx) = if first_angle {
(0.0, far)
} else {
(end - len, big)
};
let x1 = x0 + len;
let at = [
block[2] - 3.0 - PROJECTION_LINE / 2.0 - (end + 0.25 * h),
top(block) + FURNITURE_GAP + PROJECTION_LINE / 2.0 + big,
];
let m = |p: P| [p[0] + at[0], p[1] + at[1]];
let mut curves: Vec<Curve> = [
[[x0, -left], [x0, left]],
[[x1, -right], [x1, right]],
[[x0, left], [x1, right]],
[[x0, -left], [x1, -right]],
[[-0.25 * h, 0.0], [end + 0.25 * h, 0.0]],
]
.into_iter()
.map(|[a, b]| Curve::Line(m(a), m(b)))
.collect();
curves.extend([big, small].map(|r| Curve::Conic {
centre: m([cx, 0.0]),
radii: [r, r],
x_axis: [1.0, 0.0],
y_axis: [0.0, 1.0],
t0: 0.0,
t1: std::f64::consts::TAU,
}));
ProjectionPlaced {
method: if first_angle {
"first-angle"
} else {
"third-angle"
}
.into(),
curves,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FinishPlaced {
pub strokes: Vec<[P; 2]>,
pub text_at: P,
pub label_box: [f64; 4],
#[serde(rename = "box")]
pub glyph: [f64; 4],
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub arcs: Vec<[f64; 5]>,
}
pub fn default_finish(block: [f64; 4], text: &str, removal: &str) -> FinishPlaced {
let laid = lay(text, TEXT);
let w = laid.max[0] - laid.min[0];
let cot = 1.0 / 3f64.sqrt();
let (short, long, gap) = (1.4 * TEXT, 3.0 * TEXT, 0.3 * TEXT);
let short_top = [-short * cot, short];
let long_top = [long * cot, long];
let left = long_top[0] + gap;
let end = left + w + gap;
let at = [block[0] - short_top[0], top(block) + FURNITURE_GAP];
let m = |p: P| [p[0] + at[0], p[1] + at[1]];
let centre = m([left + w / 2.0, long - gap - TEXT / 2.0]);
let (marks, circles) = haecceity::presentation::notes::removal_marks(
haecceity::pmi::MaterialRemoval::from_term(removal)
.unwrap_or(haecceity::pmi::MaterialRemoval::AnyProcessAllowed),
short,
);
let mut strokes = vec![
[m(short_top), m([0.0, 0.0])],
[m([0.0, 0.0]), m(long_top)],
[m(long_top), m([end, long])],
];
strokes.extend(marks.iter().map(|[a, b]| [m(*a), m(*b)]));
FinishPlaced {
strokes,
arcs: circles
.iter()
.map(|c| {
let [x, y] = m([c[0], c[1]]);
[x, y, c[2], c[3], c[4]]
})
.collect(),
text_at: centre,
label_box: [
centre[0] - w / 2.0,
centre[1] - TEXT / 2.0,
centre[0] + w / 2.0,
centre[1] + TEXT / 2.0,
],
glyph: [block[0], at[1], m([end, long])[0], at[1] + long],
}
}
fn source(field: &str) -> String {
match KEYS.iter().find(|(_, f)| *f == field) {
Some((key, _)) => format!("sheet/title/{key}"),
None if field == "format" => "sheet/size".into(),
None => format!("the title block's {field}"),
}
}
pub fn problems(cells: &[TitleCell], page: [f64; 2]) -> Vec<Problem> {
let mut out = Vec::new();
for c in cells {
if c.field == "general_tolerance" && c.value.is_none() {
out.push(Problem {
crossing_kinds: Vec::new(),
ink_is_leader: None,
id: "p:general_tolerance_missing:sheet".into(),
code: "general_tolerance_missing".into(),
severity: "warning".into(),
message: "GEN. TOL. is blank: no general tolerance is drawn from the Spec or usable PMI. Set sheet/title/tolerance to the intended requirement. The offered fix explicitly states UNSPECIFIED; it acknowledges the missing requirement without inventing a manufacturing tolerance.".into(),
subjects: vec!["sheet".into()],
refs: vec!["title_block/general_tolerance".into(), "sheet/title/tolerance".into()],
fix: vec![crate::items::Op::set("sheet/title/tolerance", serde_json::json!("UNSPECIFIED"))],
fixes: Vec::new(),
});
}
let Some(v) = &c.value else { continue };
let laid = lay(v, value_size(v, c.cell));
let [w, h] = [laid.max[0] - laid.min[0], laid.max[1] - laid.min[1]];
let [x0, y0, x1, y1] = c.cell;
let (cw, ch) = (x1 - x0, y1 - y0);
let subject = format!("title_block/{}", c.field);
if w > cw + 1e-9 || h > ch + 1e-9 {
out.push(Problem {
id: format!("p:title_field_overflow:{subject}"),
code: "title_field_overflow".into(),
severity: "warning".into(),
message: format!(
"Title-block field '{}' overflows its cell: text {w:.2} × {h:.2} mm, cell {cw:.2} × {ch:.2} mm. The value, {v:?}, is drawn whole at {MIN_TEXT} mm, the smallest text height, not shortened; give {} a concise value.",
c.field,
source(&c.field)
),
subjects: vec!["sheet".into()],
refs: vec![subject.clone()],
..Default::default()
});
}
let (cx, cy) = (0.5 * (x0 + x1), 0.5 * (y0 + y1));
let (lo, hi) = ([cx - w / 2.0, cy - h / 2.0], [cx + w / 2.0, cy + h / 2.0]);
if lo[0] < FRAME || lo[1] < FRAME || hi[0] > page[0] - FRAME || hi[1] > page[1] - FRAME {
out.push(Problem {
id: format!("p:annotation_off_sheet:{subject}"),
code: "annotation_off_sheet".into(),
severity: "error".into(),
message: format!(
"Title-block field '{}' ({v:?}) runs off the sheet's drawing area; give {} a concise value.",
c.field,
source(&c.field)
),
subjects: vec!["sheet".into()],
refs: vec![subject],
..Default::default()
});
}
}
out
}
pub(crate) fn number_sheets(plan: &mut crate::model::Plan) {
if plan.sheets.is_empty() {
return;
}
let count = plan.sheets.len() + 1;
plan.problems.retain(|p| {
!(["title_field_overflow", "annotation_off_sheet"].contains(&p.code.as_str())
&& p.refs.iter().any(|r| r == "title_block/sheet"))
});
for sheet in std::iter::once(&mut plan.sheet).chain(&mut plan.sheets) {
let value = format!("{}/{count}", sheet.number);
sheet.title.insert("sheet".into(), value.clone());
for cell in sheet.title_cells.iter_mut().filter(|c| c.field == "sheet") {
cell.value = Some(value.clone());
for mut problem in problems(std::slice::from_ref(cell), sheet.page) {
if sheet.number > 1 {
problem.id += &format!(":sheet:{}", sheet.number);
problem.subjects = vec![format!("sheet:{}", sheet.number)];
}
plan.problems.push(problem);
}
}
}
}
pub(crate) fn pack_cells(sheet: &mut crate::model::PlannedSheet, item: u32, qty: usize) {
sheet.title_cells = cells(sheet.title_block, &sheet.title, &sheet.size);
let owner = &mut sheet.title_cells[0];
let [x0, y0, x1, y1] = owner.cell;
let width = x1 - x0;
owner.cell[2] = x0 + width * 0.60;
for (field, label, value, left, right) in [
("pack_item", "ITEM", item.to_string(), 0.60, 0.80),
("pack_qty", "QTY", qty.to_string(), 0.80, 1.00),
] {
sheet.title_cells.push(TitleCell {
field: field.into(),
label: label.into(),
cell: [x0 + width * left, y0, x0 + width * right, y1],
value: Some(value),
});
}
}