1use super::layout::{LayoutStyle, Presentation, TextRun};
18use super::PmiGeometry;
19use serde::{Deserialize, Serialize};
20use serde_json::{json, Value};
21
22pub fn symbol_fields() -> Vec<(&'static str, Value)> {
24 vec![
25 ("style", json!({"type": "options", "label": "Style", "options": ["SYMBOL", "TEXT"], "default_value": "SYMBOL",
26 "hint": "SYMBOL draws the standard weld symbol; TEXT keeps the plain text leader."})),
27 ("standard", json!({"type": "options", "label": "Standard", "options": ["AWS", "ISO"], "default_value": "AWS",
28 "hint": "AWS A2.4 (the arrow side's symbol below the reference line) or ISO 2553 (solid and dashed reference lines, z leg size)."})),
29 ("side", json!({"type": "options", "label": "Weld side", "options": ["ARROW", "OTHER", "BOTH"], "default_value": "ARROW",
30 "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."})),
31 ("length", json!({"type": "number", "label": "Length", "default_value": 0,
32 "hint": "Weld length (each segment of an intermittent weld). 0 = from the weld feature (its segment length), else continuous."})),
33 ("pitch", json!({"type": "number", "label": "Pitch", "default_value": 0,
34 "hint": "Centre-to-centre spacing of an intermittent weld. 0 = from the weld feature, else not intermittent."})),
35 ("allAround", json!({"type": "boolean", "label": "All around", "default_value": false,
36 "hint": "Weld all around the joint (circle at the elbow); a weld feature welded all around draws it too."})),
37 ("fieldWeld", json!({"type": "boolean", "label": "Field weld", "default_value": false,
38 "hint": "Weld made in the field (flag at the elbow)."})),
39 ]
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
43pub enum Standard {
44 Aws,
45 Iso,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
49pub enum Side {
50 Arrow,
51 Other,
52 Both,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
57pub enum Glyph {
58 Fillet,
59 Square,
60 V,
61 Bevel,
62 U,
63 J,
64 FlareV,
65 FlareBevel,
66 Plug,
67 Spot,
68 Seam,
69 Surfacing,
70}
71
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75pub struct WeldSymbol {
76 pub standard: Standard,
77 pub side: Side,
78 pub glyph: Glyph,
79 pub size: String,
81 pub length: String,
83 pub all_around: bool,
84 pub field_weld: bool,
85 pub tail: String,
87 #[serde(default)]
90 pub staggered: bool,
91}
92
93pub fn path_length(curves: &[crate::NurbsCurve]) -> f64 {
95 let mut length = 0.0;
96 for curve in curves {
97 let Ok([t0, t1]) = curve.domain() else { continue };
98 let mut previous: Option<crate::Vec3> = None;
99 for k in 0..=512 {
100 let Ok(point) = curve.evaluate(t0 + (t1 - t0) * k as f64 / 512.0) else { continue };
101 if let Some(last) = previous { length += point.sub(last).length(); }
102 previous = Some(point);
103 }
104 }
105 length
106}
107
108pub fn segments(kind: &str, weld: &Value, seam_length: f64, evaluate: Evaluate<'_>) -> Option<usize> {
112 let get = |key: &str, default: f64| -> Option<f64> {
113 match weld.get(key) { None => Some(default), value => number(key, value, evaluate).ok() }
114 };
115 let count = |span: f64, pitch: f64| -> Option<usize> {
116 (span >= -1e-9 && pitch > 0.0).then(|| ((span.max(0.0) / pitch + 1e-9).floor() + 1.0) as usize)
117 };
118 match kind {
119 "WELD" if matches!(text(weld.get("intermittent")), "CHAIN" | "STAGGERED") => {
120 let (segment, pitch) = (get("segmentLength", 10.0)?, get("pitch", 25.0)?);
121 count(seam_length - segment, pitch)
122 }
123 "WELD.TACK" => get("count", 3.0).map(|n| n.max(0.0) as usize),
124 "WELD.SPOT" => {
125 let (pitch, end) = (get("pitch", 25.0)?, get("endDistance", 10.0)?);
126 count(seam_length - 2.0 * end, pitch)
127 }
128 _ => None,
129 }
130}
131
132pub type Evaluate<'a> = &'a dyn Fn(&str) -> Option<f64>;
135
136fn number(field: &str, value: Option<&Value>, evaluate: Evaluate<'_>) -> Result<f64, String> {
139 match value {
140 Some(Value::Number(n)) => Ok(n.as_f64().unwrap_or(0.0)),
141 Some(Value::String(s)) if s.trim().is_empty() => Ok(0.0),
142 Some(Value::String(s)) => s.trim().parse().ok().or_else(|| evaluate(s))
143 .ok_or_else(|| format!("{field}: cannot evaluate `{}`", s.trim())),
144 _ => Ok(0.0),
145 }
146}
147
148pub fn literal(_: &str) -> Option<f64> {
150 None
151}
152
153fn text<'a>(value: Option<&'a Value>) -> &'a str {
154 value.and_then(Value::as_str).unwrap_or("")
155}
156
157fn fmt(value: f64) -> String {
159 let rounded = (value * 100.0).round() / 100.0;
160 let text = format!("{rounded:.2}");
161 text.trim_end_matches('0').trim_end_matches('.').to_string()
162}
163
164impl WeldSymbol {
165 pub fn from_params(annotation: &Value, kind: &str, weld: &Value, evaluate: Evaluate<'_>, segments: Option<usize>) -> Result<Option<Self>, String> {
174 if text(annotation.get("style")) == "TEXT" {
175 return Ok(None);
176 }
177 let standard = if text(annotation.get("standard")) == "ISO" { Standard::Iso } else { Standard::Aws };
178 let mut side = match text(annotation.get("side")) {
179 "OTHER" => Side::Other,
180 "BOTH" => Side::Both,
181 _ => Side::Arrow,
182 };
183 let iso = standard == Standard::Iso;
184 let feature = |key: &str| number(&format!("weld {key}"), weld.get(key), evaluate);
185 let flag = |key: &str| weld.get(key).and_then(Value::as_bool).unwrap_or(false);
186 let mut length = number("length", annotation.get("length"), evaluate)?.max(0.0);
187 let mut pitch = number("pitch", annotation.get("pitch"), evaluate)?.max(0.0);
188 let mut all_around = annotation.get("allAround").and_then(Value::as_bool).unwrap_or(false) || flag("allAround");
189 let mut tail_kind: Option<&str> = None;
190 let staggered = kind == "WELD" && text(weld.get("intermittent")) == "STAGGERED" && text(weld.get("sides")) == "BOTH";
191 let fillet_size = || -> Result<String, String> {
192 let first = match weld.get("legSize") { None => 3.0, value => number("weld leg size", value, evaluate)? };
193 let second = feature("legSize2")?;
194 let base = if second > 0.0 && (second - first).abs() > 1e-12 { format!("{}x{}", fmt(first), fmt(second)) } else { fmt(first) };
195 Ok(if iso { format!("z{base}") } else { base })
196 };
197 let (glyph, size) = match kind {
198 "WELD" => {
199 if text(weld.get("sides")) == "BOTH" { side = Side::Both; }
200 if matches!(text(weld.get("intermittent")), "CHAIN" | "STAGGERED") {
201 length = match weld.get("segmentLength") { None => 10.0, value => number("weld segment length", value, evaluate)? };
202 pitch = match weld.get("pitch") { None => 25.0, value => number("weld pitch", value, evaluate)? };
203 }
204 (Glyph::Fillet, fillet_size()?)
205 }
206 "WELD.TACK" => {
207 if text(weld.get("sides")) == "BOTH" { side = Side::Both; }
208 length = match weld.get("tackLength") { None => 5.0, value => number("weld tack length", value, evaluate)? };
209 pitch = 0.0;
210 tail_kind = Some("TACK");
211 (Glyph::Fillet, fillet_size()?)
212 }
213 "WELD.GROOVE" => {
214 if flag("double") { side = Side::Both; }
215 let shape = match text(weld.get("shape")) {
216 "SQUARE" => Glyph::Square,
217 "BEVEL" => Glyph::Bevel,
218 "U" => Glyph::U,
219 "J" => Glyph::J,
220 "FLARE_V" => Glyph::FlareV,
221 "FLARE_BEVEL" => Glyph::FlareBevel,
222 _ => Glyph::V,
223 };
224 if matches!(shape, Glyph::Square | Glyph::FlareV | Glyph::FlareBevel) {
225 (shape, String::new())
226 } else {
227 let angle = match weld.get("grooveAngle") { None => 60.0, value => number("weld groove angle", value, evaluate)? };
228 (shape, format!("{}°", fmt(angle)))
229 }
230 }
231 "WELD.SPOT" => {
232 pitch = match weld.get("pitch") { None => 25.0, value => number("weld pitch", value, evaluate)? };
233 let diameter = match weld.get("diameter") { None => 5.0, value => number("weld nugget diameter", value, evaluate)? };
234 length = 0.0;
235 (Glyph::Spot, format!("\u{2300}{}", fmt(diameter)))
236 }
237 "WELD.RSEAM" => {
238 let width = match weld.get("width") { None => 5.0, value => number("weld width", value, evaluate)? };
239 (Glyph::Seam, fmt(width))
240 }
241 "WELD.PLUG" => (Glyph::Plug, String::new()),
242 "WELD.SURF" => {
243 let thickness = match weld.get("thickness") { None => 2.0, value => number("weld thickness", value, evaluate)? };
244 (Glyph::Surfacing, fmt(thickness))
245 }
246 _ => return Ok(None),
247 };
248 let length_text = match glyph {
251 Glyph::Spot => match segments {
252 Some(n) if n > 0 => format!("{} ({n})", fmt(pitch)),
253 _ => fmt(pitch),
254 },
255 _ if length <= 0.0 => String::new(),
256 _ => match (standard, pitch > 0.0, segments) {
257 (_, false, Some(n)) if tail_kind.is_some() => format!("{} ({n})", fmt(length)),
258 (_, false, _) => fmt(length),
259 (Standard::Aws, true, _) => format!("{}-{}", fmt(length), fmt(pitch)),
260 (Standard::Iso, true, Some(n)) => format!("{n} x {} ({})", fmt(length), fmt((pitch - length).max(0.0))),
261 (Standard::Iso, true, None) => format!("{} ({})", fmt(length), fmt((pitch - length).max(0.0))),
262 },
263 };
264 if matches!(glyph, Glyph::Spot | Glyph::Seam | Glyph::Plug | Glyph::Surfacing) && side == Side::Both {
265 side = Side::Arrow;
266 }
267 all_around = all_around && !matches!(glyph, Glyph::Spot);
268 let mut tail: Vec<&str> = Vec::new();
269 if let Some(kind) = tail_kind { tail.push(kind); }
270 for note in [text(weld.get("process")).trim(), text(annotation.get("afterText")).trim()] {
271 if !note.is_empty() {
272 tail.push(note);
273 }
274 }
275 Ok(Some(WeldSymbol {
276 standard,
277 side,
278 glyph,
279 size,
280 length: length_text,
281 all_around,
282 field_weld: annotation.get("fieldWeld").and_then(Value::as_bool).unwrap_or(false),
283 tail: tail.join(" "),
284 staggered: staggered && side == Side::Both,
285 }))
286 }
287}
288
289#[derive(Debug, Clone, Copy)]
291pub struct Frame {
292 pub right: [f64; 3],
293 pub up: [f64; 3],
294 pub height: f64,
296 pub arrow: f64,
298}
299
300impl Frame {
301 pub fn from_plane(normal: [f64; 3], x_axis: [f64; 3], height: f64, arrow: f64) -> Self {
304 let right = normalize(x_axis);
305 Frame { right, up: normalize(cross(normal, right)), height, arrow }
306 }
307
308 pub fn from_view(forward: [f64; 3], up: [f64; 3], height: f64, arrow: f64) -> Self {
310 let right = normalize(cross(forward, up));
311 let up = normalize(cross(right, forward));
312 Frame { right, up, height, arrow }
313 }
314}
315
316fn add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
317 [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
318}
319fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
320 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
321}
322fn scale(a: [f64; 3], s: f64) -> [f64; 3] {
323 [a[0] * s, a[1] * s, a[2] * s]
324}
325fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
326 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
327}
328fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
329 [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
330}
331fn normalize(a: [f64; 3]) -> [f64; 3] {
332 let length = dot(a, a).sqrt();
333 if length > 1e-12 { scale(a, 1.0 / length) } else { [1.0, 0.0, 0.0] }
334}
335
336pub fn default_elbow(anchor: [f64; 3], frame: &Frame) -> [f64; 3] {
339 add(anchor, add(scale(frame.right, 3.0 * frame.height), scale(frame.up, 4.0 * frame.height)))
340}
341
342pub const RING: f64 = 2.2;
346
347pub fn text_width(text: &str, height: f64) -> f64 {
350 text.chars().count() as f64 * height * 0.8
351}
352
353pub fn present_row(row: &super::PmiAnnotationReport, style: &LayoutStyle) -> Option<Presentation> {
358 let symbol = row.weld_symbol.as_ref()?;
359 let PmiGeometry::Leader { targets, .. } = &row.geometry else { return None };
360 let anchor = *targets.first()?;
361 let plane = row.plane.or(style.plane);
362 let frame = match plane {
363 Some(plane) => Frame::from_plane(plane.normal, plane.x_axis, style.text_height, style.arrow),
364 None => Frame::from_view(style.view_dir, style.view_up, style.text_height, style.arrow),
365 };
366 let elbow = plane.map_or(row.label_world, |plane| plane.project(row.label_world));
367 Some(present(symbol, anchor, elbow, &frame))
368}
369
370pub fn present(symbol: &WeldSymbol, anchor: [f64; 3], elbow: [f64; 3], frame: &Frame) -> Presentation {
373 let h = frame.height;
374 let (u, v) = (frame.right, frame.up);
375 let s = if dot(sub(elbow, anchor), u) >= 0.0 { 1.0 } else { -1.0 };
377 let at = |x: f64, y: f64| add(elbow, add(scale(u, s * x), scale(v, y)));
378 let size = symbol.size.clone();
379 let length = symbol.length.clone();
380 let tail = symbol.tail.clone();
381 let label_room = text_width(&size, h) + text_width(&length, h) + 4.0 * h;
382 let near_text = if s > 0.0 { text_width(&size, h) } else { text_width(&length, h) };
386 let centre = RING * h + 0.9 * h + near_text + 0.5 * h;
387 let line_length = (centre / h + 4.5).max(label_room / h + 2.0 + RING) * h;
388 let mut drawn = Presentation::default();
389 let mut texts: Vec<TextRun> = Vec::new();
390
391 drawn.polylines.push(vec![elbow, anchor]);
393 let to_anchor = sub(anchor, elbow);
394 let distance = dot(to_anchor, to_anchor).sqrt();
395 if distance > 1e-9 {
396 let d = scale(to_anchor, 1.0 / distance);
397 let head = frame.arrow.min(distance * 0.5);
398 let side = normalize(cross(cross(u, v), d));
399 let base = sub(anchor, scale(d, head));
400 drawn.arrows.push([anchor, add(base, scale(side, head * 0.3)), sub(base, scale(side, head * 0.3))]);
401 }
402
403 drawn.polylines.push(vec![at(0.0, 0.0), at(line_length, 0.0)]);
405
406 let iso = symbol.standard == Standard::Iso;
408 let dashed_y = -0.6 * h;
409 if iso && symbol.side != Side::Both {
410 let (dash, gap) = (0.5 * h, 0.25 * h);
411 let mut x = 0.0;
412 while x < line_length {
413 let end = (x + dash).min(line_length);
414 drawn.polylines.push(vec![at(x, dashed_y), at(end, dashed_y)]);
415 x += dash + gap;
416 }
417 }
418
419 let left = if s > 0.0 { centre - 0.5 * h } else { centre + 0.5 * h };
423 let screen_x = |k: f64| if s > 0.0 { left + k * h } else { left - k * h };
424 let mut glyph = |base_y: f64, toward: f64, dx: f64| {
426 let sx = |k: f64| screen_x(k + dx);
427 let y = |k: f64| base_y + toward * k * h;
428 let pt = |kx: f64, ky: f64| at(sx(kx), y(ky));
429 let arc = |cx: f64, cy: f64, r: f64, a0: f64, a1: f64| -> Vec<[f64; 3]> {
432 (0..=16).map(|k| {
433 let a = a0 + (a1 - a0) * k as f64 / 16.0;
434 pt(cx + r * a.cos(), cy + r * a.sin())
435 }).collect()
436 };
437 match symbol.glyph {
438 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)]),
439 Glyph::Square => {
440 drawn.polylines.push(vec![pt(0.3, 0.0), pt(0.3, 1.0)]);
441 drawn.polylines.push(vec![pt(0.7, 0.0), pt(0.7, 1.0)]);
442 }
443 Glyph::V => drawn.polylines.push(vec![pt(0.0, 1.0), pt(0.5, 0.0), pt(1.0, 1.0)]),
444 Glyph::Bevel => {
445 drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
446 drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.9, 1.0)]);
447 }
448 Glyph::U => {
449 let mut line = vec![pt(0.0, 1.0), pt(0.25, 0.55)];
450 line.extend(arc(0.5, 0.55, 0.25, std::f64::consts::PI, 2.0 * std::f64::consts::PI).into_iter().skip(1));
451 line.push(pt(1.0, 1.0));
452 drawn.polylines.push(vec![pt(0.5, 0.0), pt(0.5, 0.3)]);
453 drawn.polylines.push(line);
454 }
455 Glyph::J => {
456 drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
457 let mut line = arc(0.2, 0.55, 0.35, -std::f64::consts::FRAC_PI_2, 0.0);
458 line.push(pt(0.9, 1.0));
459 drawn.polylines.push(line);
460 }
461 Glyph::FlareV => {
464 let reach = (0.5_f64 / 0.6).asin();
465 drawn.polylines.push(arc(-0.15, 0.5, 0.6, -reach, reach));
466 drawn.polylines.push(arc(1.15, 0.5, 0.6, std::f64::consts::PI - reach, std::f64::consts::PI + reach));
467 }
468 Glyph::FlareBevel => {
469 let reach = (0.5_f64 / 0.6).asin();
470 drawn.polylines.push(vec![pt(0.2, 0.0), pt(0.2, 1.0)]);
471 drawn.polylines.push(arc(1.15, 0.5, 0.6, std::f64::consts::PI - reach, std::f64::consts::PI + reach));
472 }
473 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)]),
474 Glyph::Spot => drawn.polylines.push(arc(0.5, 0.4, 0.4, 0.0, std::f64::consts::TAU)),
475 Glyph::Seam => {
476 drawn.polylines.push(arc(0.5, 0.4, 0.4, 0.0, std::f64::consts::TAU));
477 drawn.polylines.push(vec![pt(-0.1, 0.3), pt(1.1, 0.3)]);
478 drawn.polylines.push(vec![pt(-0.1, 0.5), pt(1.1, 0.5)]);
479 }
480 Glyph::Surfacing => {
481 drawn.polylines.push(arc(0.25, 0.0, 0.25, 0.0, std::f64::consts::PI));
482 drawn.polylines.push(arc(0.75, 0.0, 0.25, 0.0, std::f64::consts::PI));
483 }
484 }
485 let text_y = base_y + toward * 0.7 * h;
488 let (lx, rx) = (sx(0.0), sx(1.0));
489 if !size.is_empty() {
490 let offset = 0.3 * h + text_width(&size, h) * 0.5;
491 let x = if s > 0.0 { lx - offset } else { lx + offset };
492 texts.push(run(&size, at(x, text_y), u, v, h));
493 }
494 if !length.is_empty() {
495 let offset = 0.3 * h + text_width(&length, h) * 0.5;
496 let x = if s > 0.0 { rx + offset } else { rx - offset };
497 texts.push(run(&length, at(x, text_y), u, v, h));
498 }
499 };
500 let (arrow_side, other_side) = if iso { ((0.0, 1.0), (dashed_y, -1.0)) } else { ((0.0, -1.0), (0.0, 1.0)) };
503 match symbol.side {
504 Side::Arrow => glyph(arrow_side.0, arrow_side.1, 0.0),
505 Side::Other => glyph(other_side.0, other_side.1, 0.0),
506 Side::Both => {
507 glyph(0.0, -1.0, 0.0);
508 glyph(0.0, 1.0, if symbol.staggered { 1.0 } else { 0.0 });
510 }
511 }
512
513 if symbol.all_around {
516 let r = RING * h;
517 drawn.polylines.push((0..=32).map(|k| {
518 let a = k as f64 / 32.0 * std::f64::consts::TAU;
519 add(elbow, add(scale(u, r * a.cos()), scale(v, r * a.sin())))
520 }).collect());
521 }
522 if symbol.field_weld {
525 let top = at(0.0, (RING + 1.0) * h);
526 drawn.polylines.push(vec![elbow, top]);
527 drawn.arrows.push([top, at(0.0, (RING + 0.4) * h), at(0.9 * h, (RING + 0.7) * h)]);
528 }
529 if !tail.is_empty() {
531 let end = at(line_length, 0.0);
532 let k = 0.8 * h * std::f64::consts::FRAC_1_SQRT_2;
533 drawn.polylines.push(vec![at(line_length + k, k), end, at(line_length + k, -k)]);
534 let x = line_length + k + 0.3 * h + text_width(&tail, h) * 0.5;
535 texts.push(run(&tail, at(x, 0.0), u, v, h));
536 }
537
538 drawn.text_anchor = elbow;
539 drawn.texts = texts;
540 drawn
541}
542
543fn run(text: &str, anchor: [f64; 3], right: [f64; 3], up: [f64; 3], height: f64) -> TextRun {
544 TextRun { text: text.to_string(), anchor, right, up, height }
545}
546