1use super::*;
2use crate::{classify_point, PointClass, SolidClassifier};
3use serde::{Deserialize, Serialize};
4
5pub(super) fn ruled_between(bottom: &NurbsCurve, top: &NurbsCurve) -> Result<NurbsSurface, String> {
10 if bottom.degree != top.degree
11 || bottom.control_points.len() != top.control_points.len()
12 || bottom.knots.len() != top.knots.len()
13 {
14 return Err("ruled_between: rows are not representation-compatible".into());
15 }
16 let grid = bottom
17 .control_points
18 .iter()
19 .zip(&top.control_points)
20 .map(|(a, b)| vec![*a, *b])
21 .collect();
22 NurbsSurface::new(
23 bottom.degree,
24 1,
25 bottom.knots.clone(),
26 vec![0.0, 0.0, 1.0, 1.0],
27 grid,
28 )
29}
30
31pub(super) fn arc_window_subrange(row: &NurbsCurve, start: Vec3, end: Vec3) -> Result<NurbsCurve, String> {
36 let [d0, d1] = row.domain()?;
37 let span = d1 - d0;
38 let u0 = project_point_to_curve(row, start)?.u;
39 let u1 = project_point_to_curve(row, end)?.u;
40 if u1 <= u0 + 1e-12 {
41 return Err("draftExtrude: a drafted arc's boundary trim inverted".into());
42 }
43 let epsilon = span * 1e-9;
44 let mut current = row.clone();
45 if u0 > d0 + epsilon {
46 current = current.split(u0)?.1;
47 }
48 let domain = current.domain()?;
49 if u1 < domain[1] - epsilon && u1 > domain[0] + epsilon {
50 current = current.split(u1)?.0;
51 }
52 Ok(current)
53}
54
55fn wall_gradient(
61 seg: &SegGeom,
62 point: Vec3,
63 zh: Vec3,
64 height: f64,
65 signed_d: f64,
66) -> Result<Vec3, String> {
67 match seg {
68 SegGeom::Line { dir, normal, .. } => dir
69 .cross(normal.scale(signed_d).add(zh.scale(height)))
70 .normalized(),
71 SegGeom::Arc {
72 center, turn, ..
73 } => {
74 let rel = point.sub(*center);
75 let radial = rel.sub(zh.scale(rel.dot(zh)));
76 let rho = radial.normalized()?;
77 rho.add(zh.scale(signed_d * turn / height)).normalized()
78 }
79 }
80}
81
82#[allow(clippy::too_many_arguments)]
92pub(super) fn junction_edge_curve(
93 prev: &SegGeom,
94 next: &SegGeom,
95 a: Vec3,
96 m: Vec3,
97 b: Vec3,
98 zh: Vec3,
99 height: f64,
100 signed_d: f64,
101) -> Result<NurbsCurve, String> {
102 let chord = b.sub(a);
103 let length = chord.length();
104 if length <= 1e-12 {
105 return Err("draftExtrude: a junction edge collapsed to a point".into());
106 }
107 let along = m.sub(a).dot(chord) / (length * length);
108 let deviation = m.sub(a).sub(chord.scale(along)).length();
109 if deviation <= length * 1e-9 {
110 return make_line(a, b);
111 }
112 let e1 = chord.scale(1.0 / length);
114 let plane_normal = chord.cross(m.sub(a)).normalized()?;
115 let e2 = plane_normal.cross(e1).normalized()?;
116 let orient = |tangent: Vec3| {
117 if tangent.dot(zh) < 0.0 {
118 tangent.scale(-1.0)
119 } else {
120 tangent
121 }
122 };
123 let t0 = orient(wall_gradient(prev, a, zh, height, signed_d)?
124 .cross(wall_gradient(next, a, zh, height, signed_d)?));
125 let t2 = orient(wall_gradient(prev, b, zh, height, signed_d)?
126 .cross(wall_gradient(next, b, zh, height, signed_d)?));
127 let d0 = (t0.dot(e1), t0.dot(e2));
128 let d2 = (t2.dot(e1), t2.dot(e2));
129 let denom = d0.0 * d2.1 - d0.1 * d2.0;
130 let scale0 = d0.0.hypot(d0.1);
131 let scale2 = d2.0.hypot(d2.1);
132 if denom.abs() <= 1e-14 * scale0 * scale2 {
133 return Err("draftExtrude: junction end tangents are parallel — no conic apex".into());
134 }
135 let s = length * d2.1 / denom;
137 let apex = (s * d0.0, s * d0.1);
138 if apex.1.abs() <= f64::EPSILON * length {
139 return Err("draftExtrude: junction conic apex is degenerate".into());
140 }
141 let mq = (m.sub(a).dot(e1), m.sub(a).dot(e2));
143 let beta = mq.1 / apex.1;
144 let gamma = (mq.0 - beta * apex.0) / length;
145 let alpha = 1.0 - beta - gamma;
146 if !(alpha > 0.0 && beta > 0.0 && gamma > 0.0) {
147 return Err(format!(
148 "draftExtrude: junction conic witness fell outside its control triangle \
149 (α={alpha:.3e} β={beta:.3e} γ={gamma:.3e})"
150 ));
151 }
152 let weight = beta / (2.0 * (alpha * gamma).sqrt());
153 let apex_3d = a.add(e1.scale(apex.0)).add(e2.scale(apex.1));
154 NurbsCurve::new(
155 2,
156 vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
157 vec![
158 Vec4::from_point(a, 1.0),
159 Vec4::from_point(apex_3d, weight),
160 Vec4::from_point(b, 1.0),
161 ],
162 )
163}
164
165fn circumcircle(a: Vec3, b: Vec3, c: Vec3, ex: Vec3, ey: Vec3, np: Vec3) -> Option<(Vec3, f64)> {
168 let (ax, ay) = (a.dot(ex), a.dot(ey));
169 let (bx, by) = (b.dot(ex), b.dot(ey));
170 let (cx, cy) = (c.dot(ex), c.dot(ey));
171 let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
172 if d.abs() < 1e-12 {
173 return None;
174 }
175 let a2 = ax * ax + ay * ay;
176 let b2 = bx * bx + by * by;
177 let c2 = cx * cx + cy * cy;
178 let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
179 let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
180 let plane_off = a.dot(np);
181 let center = ex.scale(ux).add(ey.scale(uy)).add(np.scale(plane_off));
182 let radius = a.sub(center).length();
183 Some((center, radius))
184}
185
186fn intersect_offset_line_circle(
190 line_point: Vec3,
191 line_dir: Vec3,
192 center: Vec3,
193 radius: f64,
194 near: Vec3,
195) -> Result<Vec3, String> {
196 let dir = line_dir.normalized()?;
197 let f = line_point.sub(center);
198 let b = f.dot(dir);
199 let c = f.dot(f) - radius * radius;
200 let disc = b * b - c;
201 if disc < -1e-9 {
202 return Err("an offset line and arc no longer meet (offset too large)".into());
203 }
204 let root = disc.max(0.0).sqrt();
205 let p1 = line_point.add(dir.scale(-b + root));
206 let p2 = line_point.add(dir.scale(-b - root));
207 Ok(if p1.sub(near).length() <= p2.sub(near).length() {
208 p1
209 } else {
210 p2
211 })
212}
213
214fn intersect_offset_circles(
218 c1: Vec3,
219 r1: f64,
220 c2: Vec3,
221 r2: f64,
222 plane_normal: Vec3,
223 near: Vec3,
224) -> Result<Vec3, String> {
225 let between = c2.sub(c1);
226 let d = between.length();
227 if d < 1e-9 {
228 return Err("concentric offset arcs do not meet".into());
229 }
230 let axis = between.scale(1.0 / d);
231 let a = (d * d + r1 * r1 - r2 * r2) / (2.0 * d);
232 let h2 = r1 * r1 - a * a;
233 if h2 < -1e-9 {
234 return Err("offset arcs no longer meet (offset too large)".into());
235 }
236 let h = h2.max(0.0).sqrt();
237 let base = c1.add(axis.scale(a));
238 let perp = plane_normal.cross(axis).normalized()?;
239 let p1 = base.add(perp.scale(h));
240 let p2 = base.sub(perp.scale(h));
241 Ok(if p1.sub(near).length() <= p2.sub(near).length() {
242 p1
243 } else {
244 p2
245 })
246}
247
248pub(super) enum SegGeom {
252 Line {
253 start: Vec3,
254 end: Vec3,
255 dir: Vec3,
257 normal: Vec3,
259 },
260 Arc {
261 center: Vec3,
262 radius: f64,
263 turn: f64,
266 arc_normal: Vec3,
268 start: Vec3,
269 end: Vec3,
270 },
271}
272
273impl SegGeom {
274 fn start(&self) -> Vec3 {
275 match self {
276 SegGeom::Line { start, .. } | SegGeom::Arc { start, .. } => *start,
277 }
278 }
279
280 fn end(&self) -> Vec3 {
281 match self {
282 SegGeom::Line { end, .. } | SegGeom::Arc { end, .. } => *end,
283 }
284 }
285
286 fn offset_point(&self, point: Vec3, signed_d: f64) -> Result<Vec3, String> {
290 match self {
291 SegGeom::Line { normal, .. } => Ok(point.add(normal.scale(signed_d))),
292 SegGeom::Arc {
293 center,
294 radius,
295 turn,
296 ..
297 } => {
298 let r_offset = radius - signed_d * turn;
299 if r_offset <= 1e-6 {
300 return Err("offset: distance is too large — a concave arc collapses".into());
301 }
302 Ok(center.add(point.sub(*center).scale(r_offset / radius)))
303 }
304 }
305 }
306}
307
308pub(super) fn classify_profile_segments(
314 profile: &[NurbsCurve],
315 plane_normal: Vec3,
316) -> Result<Vec<SegGeom>, String> {
317 let tol = 1e-6;
318 if profile.is_empty() {
319 return Err("offset: profile has no segments".into());
320 }
321 let np = plane_normal.normalized()?;
322 let ex = np.perpendicular()?;
323 let ey = np.cross(ex).normalized()?;
324 let mut segs = Vec::with_capacity(profile.len());
325 for curve in profile {
326 let [t0, t1] = curve.domain()?;
327 let start = curve.evaluate(t0)?;
328 let end = curve.evaluate(t1)?;
329 let chord = end.sub(start);
330 let chord_len = chord.length();
331 if chord_len <= tol {
332 return Err("offset: profile has a degenerate (zero-length) segment".into());
333 }
334 let dir = chord.scale(1.0 / chord_len);
335 let mut is_line = true;
337 for k in 1..8 {
338 let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0)?;
339 let rel = point.sub(start);
340 let perpendicular = rel.sub(dir.scale(rel.dot(dir))).length();
341 if perpendicular > tol * 10.0 {
342 is_line = false;
343 break;
344 }
345 }
346 if is_line {
347 segs.push(SegGeom::Line {
348 start,
349 end,
350 dir,
351 normal: np.cross(dir).normalized()?,
352 });
353 continue;
354 }
355 let mid = curve.evaluate((t0 + t1) * 0.5)?;
357 let (center, radius) = circumcircle(start, mid, end, ex, ey, np).ok_or_else(|| {
358 "offset: only straight lines and circular arcs are supported".to_string()
359 })?;
360 for k in 0..=8 {
361 let point = curve.evaluate(t0 + (t1 - t0) * k as f64 / 8.0)?;
362 if (point.sub(center).length() - radius).abs() > tol * 10.0 {
363 return Err("offset: only straight lines and circular arcs are supported".into());
364 }
365 }
366 let bend = np.dot(mid.sub(start).cross(end.sub(mid)));
368 let (arc_normal, turn) = if bend >= 0.0 {
369 (np, 1.0)
370 } else {
371 (np.scale(-1.0), -1.0)
372 };
373 segs.push(SegGeom::Arc {
374 center,
375 radius,
376 turn,
377 arc_normal,
378 start,
379 end,
380 });
381 }
382 Ok(segs)
383}
384
385pub(super) fn offset_junction(
396 prev: &SegGeom,
397 next: &SegGeom,
398 plane_normal: Vec3,
399 signed_d: f64,
400) -> Result<Vec3, String> {
401 let vertex = prev.end();
402 if signed_d == 0.0 {
403 return Ok(vertex);
404 }
405 let prev_offset = prev.offset_point(prev.end(), signed_d)?;
406 let next_offset = next.offset_point(next.start(), signed_d)?;
407 if prev_offset.sub(next_offset).length() <= 1e-6 {
408 return Ok(prev_offset.add(next_offset).scale(0.5));
409 }
410 match (prev, next) {
411 (SegGeom::Line { normal: na, .. }, SegGeom::Line { normal: nb, .. }) => {
412 let denom = 1.0 + na.dot(*nb);
413 if denom.abs() < 1e-6 {
414 return Err("offset: degenerate (near-reversal) polyline corner".into());
415 }
416 Ok(vertex.add(na.add(*nb).scale(signed_d / denom)))
417 }
418 (
419 SegGeom::Line { dir, .. },
420 SegGeom::Arc {
421 center,
422 radius,
423 turn,
424 ..
425 },
426 ) => intersect_offset_line_circle(
427 prev_offset,
428 *dir,
429 *center,
430 radius - signed_d * turn,
431 vertex,
432 ),
433 (
434 SegGeom::Arc {
435 center,
436 radius,
437 turn,
438 ..
439 },
440 SegGeom::Line { dir, .. },
441 ) => intersect_offset_line_circle(
442 next_offset,
443 *dir,
444 *center,
445 radius - signed_d * turn,
446 vertex,
447 ),
448 (
449 SegGeom::Arc {
450 center: c1,
451 radius: r1,
452 turn: turn1,
453 ..
454 },
455 SegGeom::Arc {
456 center: c2,
457 radius: r2,
458 turn: turn2,
459 ..
460 },
461 ) => intersect_offset_circles(
462 *c1,
463 r1 - signed_d * turn1,
464 *c2,
465 r2 - signed_d * turn2,
466 plane_normal,
467 vertex,
468 ),
469 }
470}
471
472fn offset_profile_segments(
483 profile: &[NurbsCurve],
484 plane_normal: Vec3,
485 signed_d: f64,
486 closed: bool,
487) -> Result<Vec<NurbsCurve>, String> {
488 let tol = 1e-6;
489 let np = plane_normal.normalized()?;
490 let segs = classify_profile_segments(profile, np)?;
491 let n = segs.len();
492
493 let mut offsets: Vec<(Vec3, Vec3)> = segs
495 .iter()
496 .map(|seg| {
497 Ok((
498 seg.offset_point(seg.start(), signed_d)?,
499 seg.offset_point(seg.end(), signed_d)?,
500 ))
501 })
502 .collect::<Result<_, String>>()?;
503 let junctions = if closed { n } else { n.saturating_sub(1) };
504 for i in 0..junctions {
505 let j = (i + 1) % n;
506 let point = offset_junction(&segs[i], &segs[j], np, signed_d)?;
507 offsets[i].1 = point;
508 offsets[j].0 = point;
509 }
510
511 let mut out = Vec::with_capacity(n);
513 for (seg, (off_start, off_end)) in segs.iter().zip(&offsets) {
514 match seg {
515 SegGeom::Line { .. } => out.push(make_line(*off_start, *off_end)?),
516 SegGeom::Arc {
517 center, arc_normal, ..
518 } => {
519 let radial = off_start.sub(*center);
520 let r2 = radial.length();
521 if r2 <= tol {
522 return Err("offset: reconstructed arc has a zero radius".into());
523 }
524 let ax = radial.scale(1.0 / r2);
525 let ay = arc_normal.cross(ax).normalized()?;
526 let ve = off_end.sub(*center);
527 let mut angle = ve.dot(ay).atan2(ve.dot(ax));
528 if angle <= 1e-9 {
529 angle += std::f64::consts::TAU;
530 }
531 out.push(make_arc(*center, ax, ay, r2, 0.0, angle)?);
532 }
533 }
534 }
535 Ok(out)
536}
537
538#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
545#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
546pub enum RibExtrusion {
547 #[default]
553 ParallelToSketch,
554 NormalToSketch,
558}
559
560pub fn rib_from_profile(
588 solid: &BrepSolid,
589 profile: &[NurbsCurve],
590 thickness: f64,
591 extrude_dir: Vec3,
592 plane_normal: Option<Vec3>,
593 extrusion: RibExtrusion,
594 name: Option<&str>,
595) -> Result<BrepSolid, String> {
596 let _ = name;
599 let tolerance = 1e-6;
600 if profile.is_empty() {
601 return Err("rib: profile needs at least 1 curve forming an open chain".into());
602 }
603 if !(thickness > 0.0) {
604 return Err("rib: thickness must be positive".into());
605 }
606
607 let mut vertices = Vec::with_capacity(profile.len() + 1);
610 let mut samples = Vec::new();
611 for (index, curve) in profile.iter().enumerate() {
612 let [start, end] = curve.domain()?;
613 let v_start = curve.evaluate(start)?;
614 let v_end = curve.evaluate(end)?;
615 if v_end.sub(v_start).length() <= tolerance {
616 return Err("rib: profile has a degenerate (zero-length) segment".into());
617 }
618 if index == 0 {
619 vertices.push(v_start);
620 } else if v_start.sub(*vertices.last().unwrap()).length() > tolerance {
621 return Err(format!(
622 "rib: profile chain is not connected at curve {index}"
623 ));
624 }
625 vertices.push(v_end);
626 let first_k = if index == 0 { 0 } else { 1 };
630 for k in first_k..=8 {
631 samples.push(curve.evaluate(start + (end - start) * k as f64 / 8.0)?);
632 }
633 }
634 let count = vertices.len();
635 if count < 2 {
636 return Err("rib: profile needs at least 2 distinct vertices".into());
637 }
638
639 if vertices[count - 1].sub(vertices[0]).length() <= tolerance {
642 return Err("rib: profile chain is closed; rib expects an open chain".into());
643 }
644
645 let np = match plane_normal {
652 Some(supplied) => supplied
653 .normalized()
654 .map_err(|_| "rib: the supplied profile plane normal is degenerate".to_string())?,
655 None => {
656 let mut normal = Vec3::default();
657 for i in 1..samples.len() - 1 {
658 let a = samples[i].sub(samples[i - 1]);
659 let b = samples[i + 1].sub(samples[i]);
660 normal = normal.add(a.cross(b));
661 }
662 normal.normalized().map_err(|_| {
663 "rib: profile is collinear and no profile plane was supplied; cannot determine \
664 its plane"
665 .to_string()
666 })?
667 }
668 };
669 let origin = vertices[0];
670 if samples
671 .iter()
672 .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
673 {
674 return Err(if plane_normal.is_some() {
675 "rib: profile does not lie in the supplied plane".into()
676 } else {
677 "rib: profile is not planar".to_string()
678 });
679 }
680
681 let reach = sweep_reach(solid, &vertices)?;
685
686 let slab = match extrusion {
689 RibExtrusion::ParallelToSketch => {
690 let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
693 let along = along.normalized().map_err(|_| {
694 "rib: a Parallel-to-Sketch rib grows INSIDE its sketch plane, but the requested \
695 direction is perpendicular to it"
696 .to_string()
697 })?;
698 parallel_slab(profile, &vertices, np, along, thickness, reach)?
699 }
700 RibExtrusion::NormalToSketch => {
701 let along = extrude_dir
702 .normalized()
703 .map_err(|_| "rib: extrude direction is degenerate".to_string())?;
704 normal_slab(profile, np, along, thickness, reach)?
705 }
706 };
707
708 let along = match extrusion {
711 RibExtrusion::ParallelToSketch => {
712 let along = extrude_dir.sub(np.scale(extrude_dir.dot(np)));
713 along.normalized()?
714 }
715 RibExtrusion::NormalToSketch => extrude_dir.normalized()?,
716 };
717 let seeds = chain_probe_seeds(profile)?;
718 let rib = up_to_next(solid, &slab, &seeds, along, reach)?;
719 let Some(rib) = rib else {
720 return Ok(solid.clone());
724 };
725
726 boolean_operation(
727 solid,
728 &rib,
729 BooleanOperation::Union,
730 &BooleanOptions::default(),
731 )
732 .map_err(|error| format!("rib: union of the rib into the part failed: {error}"))
733}
734
735fn sweep_reach(solid: &BrepSolid, chain: &[Vec3]) -> Result<f64, String> {
739 let mut min = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
740 let mut max = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
741 let mut extend = |point: Vec3| {
742 min = Vec3::new(min.x.min(point.x), min.y.min(point.y), min.z.min(point.z));
743 max = Vec3::new(max.x.max(point.x), max.y.max(point.y), max.z.max(point.z));
744 };
745 for vertex in &solid.vertices {
746 extend(vertex.point);
747 }
748 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
749 for row in &face.surface.control_points {
750 for point in row {
751 extend(point.point()?);
752 }
753 }
754 }
755 for point in chain {
756 extend(*point);
757 }
758 let diagonal = max.sub(min).length();
759 if !(diagonal > 0.0) || !diagonal.is_finite() {
760 return Err("rib: the target solid has no extent to grow the rib against".into());
761 }
762 Ok(diagonal * 2.0)
763}
764
765fn chain_probe_seeds(profile: &[NurbsCurve]) -> Result<Vec<Vec3>, String> {
773 let mut seeds = Vec::with_capacity(profile.len());
774 for curve in profile {
775 let [start, end] = curve.domain()?;
776 seeds.push(curve.evaluate(start + (end - start) * 0.5)?);
777 }
778 if seeds.is_empty() {
779 return Err("rib: profile has no points to grow from".into());
780 }
781 Ok(seeds)
782}
783
784fn parallel_slab(
791 profile: &[NurbsCurve],
792 vertices: &[Vec3],
793 np: Vec3,
794 along: Vec3,
795 thickness: f64,
796 reach: f64,
797) -> Result<BrepSolid, String> {
798 let offset = along.scale(reach);
799 let chain_start = vertices[0];
800 let chain_end = *vertices.last().expect("chain has vertices");
801 let mut region: Vec<NurbsCurve> = Vec::with_capacity(profile.len() * 2 + 2);
802 for curve in profile {
803 region.push(curve.clone());
804 }
805 region.push(make_line(chain_end, chain_end.add(offset))?);
806 for curve in profile.iter().rev() {
807 region.push(super::extrude::translated_curve(&curve.reversed()?, offset)?);
808 }
809 region.push(make_line(chain_start.add(offset), chain_start)?);
810
811 let base = region
814 .iter()
815 .map(|curve| super::extrude::translated_curve(curve, np.scale(-thickness * 0.5)))
816 .collect::<Result<Vec<_>, String>>()?;
817 extrude_profile_brep(&base, np, thickness)
818 .map_err(|error| format!("rib: sweeping the profile inside its plane failed: {error}"))
819}
820
821fn normal_slab(
825 profile: &[NurbsCurve],
826 np: Vec3,
827 along: Vec3,
828 thickness: f64,
829 reach: f64,
830) -> Result<BrepSolid, String> {
831 let half = thickness * 0.5;
832 let left = offset_profile_segments(profile, np, half, false)
833 .map_err(|error| format!("rib: {error}"))?;
834 let right = offset_profile_segments(profile, np, -half, false)
835 .map_err(|error| format!("rib: {error}"))?;
836 let left_first = &left[0];
837 let left_last = &left[left.len() - 1];
838 let right_first = &right[0];
839 let right_last = &right[right.len() - 1];
840 let left_start = left_first.evaluate(left_first.domain()?[0])?;
841 let left_end = left_last.evaluate(left_last.domain()?[1])?;
842 let right_start = right_first.evaluate(right_first.domain()?[0])?;
843 let right_end = right_last.evaluate(right_last.domain()?[1])?;
844 let mut thin_loop: Vec<NurbsCurve> = Vec::with_capacity(left.len() + right.len() + 2);
845 for curve in &left {
846 thin_loop.push(curve.clone());
847 }
848 thin_loop.push(make_line(left_end, right_end)?);
849 for curve in right.iter().rev() {
850 thin_loop.push(curve.reversed()?);
851 }
852 thin_loop.push(make_line(right_start, left_start)?);
853 extrude_profile_brep(&thin_loop, along, reach)
854 .map_err(|error| format!("rib: extrude of the thickened profile failed: {error}"))
855}
856
857fn up_to_next(
872 solid: &BrepSolid,
873 slab: &BrepSolid,
874 seeds: &[Vec3],
875 along: Vec3,
876 reach: f64,
877) -> Result<Option<BrepSolid>, String> {
878 let free = match boolean_operation(
879 slab,
880 solid,
881 BooleanOperation::Subtract,
882 &BooleanOptions::default(),
883 ) {
884 Ok(free) => free,
885 Err(error) => {
889 return Err(format!(
892 "rib: RIB_UP_TO_NEXT_UNBOUNDED — the rib never reaches the part, so it has \
893 nothing to stop against (SolidWorks' Up To Next requires every part of a rib \
894 to meet a face); check the rib's direction — the cut reported: {error}"
895 ))
896 }
897 };
898 if free.shells.is_empty() {
899 return Ok(None);
900 }
901
902 let classifier = SolidClassifier::new(solid, 1e-6)?;
906 let steps = 64;
907 let mut probes = Vec::new();
908 for seed in seeds {
909 for step in 1..=steps {
910 let point = seed.add(along.scale(reach * step as f64 / steps as f64 * 0.5));
911 if classifier.classify(point)?.class == PointClass::Out {
912 probes.push(point);
913 break;
914 }
915 }
916 }
917 if probes.is_empty() {
918 return Ok(None);
920 }
921
922 let mut kept: Option<BrepSolid> = None;
923 for shell in &free.shells {
924 let piece = solid_from_shell(&free, shell);
925 let grown_here = probes
926 .iter()
927 .map(|probe| classify_point(*probe, &piece, 1e-6))
928 .collect::<Result<Vec<_>, String>>()?
929 .into_iter()
930 .any(|classification| classification.class == PointClass::In);
931 if !grown_here {
932 continue;
933 }
934 let overrun = piece
937 .vertices
938 .iter()
939 .map(|vertex| vertex.point.sub(seeds[0]).dot(along))
940 .fold(f64::NEG_INFINITY, f64::max);
941 if overrun >= reach * 0.99 {
942 return Err(
952 "rib: RIB_UP_TO_NEXT_UNBOUNDED — part of the rib never lands on the part, so \
953 it has no face to stop against (SolidWorks' Up To Next requires the whole rib \
954 to terminate on a face). Turn the rib around with `direction`, or move the \
955 profile so its sweep meets the part"
956 .into(),
957 );
958 }
959 kept = Some(match kept {
960 None => piece,
961 Some(previous) => boolean_operation(
962 &previous,
963 &piece,
964 BooleanOperation::Union,
965 &BooleanOptions::default(),
966 )
967 .map_err(|error| format!("rib: joining the rib's own pieces failed: {error}"))?,
968 });
969 }
970 Ok(kept)
971}
972
973fn solid_from_shell(source: &BrepSolid, shell: &ShellRecord) -> BrepSolid {
977 let edge_ids: std::collections::HashSet<u64> = shell
978 .faces
979 .iter()
980 .flat_map(|face| &face.loops)
981 .flat_map(|loop_record| &loop_record.coedges)
982 .map(|coedge| coedge.edge_id)
983 .collect();
984 let edges: Vec<EdgeRecord> = source
985 .edges
986 .iter()
987 .filter(|edge| edge_ids.contains(&edge.id))
988 .cloned()
989 .collect();
990 let vertex_ids: std::collections::HashSet<u64> = edges
991 .iter()
992 .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
993 .collect();
994 BrepSolid {
995 id: source.id,
996 vertices: source
997 .vertices
998 .iter()
999 .filter(|vertex| vertex_ids.contains(&vertex.id))
1000 .cloned()
1001 .collect(),
1002 edges,
1003 shells: vec![shell.clone()],
1004 genus: 0,
1005 }
1006}