1use crate::sweep_topology::{curve_to_plane_parameters, parameter_line};
2use crate::topology::{
3 BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord,
4};
5use crate::{make_line, make_plane, make_revolution, NurbsCurve, NurbsSurface, Vec3, Vec4};
6
7const TOLERANCE: f64 = 1e-5;
8
9fn next_id(counter: &mut u64) -> u64 {
10 let id = *counter;
11 *counter += 1;
12 id
13}
14
15fn rotate_point(point: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Vec3 {
16 let vector = point.sub(origin);
17 let cosine = angle.cos();
18 let sine = angle.sin();
19 origin
20 .add(vector.scale(cosine))
21 .add(axis.cross(vector).scale(sine))
22 .add(axis.scale(axis.dot(vector) * (1.0 - cosine)))
23}
24
25fn rotate_curve(
26 curve: &NurbsCurve,
27 origin: Vec3,
28 axis: Vec3,
29 angle: f64,
30) -> Result<NurbsCurve, String> {
31 NurbsCurve::new(
32 curve.degree,
33 curve.knots.clone(),
34 curve
35 .control_points
36 .iter()
37 .map(|point| {
38 let euclidean = Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w);
39 Vec4::from_point(rotate_point(euclidean, origin, axis, angle), point.w)
40 })
41 .collect(),
42 )
43}
44
45fn signed_profile_area(
46 curves: &[NurbsCurve],
47 origin: Vec3,
48 radial: Vec3,
49 axis: Vec3,
50) -> Result<f64, String> {
51 let mut area = 0.0;
52 for curve in curves {
53 let [start, end] = curve.domain()?;
54 let mut previous = curve.evaluate(start)?;
55 for index in 1..=64 {
56 let point = curve.evaluate(start + (end - start) * index as f64 / 64.0)?;
57 let a = previous.sub(origin);
58 let b = point.sub(origin);
59 area += 0.5 * (a.dot(radial) * b.dot(axis) - b.dot(radial) * a.dot(axis));
60 previous = point;
61 }
62 }
63 Ok(area)
64}
65
66struct RevolveProfile {
67 curves: Vec<NurbsCurve>,
68 points: Vec<Vec3>,
69 axis_points: Vec<bool>,
70 axis_curves: Vec<bool>,
71 radial_curves: Vec<bool>,
79 radial: Vec3,
80 axis: Vec3,
81 input_indices: Vec<usize>,
87}
88
89fn is_segment(curve: &NurbsCurve) -> bool {
91 curve.degree == 1 && curve.control_points.len() == 2
92}
93
94fn clamped_at(curve: &NurbsCurve, at_start: bool) -> bool {
97 let order = curve.degree + 1;
98 let knots = &curve.knots;
99 if at_start {
100 knots[..order].iter().all(|knot| *knot == knots[0])
101 } else {
102 knots[knots.len() - order..].iter().all(|knot| *knot == knots[knots.len() - 1])
103 }
104}
105
106fn end_control_point(curve: &NurbsCurve, at_start: bool) -> Vec3 {
107 let point = if at_start {
108 curve.control_points[0]
109 } else {
110 curve.control_points[curve.control_points.len() - 1]
111 };
112 Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w)
113}
114
115fn move_end(curve: &mut NurbsCurve, at_start: bool, target: Vec3) -> Result<(), String> {
117 let mut control_points = curve.control_points.clone();
118 let index = if at_start { 0 } else { control_points.len() - 1 };
119 control_points[index] = Vec4::from_point(target, control_points[index].w);
120 *curve = NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)?;
121 Ok(())
122}
123
124fn weld_junctions(curves: &mut [NurbsCurve]) -> Result<bool, String> {
130 let count = curves.len();
131 let mut moved = false;
132 for index in 0..count {
133 let next = (index + 1) % count;
134 if !clamped_at(&curves[index], false) || !clamped_at(&curves[next], true) {
135 continue;
136 }
137 let end = end_control_point(&curves[index], false);
138 let start = end_control_point(&curves[next], true);
139 if end.x == start.x && end.y == start.y && end.z == start.z {
140 continue;
141 }
142 if is_segment(&curves[index]) && !is_segment(&curves[next]) {
143 move_end(&mut curves[index], false, start)?;
144 } else {
145 move_end(&mut curves[next], true, end)?;
146 }
147 moved = true;
148 }
149 Ok(moved)
150}
151
152fn flatten_radial_generatrices(
163 curves: &mut [NurbsCurve],
164 radial: &[bool],
165 axis_point: Vec3,
166 axis: Vec3,
167) -> Result<bool, String> {
168 let count = curves.len();
169 let Some(first) = (0..count).find(|index| !radial[*index]) else {
170 return Ok(false);
171 };
172 let axial = |point: Vec3| point.sub(axis_point).dot(axis);
173 let mut moved = false;
174 let mut offset = 1;
175 while offset <= count {
176 let begin = (first + offset) % count;
177 if !radial[begin] {
178 offset += 1;
179 continue;
180 }
181 let mut run = vec![begin];
182 while radial[(run[run.len() - 1] + 1) % count] {
183 run.push((run[run.len() - 1] + 1) % count);
184 }
185 offset += run.len();
186 let last = run[run.len() - 1];
188 if run.iter().any(|index| !clamped_at(&curves[*index], true) || !clamped_at(&curves[*index], false)) {
189 continue;
190 }
191 let mut vertices: Vec<Vec3> = run.iter().map(|index| end_control_point(&curves[*index], true)).collect();
192 vertices.push(end_control_point(&curves[last], false));
193 let before = (begin + count - 1) % count;
194 let after = (last + 1) % count;
195 let mut fixed = Vec::new();
196 if !is_segment(&curves[before]) {
197 fixed.push(axial(vertices[0]));
198 }
199 if !is_segment(&curves[after]) {
200 fixed.push(axial(vertices[vertices.len() - 1]));
201 }
202 let pool: Vec<f64> = if fixed.is_empty() { vertices.iter().map(|point| axial(*point)).collect() } else { fixed };
203 let target = pool.iter().sum::<f64>() / pool.len() as f64;
204 for (k, vertex) in vertices.iter().enumerate() {
205 let shift = target - axial(*vertex);
206 if shift == 0.0 {
207 continue;
208 }
209 let point = vertex.add(axis.scale(shift));
210 let (incoming, outgoing) = if k == 0 {
211 (before, run[0])
212 } else if k == run.len() {
213 (last, after)
214 } else {
215 (run[k - 1], run[k])
216 };
217 if clamped_at(&curves[incoming], false) {
218 move_end(&mut curves[incoming], false, point)?;
219 }
220 if clamped_at(&curves[outgoing], true) {
221 move_end(&mut curves[outgoing], true, point)?;
222 }
223 moved = true;
224 }
225 }
226 Ok(moved)
227}
228
229fn prepare_profile(
230 input: &[NurbsCurve],
231 axis_point: Vec3,
232 axis_direction: Vec3,
233 flatten_radial: bool,
234) -> Result<RevolveProfile, String> {
235 if input.len() < 2 {
236 return Err("profile needs at least 2 curves".into());
237 }
238 let axis = axis_direction.normalized()?;
239 let mut curves: Vec<NurbsCurve> = input
240 .iter()
241 .map(|curve| {
242 NurbsCurve::new(
243 curve.degree,
244 curve.knots.clone(),
245 curve.control_points.clone(),
246 )
247 })
248 .collect::<Result<_, _>>()?;
249 let closure_points = |curves: &[NurbsCurve]| -> Result<Vec<Vec3>, String> {
250 let mut points = Vec::with_capacity(curves.len());
251 for index in 0..curves.len() {
252 let [start, end] = curves[index].domain()?;
253 let next_start = curves[(index + 1) % curves.len()].domain()?[0];
254 let point = curves[index].evaluate(start)?;
255 if curves[index]
256 .evaluate(end)?
257 .sub(curves[(index + 1) % curves.len()].evaluate(next_start)?)
258 .length()
259 > TOLERANCE
260 {
261 return Err(format!("profile not closed at curve {index}"));
262 }
263 points.push(point);
264 }
265 Ok(points)
266 };
267 let mut points = closure_points(&curves)?;
268
269 let radial_distance = |point: Vec3| {
270 let delta = point.sub(axis_point);
271 delta.sub(axis.scale(delta.dot(axis))).length()
272 };
273 let mut radial = None;
274 'outer: for curve in &curves {
275 let [start, end] = curve.domain()?;
276 for index in 0..=24 {
277 let point = curve.evaluate(start + (end - start) * index as f64 / 24.0)?;
278 let delta = point.sub(axis_point);
279 let candidate = delta.sub(axis.scale(delta.dot(axis)));
280 if candidate.length() > TOLERANCE * 100.0 {
281 radial = Some(candidate.normalized()?);
282 break 'outer;
283 }
284 }
285 }
286 let radial = radial.ok_or_else(|| "revolveSolid: profile touches the axis".to_string())?;
287 let curve_on_axis = |curve: &NurbsCurve| -> Result<bool, String> {
288 let [start, end] = curve.domain()?;
289 for index in 0..=8 {
290 if radial_distance(curve.evaluate(start + (end - start) * index as f64 / 8.0)?)
291 > TOLERANCE * 100.0
292 {
293 return Ok(false);
294 }
295 }
296 Ok(true)
297 };
298 for curve in &curves {
299 let [start, end] = curve.domain()?;
300 let on_axis = curve_on_axis(curve)?;
301 for index in 0..=24 {
302 let point = curve.evaluate(start + (end - start) * index as f64 / 24.0)?;
303 let delta = point.sub(axis_point);
304 let in_plane_radial = delta.dot(radial);
305 let off_plane = delta
306 .sub(axis.scale(delta.dot(axis)))
307 .sub(radial.scale(in_plane_radial))
308 .length();
309 if off_plane > TOLERANCE * 100.0 {
310 return Err("revolveSolid: profile not in a half-plane containing the axis".into());
311 }
312 if in_plane_radial < -TOLERANCE * 100.0 {
313 return Err("revolveSolid: profile crosses the revolve axis".into());
314 }
315 if in_plane_radial < TOLERANCE * 100.0 && index != 0 && index != 24 && !on_axis {
316 return Err(
317 "revolveSolid: profile may only touch the axis at boundary vertices or axis edges"
318 .into(),
319 );
320 }
321 }
322 }
323 let mut input_indices: Vec<usize> = (0..curves.len()).collect();
324 if signed_profile_area(&curves, axis_point, radial, axis)? < 0.0 {
325 curves = curves
326 .iter()
327 .rev()
328 .map(NurbsCurve::reversed)
329 .collect::<Result<_, _>>()?;
330 points = closure_points(&curves)?;
331 input_indices.reverse();
332 }
333 let mut axis_points: Vec<bool> = points
334 .iter()
335 .map(|point| radial_distance(*point) <= TOLERANCE * 100.0)
336 .collect();
337 if axis_points.iter().any(|flag| *flag) {
338 let snapped: Vec<Vec3> = points
339 .iter()
340 .enumerate()
341 .map(|(index, point)| {
342 if axis_points[index] {
343 axis_point.add(axis.scale(point.sub(axis_point).dot(axis)))
344 } else {
345 *point
346 }
347 })
348 .collect();
349 for index in 0..curves.len() {
350 let next = (index + 1) % curves.len();
351 if !axis_points[index] && !axis_points[next] {
352 continue;
353 }
354 let mut control_points = curves[index].control_points.clone();
355 if axis_points[index] {
356 let weight = control_points[0].w;
357 control_points[0] = Vec4::from_point(snapped[index], weight);
358 }
359 if axis_points[next] {
360 let last = control_points.len() - 1;
361 let weight = control_points[last].w;
362 control_points[last] = Vec4::from_point(snapped[next], weight);
363 }
364 curves[index] = NurbsCurve::new(
365 curves[index].degree,
366 curves[index].knots.clone(),
367 control_points,
368 )?;
369 }
370 points = closure_points(&curves)?;
371 axis_points = points
372 .iter()
373 .map(|point| radial_distance(*point) <= TOLERANCE * 100.0)
374 .collect();
375 }
376 if std::env::var("BREP_REVOLVE_WELD").as_deref() != Ok("0") && weld_junctions(&mut curves)? {
382 points = closure_points(&curves)?;
383 }
384 let axis_curves = curves
385 .iter()
386 .map(curve_on_axis)
387 .collect::<Result<Vec<_>, _>>()?;
388 let radial_of = |curves: &[NurbsCurve]| {
393 curves
394 .iter()
395 .enumerate()
396 .map(|(index, curve)| {
397 if axis_curves[index] {
398 return Ok(false);
399 }
400 Ok(is_straight_radial(curve, axis)?)
401 })
402 .collect::<Result<Vec<_>, String>>()
403 };
404 let mut radial_curves = radial_of(&curves)?;
405 let flatten_radial = flatten_radial && std::env::var("BREP_REVOLVE_FLAT_RADIAL").as_deref() != Ok("0");
407 if flatten_radial && flatten_radial_generatrices(&mut curves, &radial_curves, axis_point, axis)? {
408 points = closure_points(&curves)?;
409 radial_curves = radial_of(&curves)?;
410 }
411 Ok(RevolveProfile {
412 curves,
413 points,
414 axis_points,
415 axis_curves,
416 radial_curves,
417 radial,
418 axis,
419 input_indices,
420 })
421}
422
423fn is_straight_radial(curve: &NurbsCurve, axis: Vec3) -> Result<bool, String> {
428 if curve.degree != 1 || curve.control_points.len() != 2 {
429 return Ok(false);
430 }
431 let [start, end] = curve.domain()?;
432 let p0 = curve.evaluate(start)?;
433 let p1 = curve.evaluate(end)?;
434 let direction = p1.sub(p0);
435 let length = direction.length();
436 if length <= TOLERANCE {
437 return Ok(false);
438 }
439 Ok(direction.dot(axis).abs() <= 1e-3 * length)
440}
441
442fn junction_curve(
443 index: usize,
444 surfaces: &[Option<NurbsSurface>],
445 points: &[Vec3],
446) -> Result<NurbsCurve, String> {
447 if let Some(surface) = &surfaces[index] {
448 return surface.iso_curve_v(surface.knots_v[surface.degree_v]);
449 }
450 let previous = (index + surfaces.len() - 1) % surfaces.len();
451 if let Some(surface) = &surfaces[previous] {
452 return surface.iso_curve_v(surface.knots_v[surface.knots_v.len() - 1 - surface.degree_v]);
453 }
454 make_line(points[index], points[index])
455}
456
457#[allow(clippy::too_many_arguments)]
465fn radial_plane_face(
466 profile: &RevolveProfile,
467 index: usize,
468 count: usize,
469 origin: Vec3,
470 revolution: &NurbsSurface,
471 arc_curves: &[NurbsCurve],
472 end_curves: &[NurbsCurve],
473 arc_ids: &[u64],
474 start_edge_ids: &[u64],
475 end_edge_ids: &[u64],
476 counter: &mut u64,
477 name: Option<String>,
478) -> Result<FaceRecord, String> {
479 let axis = profile.axis;
480 let a_start = profile.points[index].sub(origin).dot(axis);
481 let a_end = profile.points[(index + 1) % count].sub(origin).dot(axis);
482 let plane_center = origin.add(axis.scale(0.5 * (a_start + a_end)));
483 let e1 = profile.radial;
484 let e2 = axis.cross(e1);
485
486 let next = (index + 1) % count;
487 let boundary: [(NurbsCurve, u64, bool); 4] = [
488 (arc_curves[index].clone(), arc_ids[index], true),
489 (end_curves[index].clone(), end_edge_ids[index], true),
490 (arc_curves[next].clone(), arc_ids[next], false),
491 (profile.curves[index].clone(), start_edge_ids[index], false),
492 ];
493
494 let mut min1 = f64::INFINITY;
495 let mut max1 = f64::NEG_INFINITY;
496 let mut min2 = f64::INFINITY;
497 let mut max2 = f64::NEG_INFINITY;
498 for (curve, _, _) in &boundary {
499 let [s, e] = curve.domain()?;
500 for k in 0..=16 {
501 let point = curve.evaluate(s + (e - s) * k as f64 / 16.0)?;
502 let d = point.sub(plane_center);
503 let c1 = d.dot(e1);
504 let c2 = d.dot(e2);
505 min1 = min1.min(c1);
506 max1 = max1.max(c1);
507 min2 = min2.min(c2);
508 max2 = max2.max(c2);
509 }
510 }
511 let padding = (max1 - min1).max(max2 - min2) * 0.05 + 1e-6;
512 let width = max1 - min1 + 2.0 * padding;
513 let height = max2 - min2 + 2.0 * padding;
514 let corner = plane_center
515 .add(e1.scale(min1 - padding))
516 .add(e2.scale(min2 - padding));
517 let plane = make_plane(corner, e1, e2, width, height)?;
518
519 let [ru0, ru1] = revolution.domain_u()?;
523 let [rv0, rv1] = revolution.domain_v()?;
524 let rev_normal = revolution.normal((ru0 + ru1) * 0.5, (rv0 + rv1) * 0.5)?;
525 let same_sense = rev_normal.dot(e1.cross(e2)) >= 0.0;
526
527 let mut coedges = Vec::with_capacity(4);
528 for (curve, edge_id, forward) in boundary {
529 let mapped = curve_to_plane_parameters(&curve, corner, e1, e2)?;
530 let pcurve = if forward { mapped } else { mapped.reversed()? };
531 coedges.push(CoedgeRecord {
532 id: next_id(counter),
533 edge_id,
534 forward,
535 pcurve,
536 });
537 }
538 let loop_id = next_id(counter);
539 Ok(FaceRecord {
540 id: next_id(counter),
541 surface: plane,
542 same_sense,
543 loops: vec![LoopRecord {
544 id: loop_id,
545 coedges,
546 }],
547 name,
548 })
549}
550
551pub fn revolve_profile_brep(
552 input: &[NurbsCurve],
553 axis_point: Vec3,
554 axis_direction: Vec3,
555 angle: f64,
556) -> Result<BrepSolid, String> {
557 revolve_profile_brep_named(input, axis_point, axis_direction, angle, &[], &[])
558}
559
560pub fn revolve_profile_brep_named(
566 input: &[NurbsCurve],
567 axis_point: Vec3,
568 axis_direction: Vec3,
569 angle: f64,
570 side_names: &[Option<String>],
571 cap_names: &[Option<String>],
572) -> Result<BrepSolid, String> {
573 if angle <= 1e-9 || angle > std::f64::consts::TAU + 1e-9 {
574 return Err("revolveSolid: angle must be in (0, 2*PI]".into());
575 }
576 if !side_names.is_empty() && side_names.len() != input.len() {
577 return Err(format!(
578 "revolveSolid: {} side names for {} profile curves",
579 side_names.len(),
580 input.len()
581 ));
582 }
583 let full_turn = angle > std::f64::consts::TAU - 1e-9;
584 let built = prepare_profile(input, axis_point, axis_direction, !full_turn).and_then(|profile| {
585 if full_turn {
586 revolve_full(profile, axis_point, side_names)
587 } else {
588 revolve_partial(profile, axis_point, angle, side_names, cap_names)
589 }
590 });
591 dump_revolve(input, axis_point, axis_direction, angle, &built);
592 built
593}
594
595fn dump_revolve(
600 input: &[NurbsCurve],
601 axis_point: Vec3,
602 axis_direction: Vec3,
603 angle: f64,
604 built: &Result<BrepSolid, String>,
605) {
606 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
607 let Some(directory) = std::env::var("BREP_REVOLVE_DUMP").ok().filter(|value| !value.is_empty()) else {
608 return;
609 };
610 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
611 let record = serde_json::json!({
612 "curves": input,
613 "axis_point": axis_point,
614 "axis_direction": axis_direction,
615 "angle": angle,
616 "solid": built.as_ref().ok(),
617 "error": built.as_ref().err(),
618 });
619 let path = std::path::Path::new(&directory).join(format!("{}-{serial:05}.json", std::process::id()));
620 if let Err(error) = std::fs::write(&path, record.to_string()) {
621 eprintln!("BREP_REVOLVE_DUMP {}: {error}", path.display());
622 }
623}
624
625fn side_name(
626 profile: &RevolveProfile,
627 curve_index: usize,
628 side_names: &[Option<String>],
629) -> Option<String> {
630 profile
631 .input_indices
632 .get(curve_index)
633 .and_then(|input_index| side_names.get(*input_index))
634 .cloned()
635 .flatten()
636}
637
638fn revolve_full(
639 profile: RevolveProfile,
640 origin: Vec3,
641 side_names: &[Option<String>],
642) -> Result<BrepSolid, String> {
643 let count = profile.curves.len();
644 let surfaces: Vec<Option<NurbsSurface>> = profile
645 .curves
646 .iter()
647 .enumerate()
648 .map(|(index, curve)| {
649 if profile.axis_curves[index] {
650 Ok(None)
651 } else {
652 make_revolution(origin, profile.axis, curve, std::f64::consts::TAU).map(Some)
653 }
654 })
655 .collect::<Result<_, String>>()?;
656 let vertices: Vec<VertexRecord> = profile
657 .points
658 .iter()
659 .enumerate()
660 .map(|(index, point)| VertexRecord {
661 id: index as u64 + 1,
662 point: *point,
663 })
664 .collect();
665 let mut counter = 100_u64;
666 let mut edges = Vec::new();
667 let mut circle_ids = Vec::with_capacity(count);
668 for index in 0..count {
669 let curve = junction_curve(index, &surfaces, &profile.points)?;
670 let [start, end] = curve.domain()?;
671 let id = next_id(&mut counter);
672 circle_ids.push(id);
673 edges.push(EdgeRecord {
674 id,
675 curve,
676 t0: start,
677 t1: end,
678 start_vertex_id: index as u64 + 1,
679 end_vertex_id: index as u64 + 1,
680 degenerate: profile.axis_points[index],
681 name: None,
682 });
683 }
684 let mut faces = Vec::new();
685 for index in 0..count {
686 if profile.axis_curves[index] {
687 continue;
688 }
689 let curve = profile.curves[index].clone();
690 let [start, end] = curve.domain()?;
691 let seam_id = next_id(&mut counter);
692 edges.push(EdgeRecord {
693 id: seam_id,
694 curve,
695 t0: start,
696 t1: end,
697 start_vertex_id: index as u64 + 1,
698 end_vertex_id: ((index + 1) % count) as u64 + 1,
699 degenerate: false,
700 name: None,
701 });
702 let coedges = vec![
703 CoedgeRecord {
704 id: next_id(&mut counter),
705 edge_id: circle_ids[index],
706 forward: true,
707 pcurve: parameter_line(0.0, start, 1.0, start)?,
708 },
709 CoedgeRecord {
710 id: next_id(&mut counter),
711 edge_id: seam_id,
712 forward: true,
713 pcurve: parameter_line(1.0, start, 1.0, end)?,
714 },
715 CoedgeRecord {
716 id: next_id(&mut counter),
717 edge_id: circle_ids[(index + 1) % count],
718 forward: false,
719 pcurve: parameter_line(1.0, end, 0.0, end)?,
720 },
721 CoedgeRecord {
722 id: next_id(&mut counter),
723 edge_id: seam_id,
724 forward: false,
725 pcurve: parameter_line(0.0, end, 0.0, start)?,
726 },
727 ];
728 let loop_id = next_id(&mut counter);
729 faces.push(FaceRecord {
730 id: next_id(&mut counter),
731 surface: surfaces[index].clone().unwrap(),
732 same_sense: true,
733 loops: vec![LoopRecord {
734 id: loop_id,
735 coedges,
736 }],
737 name: side_name(&profile, index, side_names),
738 });
739 }
740 let solid = BrepSolid {
741 mass_properties_cache: Default::default(),
742 id: next_id(&mut counter),
743 vertices,
744 edges,
745 shells: vec![ShellRecord {
746 id: next_id(&mut counter),
747 faces,
748 }],
749 genus: if profile.axis_points.iter().any(|flag| *flag) {
750 0
751 } else {
752 1
753 },
754 };
755 let issues = solid.validate();
756 if issues.is_empty() {
757 Ok(solid)
758 } else {
759 Err(format!("Rust full revolution is invalid: {issues:?}"))
760 }
761}
762
763fn revolve_partial(
764 profile: RevolveProfile,
765 origin: Vec3,
766 angle: f64,
767 side_names: &[Option<String>],
768 cap_names: &[Option<String>],
769) -> Result<BrepSolid, String> {
770 let count = profile.curves.len();
771 let end_curves: Vec<NurbsCurve> = profile
772 .curves
773 .iter()
774 .map(|curve| rotate_curve(curve, origin, profile.axis, angle))
775 .collect::<Result<_, _>>()?;
776 let surfaces: Vec<Option<NurbsSurface>> = profile
777 .curves
778 .iter()
779 .enumerate()
780 .map(|(index, curve)| {
781 if profile.axis_curves[index] {
782 Ok(None)
783 } else {
784 make_revolution(origin, profile.axis, curve, angle).map(Some)
785 }
786 })
787 .collect::<Result<_, String>>()?;
788 let mut vertices = Vec::new();
789 let mut start_vertex_ids = Vec::with_capacity(count);
790 let mut end_vertex_ids = Vec::with_capacity(count);
791 let mut counter = 100_u64;
792 for point in &profile.points {
793 let id = next_id(&mut counter);
794 start_vertex_ids.push(id);
795 vertices.push(VertexRecord { id, point: *point });
796 }
797 for index in 0..count {
798 if profile.axis_points[index] {
799 end_vertex_ids.push(start_vertex_ids[index]);
800 } else {
801 let id = next_id(&mut counter);
802 end_vertex_ids.push(id);
803 vertices.push(VertexRecord {
804 id,
805 point: rotate_point(profile.points[index], origin, profile.axis, angle),
806 });
807 }
808 }
809
810 let mut edges = Vec::new();
811 let mut arc_ids = Vec::with_capacity(count);
812 let mut arc_curves = Vec::with_capacity(count);
813 for index in 0..count {
814 let curve = junction_curve(index, &surfaces, &profile.points)?;
815 let [start, end] = curve.domain()?;
816 let id = next_id(&mut counter);
817 arc_ids.push(id);
818 arc_curves.push(curve.clone());
819 edges.push(EdgeRecord {
820 id,
821 curve,
822 t0: start,
823 t1: end,
824 start_vertex_id: start_vertex_ids[index],
825 end_vertex_id: end_vertex_ids[index],
826 degenerate: profile.axis_points[index],
827 name: None,
828 });
829 }
830 let mut start_edge_ids = Vec::with_capacity(count);
831 let mut end_edge_ids = Vec::with_capacity(count);
832 for index in 0..count {
833 let [start, end] = profile.curves[index].domain()?;
834 let start_id = next_id(&mut counter);
835 start_edge_ids.push(start_id);
836 edges.push(EdgeRecord {
837 id: start_id,
838 curve: profile.curves[index].clone(),
839 t0: start,
840 t1: end,
841 start_vertex_id: start_vertex_ids[index],
842 end_vertex_id: start_vertex_ids[(index + 1) % count],
843 degenerate: false,
844 name: None,
845 });
846 if profile.axis_curves[index] {
847 end_edge_ids.push(start_id);
848 } else {
849 let end_id = next_id(&mut counter);
850 end_edge_ids.push(end_id);
851 edges.push(EdgeRecord {
852 id: end_id,
853 curve: end_curves[index].clone(),
854 t0: start,
855 t1: end,
856 start_vertex_id: end_vertex_ids[index],
857 end_vertex_id: end_vertex_ids[(index + 1) % count],
858 degenerate: false,
859 name: None,
860 });
861 }
862 }
863
864 let mut faces = Vec::new();
865 for index in 0..count {
866 if profile.axis_curves[index] {
867 continue;
868 }
869 if profile.radial_curves[index] {
870 faces.push(radial_plane_face(
871 &profile,
872 index,
873 count,
874 origin,
875 surfaces[index].as_ref().unwrap(),
876 &arc_curves,
877 &end_curves,
878 &arc_ids,
879 &start_edge_ids,
880 &end_edge_ids,
881 &mut counter,
882 side_name(&profile, index, side_names),
883 )?);
884 continue;
885 }
886 let [start, end] = profile.curves[index].domain()?;
887 let coedges = vec![
888 CoedgeRecord {
889 id: next_id(&mut counter),
890 edge_id: arc_ids[index],
891 forward: true,
892 pcurve: parameter_line(0.0, start, 1.0, start)?,
893 },
894 CoedgeRecord {
895 id: next_id(&mut counter),
896 edge_id: end_edge_ids[index],
897 forward: true,
898 pcurve: parameter_line(1.0, start, 1.0, end)?,
899 },
900 CoedgeRecord {
901 id: next_id(&mut counter),
902 edge_id: arc_ids[(index + 1) % count],
903 forward: false,
904 pcurve: parameter_line(1.0, end, 0.0, end)?,
905 },
906 CoedgeRecord {
907 id: next_id(&mut counter),
908 edge_id: start_edge_ids[index],
909 forward: false,
910 pcurve: parameter_line(0.0, end, 0.0, start)?,
911 },
912 ];
913 let loop_id = next_id(&mut counter);
914 faces.push(FaceRecord {
915 id: next_id(&mut counter),
916 surface: surfaces[index].clone().unwrap(),
917 same_sense: true,
918 loops: vec![LoopRecord {
919 id: loop_id,
920 coedges,
921 }],
922 name: side_name(&profile, index, side_names),
923 });
924 }
925
926 let mut min_radial = f64::INFINITY;
927 let mut max_radial = f64::NEG_INFINITY;
928 let mut min_axis = f64::INFINITY;
929 let mut max_axis = f64::NEG_INFINITY;
930 for curve in &profile.curves {
931 let [start, end] = curve.domain()?;
932 for index in 0..=24 {
933 let delta = curve
934 .evaluate(start + (end - start) * index as f64 / 24.0)?
935 .sub(origin);
936 let radial = delta.dot(profile.radial);
937 let axial = delta.dot(profile.axis);
938 min_radial = min_radial.min(radial);
939 max_radial = max_radial.max(radial);
940 min_axis = min_axis.min(axial);
941 max_axis = max_axis.max(axial);
942 }
943 }
944 let padding = (max_radial - min_radial).max(max_axis - min_axis) * 0.05 + 1e-6;
945 let width = max_radial - min_radial + 2.0 * padding;
946 let height = max_axis - min_axis + 2.0 * padding;
947 let start_origin = origin
948 .add(profile.radial.scale(min_radial - padding))
949 .add(profile.axis.scale(min_axis - padding));
950 let mut start_coedges = Vec::with_capacity(count);
951 for index in 0..count {
952 start_coedges.push(CoedgeRecord {
953 id: next_id(&mut counter),
954 edge_id: start_edge_ids[index],
955 forward: true,
956 pcurve: curve_to_plane_parameters(
957 &profile.curves[index],
958 start_origin,
959 profile.radial,
960 profile.axis,
961 )?,
962 });
963 }
964 let start_loop_id = next_id(&mut counter);
965 faces.push(FaceRecord {
966 id: next_id(&mut counter),
967 surface: make_plane(start_origin, profile.radial, profile.axis, width, height)?,
968 same_sense: true,
969 loops: vec![LoopRecord {
970 id: start_loop_id,
971 coedges: start_coedges,
972 }],
973 name: cap_names.first().cloned().flatten(),
974 });
975
976 let end_radial = rotate_point(origin.add(profile.radial), origin, profile.axis, angle)
977 .sub(origin)
978 .normalized()?;
979 let end_origin = origin
980 .add(end_radial.scale(min_radial - padding))
981 .add(profile.axis.scale(min_axis - padding));
982 let mut end_coedges = Vec::with_capacity(count);
983 for index in (0..count).rev() {
984 end_coedges.push(CoedgeRecord {
985 id: next_id(&mut counter),
986 edge_id: end_edge_ids[index],
987 forward: false,
988 pcurve: curve_to_plane_parameters(
989 &end_curves[index],
990 end_origin,
991 profile.axis,
992 end_radial,
993 )?
994 .reversed()?,
995 });
996 }
997 let end_loop_id = next_id(&mut counter);
998 faces.push(FaceRecord {
999 id: next_id(&mut counter),
1000 surface: make_plane(end_origin, profile.axis, end_radial, height, width)?,
1001 same_sense: true,
1002 loops: vec![LoopRecord {
1003 id: end_loop_id,
1004 coedges: end_coedges,
1005 }],
1006 name: cap_names.get(1).cloned().flatten(),
1007 });
1008
1009 let solid = BrepSolid {
1010 mass_properties_cache: Default::default(),
1011 id: next_id(&mut counter),
1012 vertices,
1013 edges,
1014 shells: vec![ShellRecord {
1015 id: next_id(&mut counter),
1016 faces,
1017 }],
1018 genus: 0,
1019 };
1020 let issues = solid.validate();
1021 if issues.is_empty() {
1022 Ok(solid)
1023 } else {
1024 Err(format!("Rust partial revolution is invalid: {issues:?}"))
1025 }
1026}
1027