use super::layout::{LayoutStyle, Presentation, TextRun};
use super::PmiGeometry;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
pub fn symbol_fields() -> Vec<(&'static str, Value)> {
vec![
("style", json!({"type": "options", "label": "Style", "options": ["SYMBOL", "TEXT"], "default_value": "SYMBOL",
"hint": "SYMBOL draws the standard weld symbol; TEXT keeps the plain text leader."})),
("standard", json!({"type": "options", "label": "Standard", "options": ["AWS", "ISO"], "default_value": "AWS",
"hint": "AWS A2.4 (the arrow side's symbol below the reference line) or ISO 2553 (solid and dashed reference lines, z leg size)."})),
("side", json!({"type": "options", "label": "Weld side", "options": ["ARROW", "OTHER", "BOTH"], "default_value": "ARROW",
"hint": "Which side of the joint the weld is on, relative to the arrow. A weld on both sides (a fillet's Sides BOTH, a double groove) draws both."})),
("length", json!({"type": "number", "label": "Length", "default_value": 0,
"hint": "Weld length (each segment of an intermittent weld). 0 = from the weld feature (its segment length), else continuous."})),
("pitch", json!({"type": "number", "label": "Pitch", "default_value": 0,
"hint": "Centre-to-centre spacing of an intermittent weld. 0 = from the weld feature, else not intermittent."})),
("allAround", json!({"type": "boolean", "label": "All around", "default_value": false,
"hint": "Weld all around the joint (circle at the elbow); a weld feature welded all around draws it too."})),
("fieldWeld", json!({"type": "boolean", "label": "Field weld", "default_value": false,
"hint": "Weld made in the field (flag at the elbow)."})),
]
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Standard {
Aws,
Iso,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Side {
Arrow,
Other,
Both,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Glyph {
Fillet,
Square,
V,
Bevel,
U,
J,
FlareV,
FlareBevel,
Plug,
Spot,
Seam,
Surfacing,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WeldSymbol {
pub standard: Standard,
pub side: Side,
pub glyph: Glyph,
pub size: String,
pub length: String,
pub all_around: bool,
pub field_weld: bool,
pub tail: String,
#[serde(default)]
pub staggered: bool,
}
pub fn path_length(curves: &[crate::NurbsCurve]) -> f64 {
let mut length = 0.0;
for curve in curves {
let Ok([t0, t1]) = curve.domain() else { continue };
let mut previous: Option<crate::Vec3> = None;
for k in 0..=512 {
let Ok(point) = curve.evaluate(t0 + (t1 - t0) * k as f64 / 512.0) else { continue };
if let Some(last) = previous { length += point.sub(last).length(); }
previous = Some(point);
}
}
length
}
pub fn segments(kind: &str, weld: &Value, seam_length: f64, evaluate: Evaluate<'_>) -> Option<usize> {
let get = |key: &str, default: f64| -> Option<f64> {
match weld.get(key) { None => Some(default), value => number(key, value, evaluate).ok() }
};
let count = |span: f64, pitch: f64| -> Option<usize> {
(span >= -1e-9 && pitch > 0.0).then(|| ((span.max(0.0) / pitch + 1e-9).floor() + 1.0) as usize)
};
match kind {
"WELD" if matches!(text(weld.get("intermittent")), "CHAIN" | "STAGGERED") => {
let (segment, pitch) = (get("segmentLength", 10.0)?, get("pitch", 25.0)?);
count(seam_length - segment, pitch)
}
"WELD.TACK" => get("count", 3.0).map(|n| n.max(0.0) as usize),
"WELD.SPOT" => {
let (pitch, end) = (get("pitch", 25.0)?, get("endDistance", 10.0)?);
count(seam_length - 2.0 * end, pitch)
}
_ => None,
}
}
pub type Evaluate<'a> = &'a dyn Fn(&str) -> Option<f64>;
fn number(field: &str, value: Option<&Value>, evaluate: Evaluate<'_>) -> Result<f64, String> {
match value {
Some(Value::Number(n)) => Ok(n.as_f64().unwrap_or(0.0)),
Some(Value::String(s)) if s.trim().is_empty() => Ok(0.0),
Some(Value::String(s)) => s.trim().parse().ok().or_else(|| evaluate(s))
.ok_or_else(|| format!("{field}: cannot evaluate `{}`", s.trim())),
_ => Ok(0.0),
}
}
pub fn literal(_: &str) -> Option<f64> {
None
}
fn text<'a>(value: Option<&'a Value>) -> &'a str {
value.and_then(Value::as_str).unwrap_or("")
}
fn fmt(value: f64) -> String {
let rounded = (value * 100.0).round() / 100.0;
let text = format!("{rounded:.2}");
text.trim_end_matches('0').trim_end_matches('.').to_string()
}
impl WeldSymbol {
pub fn from_params(annotation: &Value, kind: &str, weld: &Value, evaluate: Evaluate<'_>, segments: Option<usize>) -> Result<Option<Self>, String> {
if text(annotation.get("style")) == "TEXT" {
return Ok(None);
}
let standard = if text(annotation.get("standard")) == "ISO" { Standard::Iso } else { Standard::Aws };
let mut side = match text(annotation.get("side")) {
"OTHER" => Side::Other,
"BOTH" => Side::Both,
_ => Side::Arrow,
};
let iso = standard == Standard::Iso;
let feature = |key: &str| number(&format!("weld {key}"), weld.get(key), evaluate);
let flag = |key: &str| weld.get(key).and_then(Value::as_bool).unwrap_or(false);
let mut length = number("length", annotation.get("length"), evaluate)?.max(0.0);
let mut pitch = number("pitch", annotation.get("pitch"), evaluate)?.max(0.0);
let mut all_around = annotation.get("allAround").and_then(Value::as_bool).unwrap_or(false) || flag("allAround");
let mut tail_kind: Option<&str> = None;
let staggered = kind == "WELD" && text(weld.get("intermittent")) == "STAGGERED" && text(weld.get("sides")) == "BOTH";
let fillet_size = || -> Result<String, String> {
let first = match weld.get("legSize") { None => 3.0, value => number("weld leg size", value, evaluate)? };
let second = feature("legSize2")?;
let base = if second > 0.0 && (second - first).abs() > 1e-12 { format!("{}x{}", fmt(first), fmt(second)) } else { fmt(first) };
Ok(if iso { format!("z{base}") } else { base })
};
let (glyph, size) = match kind {
"WELD" => {
if text(weld.get("sides")) == "BOTH" { side = Side::Both; }
if matches!(text(weld.get("intermittent")), "CHAIN" | "STAGGERED") {
length = match weld.get("segmentLength") { None => 10.0, value => number("weld segment length", value, evaluate)? };
pitch = match weld.get("pitch") { None => 25.0, value => number("weld pitch", value, evaluate)? };
}
(Glyph::Fillet, fillet_size()?)
}
"WELD.TACK" => {
if text(weld.get("sides")) == "BOTH" { side = Side::Both; }
length = match weld.get("tackLength") { None => 5.0, value => number("weld tack length", value, evaluate)? };
pitch = 0.0;
tail_kind = Some("TACK");
(Glyph::Fillet, fillet_size()?)
}
"WELD.GROOVE" => {
if flag("double") { side = Side::Both; }
let shape = match text(weld.get("shape")) {
"SQUARE" => Glyph::Square,
"BEVEL" => Glyph::Bevel,
"U" => Glyph::U,
"J" => Glyph::J,
"FLARE_V" => Glyph::FlareV,
"FLARE_BEVEL" => Glyph::FlareBevel,
_ => Glyph::V,
};
if matches!(shape, Glyph::Square | Glyph::FlareV | Glyph::FlareBevel) {
(shape, String::new())
} else {
let angle = match weld.get("grooveAngle") { None => 60.0, value => number("weld groove angle", value, evaluate)? };
(shape, format!("{}°", fmt(angle)))
}
}
"WELD.SPOT" => {
pitch = match weld.get("pitch") { None => 25.0, value => number("weld pitch", value, evaluate)? };
let diameter = match weld.get("diameter") { None => 5.0, value => number("weld nugget diameter", value, evaluate)? };
length = 0.0;
(Glyph::Spot, format!("\u{2300}{}", fmt(diameter)))
}
"WELD.RSEAM" => {
let width = match weld.get("width") { None => 5.0, value => number("weld width", value, evaluate)? };
(Glyph::Seam, fmt(width))
}
"WELD.PLUG" => (Glyph::Plug, String::new()),
"WELD.SURF" => {
let thickness = match weld.get("thickness") { None => 2.0, value => number("weld thickness", value, evaluate)? };
(Glyph::Surfacing, fmt(thickness))
}
_ => return Ok(None),
};
let length_text = match glyph {
Glyph::Spot => match segments {
Some(n) if n > 0 => format!("{} ({n})", fmt(pitch)),
_ => fmt(pitch),
},
_ if length <= 0.0 => String::new(),
_ => match (standard, pitch > 0.0, segments) {
(_, false, Some(n)) if tail_kind.is_some() => format!("{} ({n})", fmt(length)),
(_, false, _) => fmt(length),
(Standard::Aws, true, _) => format!("{}-{}", fmt(length), fmt(pitch)),
(Standard::Iso, true, Some(n)) => format!("{n} x {} ({})", fmt(length), fmt((pitch - length).max(0.0))),
(Standard::Iso, true, None) => format!("{} ({})", fmt(length), fmt((pitch - length).max(0.0))),
},
};
if matches!(glyph, Glyph::Spot | Glyph::Seam | Glyph::Plug | Glyph::Surfacing) && side == Side::Both {
side = Side::Arrow;
}
all_around = all_around && !matches!(glyph, Glyph::Spot);
let mut tail: Vec<&str> = Vec::new();
if let Some(kind) = tail_kind { tail.push(kind); }
for note in [text(weld.get("process")).trim(), text(annotation.get("afterText")).trim()] {
if !note.is_empty() {
tail.push(note);
}
}
Ok(Some(WeldSymbol {
standard,
side,
glyph,
size,
length: length_text,
all_around,
field_weld: annotation.get("fieldWeld").and_then(Value::as_bool).unwrap_or(false),
tail: tail.join(" "),
staggered: staggered && side == Side::Both,
}))
}
}
#[derive(Debug, Clone, Copy)]
pub struct Frame {
pub right: [f64; 3],
pub up: [f64; 3],
pub height: f64,
pub arrow: f64,
}
impl Frame {
pub fn from_plane(normal: [f64; 3], x_axis: [f64; 3], height: f64, arrow: f64) -> Self {
let right = normalize(x_axis);
Frame { right, up: normalize(cross(normal, right)), height, arrow }
}
pub fn from_view(forward: [f64; 3], up: [f64; 3], height: f64, arrow: f64) -> Self {
let right = normalize(cross(forward, up));
let up = normalize(cross(right, forward));
Frame { right, up, height, arrow }
}
}
fn add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn scale(a: [f64; 3], s: f64) -> [f64; 3] {
[a[0] * s, a[1] * s, a[2] * s]
}
fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn normalize(a: [f64; 3]) -> [f64; 3] {
let length = dot(a, a).sqrt();
if length > 1e-12 { scale(a, 1.0 / length) } else { [1.0, 0.0, 0.0] }
}
pub fn default_elbow(anchor: [f64; 3], frame: &Frame) -> [f64; 3] {
add(anchor, add(scale(frame.right, 3.0 * frame.height), scale(frame.up, 4.0 * frame.height)))
}
pub const RING: f64 = 2.2;
pub fn text_width(text: &str, height: f64) -> f64 {
text.chars().count() as f64 * height * 0.8
}
pub fn present_row(row: &super::PmiAnnotationReport, style: &LayoutStyle) -> Option<Presentation> {
let symbol = row.weld_symbol.as_ref()?;
let PmiGeometry::Leader { targets, .. } = &row.geometry else { return None };
let anchor = *targets.first()?;
let plane = row.plane.or(style.plane);
let frame = match plane {
Some(plane) => Frame::from_plane(plane.normal, plane.x_axis, style.text_height, style.arrow),
None => Frame::from_view(style.view_dir, style.view_up, style.text_height, style.arrow),
};
let elbow = plane.map_or(row.label_world, |plane| plane.project(row.label_world));
Some(present(symbol, anchor, elbow, &frame))
}
pub fn present(symbol: &WeldSymbol, anchor: [f64; 3], elbow: [f64; 3], frame: &Frame) -> Presentation {
let h = frame.height;
let (u, v) = (frame.right, frame.up);
let s = if dot(sub(elbow, anchor), u) >= 0.0 { 1.0 } else { -1.0 };
let at = |x: f64, y: f64| add(elbow, add(scale(u, s * x), scale(v, y)));
let size = symbol.size.clone();
let length = symbol.length.clone();
let tail = symbol.tail.clone();
let label_room = text_width(&size, h) + text_width(&length, h) + 4.0 * h;
let near_text = if s > 0.0 { text_width(&size, h) } else { text_width(&length, h) };
let centre = RING * h + 0.9 * h + near_text + 0.5 * h;
let line_length = (centre / h + 4.5).max(label_room / h + 2.0 + RING) * h;
let mut drawn = Presentation::default();
let mut texts: Vec<TextRun> = Vec::new();
drawn.polylines.push(vec![elbow, anchor]);
let to_anchor = sub(anchor, elbow);
let distance = dot(to_anchor, to_anchor).sqrt();
if distance > 1e-9 {
let d = scale(to_anchor, 1.0 / distance);
let head = frame.arrow.min(distance * 0.5);
let side = normalize(cross(cross(u, v), d));
let base = sub(anchor, scale(d, head));
drawn.arrows.push([anchor, add(base, scale(side, head * 0.3)), sub(base, scale(side, head * 0.3))]);
}
drawn.polylines.push(vec![at(0.0, 0.0), at(line_length, 0.0)]);
let iso = symbol.standard == Standard::Iso;
let dashed_y = -0.6 * h;
if iso && symbol.side != Side::Both {
let (dash, gap) = (0.5 * h, 0.25 * h);
let mut x = 0.0;
while x < line_length {
let end = (x + dash).min(line_length);
drawn.polylines.push(vec![at(x, dashed_y), at(end, dashed_y)]);
x += dash + gap;
}
}
let left = if s > 0.0 { centre - 0.5 * h } else { centre + 0.5 * h };
let screen_x = |k: f64| if s > 0.0 { left + k * h } else { left - k * h };
let mut glyph = |base_y: f64, toward: f64, dx: f64| {
let sx = |k: f64| screen_x(k + dx);
let y = |k: f64| base_y + toward * k * h;
let pt = |kx: f64, ky: f64| at(sx(kx), y(ky));
let arc = |cx: f64, cy: f64, r: f64, a0: f64, a1: f64| -> Vec<[f64; 3]> {
(0..=16).map(|k| {
let a = a0 + (a1 - a0) * k as f64 / 16.0;
pt(cx + r * a.cos(), cy + r * a.sin())
}).collect()
};
match symbol.glyph {
Glyph::Fillet => drawn.polylines.push(vec![pt(0.0, 0.0), pt(0.0, 1.0), pt(1.0, 0.0), pt(0.0, 0.0)]),
Glyph::Square => {
drawn.polylines.push(vec![pt(0.3, 0.0), pt(0.3, 1.0)]);
drawn.polylines.push(vec![pt(0.7, 0.0), pt(0.7, 1.0)]);
}
Glyph::V => drawn.polylines.push(vec![pt(0.0, 1.0), pt(0.5, 0.0), pt(1.0, 1.0)]),
Glyph::Bevel => {
drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.9, 1.0)]);
}
Glyph::U => {
let mut line = vec![pt(0.0, 1.0), pt(0.25, 0.55)];
line.extend(arc(0.5, 0.55, 0.25, std::f64::consts::PI, 2.0 * std::f64::consts::PI).into_iter().skip(1));
line.push(pt(1.0, 1.0));
drawn.polylines.push(vec![pt(0.5, 0.0), pt(0.5, 0.3)]);
drawn.polylines.push(line);
}
Glyph::J => {
drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
let mut line = arc(0.2, 0.55, 0.35, -std::f64::consts::FRAC_PI_2, 0.0);
line.push(pt(0.9, 1.0));
drawn.polylines.push(line);
}
Glyph::FlareV => {
let reach = (0.5_f64 / 0.6).asin();
drawn.polylines.push(arc(-0.15, 0.5, 0.6, -reach, reach));
drawn.polylines.push(arc(1.15, 0.5, 0.6, std::f64::consts::PI - reach, std::f64::consts::PI + reach));
}
Glyph::FlareBevel => {
let reach = (0.5_f64 / 0.6).asin();
drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
drawn.polylines.push(arc(1.15, 0.5, 0.6, std::f64::consts::PI - reach, std::f64::consts::PI + reach));
}
Glyph::Plug => drawn.polylines.push(vec![pt(0.0, 0.0), pt(0.0, 0.6), pt(1.0, 0.6), pt(1.0, 0.0)]),
Glyph::Spot => drawn.polylines.push(arc(0.5, 0.4, 0.4, 0.0, std::f64::consts::TAU)),
Glyph::Seam => {
drawn.polylines.push(arc(0.5, 0.4, 0.4, 0.0, std::f64::consts::TAU));
drawn.polylines.push(vec![pt(-0.1, 0.3), pt(1.1, 0.3)]);
drawn.polylines.push(vec![pt(-0.1, 0.5), pt(1.1, 0.5)]);
}
Glyph::Surfacing => {
drawn.polylines.push(arc(0.25, 0.0, 0.25, 0.0, std::f64::consts::PI));
drawn.polylines.push(arc(0.75, 0.0, 0.25, 0.0, std::f64::consts::PI));
}
}
let text_y = base_y + toward * 0.7 * h;
let (lx, rx) = (sx(0.0), sx(1.0));
if !size.is_empty() {
let offset = 0.3 * h + text_width(&size, h) * 0.5;
let x = if s > 0.0 { lx - offset } else { lx + offset };
texts.push(run(&size, at(x, text_y), u, v, h));
}
if !length.is_empty() {
let offset = 0.3 * h + text_width(&length, h) * 0.5;
let x = if s > 0.0 { rx + offset } else { rx - offset };
texts.push(run(&length, at(x, text_y), u, v, h));
}
};
let (arrow_side, other_side) = if iso { ((0.0, 1.0), (dashed_y, -1.0)) } else { ((0.0, -1.0), (0.0, 1.0)) };
match symbol.side {
Side::Arrow => glyph(arrow_side.0, arrow_side.1, 0.0),
Side::Other => glyph(other_side.0, other_side.1, 0.0),
Side::Both => {
glyph(0.0, -1.0, 0.0);
glyph(0.0, 1.0, if symbol.staggered { 1.0 } else { 0.0 });
}
}
if symbol.all_around {
let r = RING * h;
drawn.polylines.push((0..=32).map(|k| {
let a = k as f64 / 32.0 * std::f64::consts::TAU;
add(elbow, add(scale(u, r * a.cos()), scale(v, r * a.sin())))
}).collect());
}
if symbol.field_weld {
let top = at(0.0, (RING + 1.0) * h);
drawn.polylines.push(vec![elbow, top]);
drawn.arrows.push([top, at(0.0, (RING + 0.4) * h), at(0.9 * h, (RING + 0.7) * h)]);
}
if !tail.is_empty() {
let end = at(line_length, 0.0);
let k = 0.8 * h * std::f64::consts::FRAC_1_SQRT_2;
drawn.polylines.push(vec![at(line_length + k, k), end, at(line_length + k, -k)]);
let x = line_length + k + 0.3 * h + text_width(&tail, h) * 0.5;
texts.push(run(&tail, at(x, 0.0), u, v, h));
}
drawn.text_anchor = elbow;
drawn.texts = texts;
drawn
}
fn run(text: &str, anchor: [f64; 3], right: [f64; 3], up: [f64; 3], height: f64) -> TextRun {
TextRun { text: text.to_string(), anchor, right, up, height }
}