1use serde::{Deserialize, Serialize};
49
50use super::{SceneMap, SelectionGeometry, Vec3};
51
52const EDGE_SAMPLES: usize = 16;
56const SPHERE_SAMPLES: usize = 16;
59const PARALLEL: f64 = 1e-6;
61const TERMINAL_TOLERANCE: f64 = 1e-4;
64const DISTINCT_ENDS: f64 = 0.85;
67const RELATIVE_TOLERANCE: f64 = 1e-6;
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum ContactRule {
73 Axis,
75 Caps,
77 Direction,
79}
80
81impl ContactRule {
82 pub fn as_str(self) -> &'static str {
84 match self {
85 ContactRule::Axis => "axis",
86 ContactRule::Caps => "caps",
87 ContactRule::Direction => "direction",
88 }
89 }
90}
91
92#[derive(Debug, Clone, Copy)]
95pub struct ContactAxis {
96 pub axis: Vec3,
100 pub plus_end: Vec3,
102 pub minus_end: Vec3,
104 pub plus_outward: Vec3,
106 pub minus_outward: Vec3,
108 pub wire_at_plus: bool,
110 pub rule: ContactRule,
112}
113
114impl ContactAxis {
115 pub fn wire_end(&self) -> Vec3 {
117 if self.wire_at_plus {
118 self.plus_end
119 } else {
120 self.minus_end
121 }
122 }
123
124 pub fn other_end(&self) -> Vec3 {
126 if self.wire_at_plus {
127 self.minus_end
128 } else {
129 self.plus_end
130 }
131 }
132
133 pub fn outward(&self) -> Vec3 {
135 if self.wire_at_plus {
136 self.plus_outward
137 } else {
138 self.minus_outward
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146#[serde(rename_all = "camelCase")]
147pub struct PortContactRow {
148 pub body: String,
150 pub end: String,
153 pub axis: [f64; 3],
155 pub wire_end: [f64; 3],
157 pub other_end: [f64; 3],
159 pub seats_origin: bool,
162 #[serde(default)]
164 pub rule: String,
165}
166
167pub fn contact_body_solid(scene: &SceneMap, name: &str) -> Option<u32> {
171 let name = name.trim();
172 if name.is_empty() {
173 return None;
174 }
175 scene.resolve_solid(name)
176}
177
178pub fn contact_body_axis(scene: &SceneMap, name: &str, reverse: bool) -> Result<ContactAxis, String> {
183 contact_body_end(scene, name, reverse, None)
184}
185
186pub fn contact_body_end(
193 scene: &SceneMap,
194 name: &str,
195 reverse: bool,
196 direction: Option<Vec3>,
197) -> Result<ContactAxis, String> {
198 let name = name.trim();
199 let handle = contact_body_solid(scene, name)
200 .ok_or_else(|| format!("contact body '{name}' is not a solid of this part"))?;
201 let (ends, scale) = crate::with_registered_solid_str(handle, |solid| body_ends(solid, name, direction))?;
202 let mut wire_at_plus = match ends.toward {
203 Some(toward) => toward,
205 None => {
207 let mut plus_side = true;
208 if let Some(centre) = rest_of_part_centre(scene, handle) {
209 let plus = ends.plus_end.sub(centre).length();
210 let minus = ends.minus_end.sub(centre).length();
211 if (plus - minus).abs() > RELATIVE_TOLERANCE * scale {
212 plus_side = plus > minus;
213 }
214 }
215 plus_side
216 }
217 };
218 if reverse {
219 wire_at_plus = !wire_at_plus;
220 }
221 Ok(ContactAxis {
222 axis: ends.axis,
223 plus_end: ends.plus_end,
224 minus_end: ends.minus_end,
225 plus_outward: ends.plus_outward,
226 minus_outward: ends.minus_outward,
227 wire_at_plus,
228 rule: ends.rule,
229 })
230}
231
232struct Ends {
234 axis: Vec3,
235 plus_end: Vec3,
236 minus_end: Vec3,
237 plus_outward: Vec3,
238 minus_outward: Vec3,
239 rule: ContactRule,
240 toward: Option<bool>,
243}
244
245fn body_ends(solid: &crate::BrepSolid, name: &str, direction: Option<Vec3>) -> Result<(Ends, f64), String> {
247 let scale = solid_scale(solid);
248 let points = body_points(solid);
249 if points.is_empty() {
250 return Err(format!("contact body '{name}' has no geometry to measure"));
251 }
252 let tolerance = RELATIVE_TOLERANCE * scale;
253
254 let mut groups: Vec<(Vec3, Vec3)> = Vec::new();
257 let mut spheres: Vec<(&crate::FaceRecord, Vec3, f64)> = Vec::new();
258 let mut planes: Vec<(&crate::FaceRecord, Vec3)> = Vec::new();
259 let mut round_tips: Vec<(&crate::FaceRecord, Vec3, Vec3)> = Vec::new();
262 for shell in &solid.shells {
263 for face in &shell.faces {
264 match crate::resolve_face_selection(solid, face.id) {
265 Ok(SelectionGeometry::Axis { origin, direction, radius }) => {
266 let Ok(direction) = direction.normalized() else { continue };
267 let direction = canonical(direction);
268 if radius.is_none() {
269 round_tips.push((face, origin, direction));
270 }
271 let known = groups
272 .iter()
273 .any(|(o, d)| collinear(*o, *d, origin, direction, tolerance));
274 if !known {
275 groups.push((origin, direction));
276 }
277 }
278 Ok(SelectionGeometry::Sphere { center, radius }) => spheres.push((face, center, radius)),
279 Ok(SelectionGeometry::Plane { normal, .. }) => {
280 if let Ok(normal) = normal.normalized() {
281 planes.push((face, normal));
282 }
283 }
284 _ => {}
285 }
286 }
287 }
288
289 if let [(origin, axis)] = groups.as_slice() {
290 let (origin, axis) = (*origin, *axis);
291 let (low, high) = axial_extent(&points, &spheres, origin, axis, tolerance);
292 if high - low <= RELATIVE_TOLERANCE * scale {
293 return Err(format!("contact body '{name}' has no length along its axis"));
294 }
295 let ends = Ends {
296 axis,
297 plus_end: origin.add(axis.scale(high)),
298 minus_end: origin.add(axis.scale(low)),
299 plus_outward: axis,
300 minus_outward: axis.scale(-1.0),
301 rule: ContactRule::Axis,
302 toward: None,
303 };
304 return Ok((ends, scale));
305 }
306
307 let slack = TERMINAL_TOLERANCE * scale;
311 let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
312 let body_centre = bbox_centre(&points);
313 let mut caps: Vec<Cap> = Vec::new();
314 for (face, normal) in &planes {
315 if let Some(centre) = boundary_centroid(solid, face) {
316 if behind(centre, *normal) {
317 caps.push(Cap { point: centre, outward: *normal, line: None });
318 }
319 }
320 }
321 for (face, center, _) in &spheres {
322 if let Some(pole) = sphere_tip(face, body_centre) {
323 if let Ok(outward) = pole.sub(*center).normalized() {
324 if behind(pole, outward) {
325 caps.push(Cap { point: pole, outward, line: Some((*center, outward)) });
326 }
327 }
328 }
329 }
330 for (face, origin, axis) in &round_tips {
331 if let Some(tip) = axial_tip(face, *origin, *axis, body_centre) {
332 if behind(tip.point, tip.outward) {
333 caps.push(tip);
334 }
335 }
336 }
337 let mut ends: Vec<Cap> = Vec::new();
340 for cap in caps {
341 match ends.iter_mut().find(|end| end.point.sub(cap.point).length() <= slack) {
342 Some(end) => {
343 if end.line.is_none() {
344 end.line = cap.line;
345 }
346 }
347 None => ends.push(cap),
348 }
349 }
350 if ends.len() < 2 && planes.len() == 2 {
351 let two: Vec<Cap> = planes
355 .iter()
356 .filter_map(|(face, normal)| {
357 boundary_centroid(solid, face).map(|centre| Cap { point: centre, outward: *normal, line: None })
358 })
359 .collect();
360 if two.len() == 2 && !same_end(&two[0], &two[1]) {
361 ends = two;
362 }
363 }
364 if let Some((a, b)) = distinct_ends(&ends, tolerance) {
365 let (mut a, mut b) = (ends[a], ends[b]);
366 a.point = on_line_of(a, &b);
369 b.point = on_line_of(b, &a);
370 if let Ok(chord) = a.point.sub(b.point).normalized() {
371 let axis = canonical(chord);
372 let (plus, minus) = if a.point.dot(axis) >= b.point.dot(axis) { (a, b) } else { (b, a) };
373 let ends = Ends {
374 axis,
375 plus_end: plus.point,
376 minus_end: minus.point,
377 plus_outward: plus.outward,
378 minus_outward: minus.outward,
379 rule: ContactRule::Caps,
380 toward: None,
381 };
382 return Ok((ends, scale));
383 }
384 }
385
386 let Some(direction) = direction.and_then(|d| d.normalized().ok()) else {
388 return Err(format!(
389 "contact body '{name}' has no distinct ends to take a wire end from; pick a Direction (a face, an edge or an axis) to say which way the wire leaves"
390 ));
391 };
392 let axis = canonical(direction);
393 let extreme = |toward: Vec3| -> Vec3 {
394 for (face, normal) in &planes {
396 if normal.dot(toward) >= 1.0 - PARALLEL {
397 if let Some(centre) = boundary_centroid(solid, face) {
398 if behind(centre, *normal) {
399 return centre;
400 }
401 }
402 }
403 }
404 let top = points.iter().map(|p| p.dot(toward)).fold(f64::NEG_INFINITY, f64::max);
406 let at_top: Vec<Vec3> = points.iter().copied().filter(|p| top - p.dot(toward) <= slack).collect();
407 bbox_centre(&at_top)
408 };
409 let plus_end = extreme(axis);
410 let minus_end = extreme(axis.scale(-1.0));
411 if plus_end.sub(minus_end).dot(axis) <= RELATIVE_TOLERANCE * scale {
412 return Err(format!("contact body '{name}' has no length along its Direction"));
413 }
414 let ends = Ends {
415 axis,
416 plus_end,
417 minus_end,
418 plus_outward: axis,
419 minus_outward: axis.scale(-1.0),
420 rule: ContactRule::Direction,
421 toward: Some(direction.dot(axis) > 0.0),
422 };
423 Ok((ends, scale))
424}
425
426fn axial_extent(
430 points: &[Vec3],
431 spheres: &[(&crate::FaceRecord, Vec3, f64)],
432 origin: Vec3,
433 axis: Vec3,
434 tolerance: f64,
435) -> (f64, f64) {
436 let mut low = f64::INFINITY;
437 let mut high = f64::NEG_INFINITY;
438 let mut include = |point: Vec3| {
439 let t = point.sub(origin).dot(axis);
440 low = low.min(t);
441 high = high.max(t);
442 };
443 for point in points {
444 include(*point);
445 }
446 for (face, center, _) in spheres {
447 if off_axis(origin, axis, *center) > tolerance {
448 continue;
449 }
450 for point in sphere_samples(face) {
451 include(point);
452 }
453 }
454 (low, high)
455}
456
457fn body_points(solid: &crate::BrepSolid) -> Vec<Vec3> {
460 let mut points: Vec<Vec3> = solid.vertices.iter().map(|vertex| vertex.point).collect();
461 for edge in &solid.edges {
462 if edge.degenerate {
463 continue;
464 }
465 for i in 0..=EDGE_SAMPLES {
466 let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
467 if let Ok(point) = edge.curve.evaluate(t) {
468 points.push(point);
469 }
470 }
471 }
472 points
473}
474
475fn sphere_samples(face: &crate::FaceRecord) -> Vec<Vec3> {
478 let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return Vec::new() };
479 let mut out = Vec::new();
480 for i in 0..=SPHERE_SAMPLES {
481 for j in 0..=SPHERE_SAMPLES {
482 let s = u[0] + (u[1] - u[0]) * (i as f64 / SPHERE_SAMPLES as f64);
483 let t = v[0] + (v[1] - v[0]) * (j as f64 / SPHERE_SAMPLES as f64);
484 if let Ok(point) = face.surface.evaluate(s, t) {
485 out.push(point);
486 }
487 }
488 }
489 out
490}
491
492fn sphere_tip(face: &crate::FaceRecord, body_centre: Vec3) -> Option<Vec3> {
495 sphere_samples(face)
496 .into_iter()
497 .max_by(|a, b| a.sub(body_centre).length().total_cmp(&b.sub(body_centre).length()))
498}
499
500fn boundary_centroid(solid: &crate::BrepSolid, face: &crate::FaceRecord) -> Option<Vec3> {
503 let mut sum = Vec3::new(0.0, 0.0, 0.0);
504 let mut length = 0.0;
505 for edge_id in face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)) {
506 let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else { continue };
507 if edge.degenerate {
508 continue;
509 }
510 let samples: Vec<Vec3> = (0..=EDGE_SAMPLES)
511 .filter_map(|i| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64)).ok())
512 .collect();
513 for pair in samples.windows(2) {
514 let piece = pair[1].sub(pair[0]).length();
515 sum = sum.add(pair[0].add(pair[1]).scale(0.5 * piece));
516 length += piece;
517 }
518 }
519 (length > 0.0).then(|| sum.scale(1.0 / length))
520}
521
522fn distinct_ends(caps: &[Cap], tolerance: f64) -> Option<(usize, usize)> {
525 let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
526 for i in 0..caps.len() {
527 for j in i + 1..caps.len() {
528 pairs.push((caps[i].point.sub(caps[j].point).length(), i, j));
529 }
530 }
531 pairs.sort_by(|a, b| b.0.total_cmp(&a.0));
532 let &(best, i, j) = pairs.first()?;
533 if best <= tolerance {
534 return None;
535 }
536 let rival = pairs.iter().skip(1).any(|&(d, k, l)| (k, l) != (i, j) && d >= DISTINCT_ENDS * best);
537 (!rival).then_some((i, j))
538}
539
540#[derive(Debug, Clone, Copy)]
543pub(super) struct Cap {
544 pub(super) point: Vec3,
545 pub(super) outward: Vec3,
546 pub(super) line: Option<(Vec3, Vec3)>,
547}
548
549fn axial_tip(face: &crate::FaceRecord, origin: Vec3, axis: Vec3, body_centre: Vec3) -> Option<Cap> {
553 let samples = sphere_samples(face);
554 if samples.is_empty() {
555 return None;
556 }
557 let along: Vec<f64> = samples.iter().map(|p| p.sub(origin).dot(axis)).collect();
558 let mean = along.iter().sum::<f64>() / along.len() as f64;
559 let centre = body_centre.sub(origin).dot(axis);
560 let (t, outward) = if mean >= centre {
561 (along.iter().copied().fold(f64::NEG_INFINITY, f64::max), axis)
562 } else {
563 (along.iter().copied().fold(f64::INFINITY, f64::min), axis.scale(-1.0))
564 };
565 Some(Cap { point: origin.add(axis.scale(t)), outward, line: Some((origin, axis)) })
566}
567
568fn on_line_of(end: Cap, other: &Cap) -> Vec3 {
571 let (Some((origin, direction)), None) = (other.line, end.line) else { return end.point };
572 let Ok(direction) = direction.normalized() else { return end.point };
573 if end.outward.dot(direction).abs() < 1.0 - PARALLEL {
574 return end.point;
575 }
576 origin.add(direction.scale(end.point.sub(origin).dot(direction)))
577}
578
579pub(super) fn same_end(a: &Cap, b: &Cap) -> bool {
583 let apart = a.point.sub(b.point);
584 let length = apart.length();
585 a.outward.dot(b.outward) > 0.9 && (length == 0.0 || apart.dot(a.outward).abs() >= 0.9 * length)
586}
587
588fn bbox_centre(points: &[Vec3]) -> Vec3 {
590 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
591 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
592 for p in points {
593 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
594 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
595 }
596 low.add(high).scale(0.5)
597}
598
599fn rest_of_part_centre(scene: &SceneMap, body: u32) -> Option<Vec3> {
603 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
604 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
605 let mut any = false;
606 let mut handles: Vec<u32> = scene.solids.values().copied().filter(|h| *h != body).collect();
607 handles.sort_unstable();
608 handles.dedup();
609 for handle in handles {
610 let Ok((a, b)) = crate::feature_pipeline::pmi::resolve::solid_bbox(handle) else { continue };
611 low = Vec3::new(low.x.min(a.x), low.y.min(a.y), low.z.min(a.z));
612 high = Vec3::new(high.x.max(b.x), high.y.max(b.y), high.z.max(b.z));
613 any = true;
614 }
615 any.then(|| low.add(high).scale(0.5))
616}
617
618fn canonical(direction: Vec3) -> Vec3 {
621 let [x, y, z] = [direction.x, direction.y, direction.z];
622 let largest = if x.abs() >= y.abs() && x.abs() >= z.abs() {
623 x
624 } else if y.abs() >= z.abs() {
625 y
626 } else {
627 z
628 };
629 if largest < 0.0 {
630 direction.scale(-1.0)
631 } else {
632 direction
633 }
634}
635
636fn collinear(o1: Vec3, d1: Vec3, o2: Vec3, d2: Vec3, tolerance: f64) -> bool {
638 d1.cross(d2).length() <= PARALLEL && off_axis(o1, d1, o2) <= tolerance.max(1e-9)
639}
640
641fn off_axis(origin: Vec3, axis: Vec3, point: Vec3) -> f64 {
643 let offset = point.sub(origin);
644 offset.sub(axis.scale(offset.dot(axis))).length()
645}
646
647fn solid_scale(solid: &crate::BrepSolid) -> f64 {
649 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
650 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
651 for vertex in &solid.vertices {
652 let p = vertex.point;
653 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
654 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
655 }
656 if solid.vertices.is_empty() {
657 return 1.0;
658 }
659 high.sub(low).length().max(1.0)
660}