1use crate::analytic_surface::curve_scale;
2use crate::analytic_surface::{circumcenter, AnalyticSurface};
3use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
4use crate::{make_arc, KernelTolerances, NurbsCurve, NurbsSurface, Vec3};
5use rustc_hash::FxHashMap as HashMap;
6
7#[path = "step/pcurve.rs"]
8pub(crate) mod pcurve;
9use pcurve::{build_pcurve, EmittedCurve, EmittedFrame, EmittedSurface, Pcurve2d};
10#[path = "step/pmi.rs"]
11pub(crate) mod pmi;
12pub use pmi::StepPmi;
13#[path = "step/assembly.rs"]
14pub mod assembly;
15pub use assembly::{
16 export_step_assembly, export_step_assembly_report, StepAssemblyExport, StepExportOccurrence,
17 StepExportProduct,
18};
19#[path = "step/export_tree.rs"]
20mod export_tree;
21pub use export_tree::{assembly_export_tree, PART_ATTRIBUTES, PART_NUMBER};
22#[path = "step/styles.rs"]
23pub(crate) mod styles;
24pub use styles::StepColors;
25
26pub use crate::step_matrix::Mat4;
27pub(crate) use crate::step_matrix::{mat4_mul, MAT4_IDENTITY};
28
29pub(crate) fn transform_point(matrix: &Mat4, point: Vec3) -> Vec3 {
30 crate::AffineTransform {
31 elements: *matrix,
32 }
33 .point(point)
34}
35
36pub(crate) fn step_string(value: &str) -> String {
37 value.replace('\'', "''")
38}
39
40pub(crate) fn real(value: f64) -> Result<String, String> {
41 let mut out = String::with_capacity(24);
42 real_into(&mut out, value)?;
43 Ok(out)
44}
45
46pub(crate) fn real_into(out: &mut String, value: f64) -> Result<(), String> {
53 if !value.is_finite() {
54 return Err(format!("export_step: non-finite number {value}"));
55 }
56 if value == 0.0 {
57 out.push_str("0.");
58 return Ok(());
59 }
60 let magnitude = value.abs();
61 if value.fract() == 0.0 && magnitude < 1e15 {
62 use std::fmt::Write;
64 let _ = write!(out, "{}", value as i64);
65 out.push('.');
66 return Ok(());
67 }
68 if !(magnitude < 9_007_199_254_740_992.0) {
69 out.push_str(&real_formatted(value));
70 return Ok(());
71 }
72 let bits = value.to_bits();
73 let exponent = ((bits >> 52) & 0x7ff) as i64;
74 let fraction = bits & ((1u64 << 52) - 1);
75 let (significand, power) = if exponent == 0 { (fraction, -1074i64) } else { (fraction | (1u64 << 52), exponent - 1075) };
76 if power >= 0 {
78 out.push_str(&real_formatted(value));
79 return Ok(());
80 }
81 let shift = (-power) as u32;
82 let scaled = significand as u128 * 1_000_000_000_000_000u128;
83 let rounded = if shift >= 128 {
84 0
85 } else {
86 let quotient = scaled >> shift;
87 let remainder = scaled - (quotient << shift);
88 let half = 1u128 << (shift - 1);
89 if remainder > half || (remainder == half && quotient & 1 == 1) { quotient + 1 } else { quotient }
90 };
91 if rounded == 0 {
92 out.push_str("0.0");
94 return Ok(());
95 }
96 if value < 0.0 {
97 out.push('-');
98 }
99 const SCALE: u64 = 1_000_000_000_000_000;
100 let (whole, mut part) = match u64::try_from(rounded) {
101 Ok(small) => ((small / SCALE) as u128, small % SCALE),
102 Err(_) => (rounded / SCALE as u128, (rounded % SCALE as u128) as u64),
103 };
104 let mut digits_of_whole = [0u8; 40];
106 let mut at = digits_of_whole.len();
107 let mut rest = whole;
108 loop {
109 at -= 1;
110 digits_of_whole[at] = b'0' + (rest % 10) as u8;
111 rest /= 10;
112 if rest == 0 {
113 break;
114 }
115 }
116 push_ascii(out, &digits_of_whole[at..]);
117 out.push('.');
118 if part == 0 {
119 out.push('0');
120 return Ok(());
121 }
122 let mut digits = 15usize;
123 while part % 10 == 0 {
124 part /= 10;
125 digits -= 1;
126 }
127 let mut buffer = [b'0'; 15];
128 for slot in buffer[..digits].iter_mut().rev() {
129 *slot = b'0' + (part % 10) as u8;
130 part /= 10;
131 }
132 push_ascii(out, &buffer[..digits]);
133 Ok(())
134}
135
136fn push_ascii(out: &mut String, digits: &[u8]) {
138 out.reserve(digits.len());
139 for &digit in digits {
140 out.push(char::from(digit));
141 }
142}
143
144fn push_decimal(out: &mut String, mut value: usize) {
146 let mut digits = [0u8; 20];
147 let mut at = digits.len();
148 loop {
149 at -= 1;
150 digits[at] = b'0' + (value % 10) as u8;
151 value /= 10;
152 if value == 0 {
153 break;
154 }
155 }
156 push_ascii(out, &digits[at..]);
157}
158
159pub(crate) fn real_formatted(value: f64) -> String {
162 if value == 0.0 {
163 return "0.".into();
164 }
165 if value.fract() == 0.0 && value.abs() < 1e15 {
168 return format!("{value:.0}.");
169 }
170 let mut output = format!("{value:.15}");
171 while output.ends_with('0') {
172 output.pop();
173 }
174 if output.ends_with('.') {
175 output.push('0');
176 }
177 if output == "-0.0" {
178 output = "0.0".into();
179 }
180 output
181}
182
183fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
184 let mut values = Vec::new();
185 let mut multiplicities = Vec::new();
186 for &knot in knots {
187 if values
188 .last()
189 .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
190 {
191 *multiplicities.last_mut().unwrap() += 1;
192 } else {
193 values.push(knot);
194 multiplicities.push(1);
195 }
196 }
197 (values, multiplicities)
198}
199pub(crate) use crate::edge_subcurve::edge_subcurve;
200
201
202#[derive(Default)]
203pub(crate) struct StepWriter {
204 lines: Vec<String>,
205}
206
207impl StepWriter {
208 pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
209 let body = body.into();
210 self.add_with(body.len(), |line| {
211 line.push_str(&body);
212 Ok(())
213 })
214 .expect("a body that is already built")
215 }
216
217 pub(crate) fn add_with(&mut self, capacity: usize, build: impl FnOnce(&mut String) -> Result<(), String>) -> Result<usize, String> {
220 let id = self.lines.len() + 1;
221 let mut line = String::with_capacity(capacity + 12);
222 line.push('#');
223 push_decimal(&mut line, id);
224 line.push('=');
225 build(&mut line)?;
226 line.push(';');
227 self.lines.push(line);
228 Ok(id)
229 }
230
231 fn data(&self) -> String {
232 self.lines.join("\n")
233 }
234}
235
236pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
237 writer.add_with(80, |line| {
238 line.push_str("CARTESIAN_POINT('',(");
239 real_into(line, point.x)?;
240 line.push(',');
241 real_into(line, point.y)?;
242 line.push(',');
243 real_into(line, point.z)?;
244 line.push_str("))");
245 Ok(())
246 })
247}
248
249pub(crate) fn id_list(ids: &[usize]) -> String {
250 let mut out = String::with_capacity(2 + 8 * ids.len());
251 out.push('(');
252 for (index, &id) in ids.iter().enumerate() {
253 if index > 0 {
254 out.push(',');
255 }
256 out.push('#');
257 push_decimal(&mut out, id);
258 }
259 out.push(')');
260 out
261}
262
263pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
264 writer.add_with(72, |line| {
265 line.push_str("DIRECTION('',(");
266 real_into(line, direction.x)?;
267 line.push(',');
268 real_into(line, direction.y)?;
269 line.push(',');
270 real_into(line, direction.z)?;
271 line.push_str("))");
272 Ok(())
273 })
274}
275
276pub(crate) fn write_placement(
277 writer: &mut StepWriter,
278 origin: Vec3,
279 axis: Vec3,
280 ref_direction: Vec3,
281) -> Result<usize, String> {
282 let origin = write_point(writer, origin)?;
283 let axis = write_direction(writer, axis)?;
284 let ref_direction = write_direction(writer, ref_direction)?;
285 Ok(writer.add(format!(
286 "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
287 )))
288}
289
290fn write_analytic_surface(
299 writer: &mut StepWriter,
300 surface: &NurbsSurface,
301) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
302 let Some(analytic) = surface.analytic() else {
303 if crate::switch!("BREP_EXTRUSION_EXPORT", true) {
304 if let Some(extrusion) = surface.linear_extrusion() {
305 let magnitude = extrusion.direction.length();
306 let axis = extrusion.direction.normalized()?;
307 let anchor = extrusion.profile.control_points[0].point()?;
313 let points = extrusion.profile.control_points.iter().map(|p|p.point()).collect::<Result<Vec<_>,_>>()?;
314 let extent = points.iter().map(|p|p.sub(anchor).length()).fold(magnitude,f64::max);
315 let coordinate = points.iter().map(|p|p.length()).fold(anchor.length(),f64::max);
316 let band = 1e-11*extent + 32.0*f64::EPSILON*coordinate;
317 if points.iter().any(|p|p.sub(anchor).dot(axis).abs()>band) { return Ok(None); }
318 let profile = write_curve(writer,&extrusion.profile)?;
319 let direction = write_direction(writer,axis)?;
320 let vector = writer.add(format!("VECTOR('',#{direction},1.)"));
321 let entity = writer.add(format!("SURFACE_OF_LINEAR_EXTRUSION('',#{profile},#{vector})"));
322 return Ok(Some((entity,!extrusion.profile_is_u,EmittedSurface::Extrusion {
323 profile:extrusion.profile.clone(), direction:axis,
324 profile_is_u:extrusion.profile_is_u, sweep_start:extrusion.sweep_domain[0], magnitude,
325 })));
326 }
327 }
328 return Ok(None);
329 };
330 match analytic {
331 AnalyticSurface::Plane {
332 origin,
333 u_dir,
334 v_dir,
335 ..
336 } => {
337 let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
340 else {
341 return Ok(None);
342 };
343 let placement = write_placement(writer, *origin, normal, x_axis)?;
344 Ok(Some((
349 writer.add(format!("PLANE('',#{placement})")),
350 false,
351 EmittedSurface::Plane {
352 origin: *origin,
353 x_axis,
354 y_axis: normal.cross(x_axis),
355 },
356 )))
357 }
358 AnalyticSurface::RuledRevolution {
359 frame,
360 rho0,
361 rho1,
362 height,
363 } => {
364 let flipped = *height < 0.0;
368 let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
369 if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
370 if *rho0 <= 0.0 {
371 return Ok(None);
372 }
373 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
374 return Ok(Some((
375 writer.add(format!(
376 "CYLINDRICAL_SURFACE('',#{placement},{})",
377 real(*rho0)?
378 )),
379 flipped,
380 EmittedSurface::Cylinder {
381 frame: EmittedFrame {
382 origin: frame.origin,
383 x_axis: frame.x_axis,
384 y_axis: frame.y_axis,
385 axis: frame.axis,
386 azimuth_sign: 1.0,
387 },
388 radius: *rho0,
389 },
390 )));
391 }
392 let slope = (rho1 - rho0) / height;
398 let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
399 if rho0.min(*rho1) <= apex_margin {
400 return Ok(None);
401 }
402 let axis = if slope >= 0.0 {
406 frame.axis
407 } else {
408 frame.axis.scale(-1.0)
409 };
410 let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
411 Ok(Some((
412 writer.add(format!(
413 "CONICAL_SURFACE('',#{placement},{},{})",
414 real(*rho0)?,
415 real(slope.abs().atan())?
416 )),
417 flipped,
418 EmittedSurface::Cone {
419 frame: EmittedFrame {
420 origin: frame.origin,
421 x_axis: frame.x_axis,
422 y_axis: axis.cross(frame.x_axis),
426 axis,
427 azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
428 },
429 radius: *rho0,
430 semi_angle: slope.abs().atan(),
431 },
432 )))
433 }
434 AnalyticSurface::Sphere { frame, radius } => {
435 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
438 Ok(Some((
439 writer.add(format!(
440 "SPHERICAL_SURFACE('',#{placement},{})",
441 real(*radius)?
442 )),
443 false,
444 EmittedSurface::Sphere {
445 frame: EmittedFrame {
446 origin: frame.origin,
447 x_axis: frame.x_axis,
448 y_axis: frame.y_axis,
449 axis: frame.axis,
450 azimuth_sign: 1.0,
451 },
452 radius: *radius,
453 },
454 )))
455 }
456 AnalyticSurface::Torus {
457 frame,
458 major_radius,
459 minor_radius,
460 } => {
461 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
462 Ok(Some((
463 writer.add(format!(
464 "TOROIDAL_SURFACE('',#{placement},{},{})",
465 real(*major_radius)?,
466 real(*minor_radius)?
467 )),
468 false,
469 EmittedSurface::Torus {
470 frame: EmittedFrame {
471 origin: frame.origin,
472 x_axis: frame.x_axis,
473 y_axis: frame.y_axis,
474 axis: frame.axis,
475 azimuth_sign: 1.0,
476 },
477 major_radius: *major_radius,
478 minor_radius: *minor_radius,
479 },
480 )))
481 }
482 AnalyticSurface::Revolution { frame, generatrix, .. } => {
485 let Some((center, radius, reversed)) = polar_meridian_sphere(frame, generatrix) else {
486 return Ok(None);
487 };
488 let placement = write_placement(writer, center, frame.axis, frame.x_axis)?;
489 Ok(Some((
490 writer.add(format!(
491 "SPHERICAL_SURFACE('',#{placement},{})",
492 real(radius)?
493 )),
494 reversed,
495 EmittedSurface::Sphere {
496 frame: EmittedFrame {
497 origin: center,
498 x_axis: frame.x_axis,
499 y_axis: frame.y_axis,
500 axis: frame.axis,
501 azimuth_sign: 1.0,
502 },
503 radius,
504 },
505 )))
506 }
507 }
508}
509
510fn sphere_of_revolution_on() -> bool {
515 crate::switch!("BREP_STEP_SPHERE_OF_REVOLUTION", true)
516}
517
518fn polar_meridian_sphere(
532 frame: &crate::analytic_surface::RevolutionFrame,
533 generatrix: &NurbsCurve,
534) -> Option<(Vec3, f64, bool)> {
535 if !sphere_of_revolution_on() {
536 return None;
537 }
538 let controls = &generatrix.control_points;
539 let count = controls.len();
540 if generatrix.degree != 2 || count < 3 || count % 2 == 0 || generatrix.knots.len() != count + 3 {
541 return None;
542 }
543 let knots = &generatrix.knots;
545 let span_knots = (count - 1) / 2;
546 for span in 1..span_knots {
547 if (knots[1 + 2 * span] - knots[2 + 2 * span]).abs() > 1e-12 {
548 return None;
549 }
550 }
551 let scale = curve_scale(generatrix);
552 let tolerance = 1e-9 * scale.max(1.0);
553 let mut points = Vec::with_capacity(count);
554 for control in controls {
555 if control.w <= 0.0 {
556 return None;
557 }
558 let point = control.point().ok()?;
559 let d = point.sub(frame.origin);
561 if d.dot(frame.y_axis).abs() > tolerance || d.dot(frame.x_axis) < -tolerance {
562 return None;
563 }
564 points.push(point);
565 }
566 let (mut num, mut den) = (0.0, 0.0);
570 for span in 0..span_knots {
571 let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
572 for (direction, through) in [
573 (p2.sub(p0), p0.add(p2).scale(0.5)),
574 (p1.sub(p0), p0),
575 (p1.sub(p2), p2),
576 ] {
577 let a = direction.dot(frame.axis);
579 let b = direction.dot(through.sub(frame.origin));
580 num += a * b;
581 den += a * a;
582 }
583 }
584 if den <= tolerance * tolerance {
585 return None;
586 }
587 let center = frame.origin.add(frame.axis.scale(num / den));
588 let radius = points[0].sub(center).length();
589 if radius <= tolerance {
590 return None;
591 }
592 let mut turn = 0.0;
593 for span in 0..span_knots {
594 let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
595 let (r0, r1, r2) = (p0.sub(center), p1.sub(center), p2.sub(center));
596 if (r0.length() - radius).abs() > tolerance
597 || (r2.length() - radius).abs() > tolerance
598 || p1.sub(p0).dot(r0).abs() > tolerance * radius
599 || p1.sub(p2).dot(r2).abs() > tolerance * radius
600 {
601 return None;
602 }
603 let cos_half = radius / r1.length();
605 let (w0, w1, w2) = (controls[2 * span].w, controls[2 * span + 1].w, controls[2 * span + 2].w);
606 if !(cos_half > 1e-6) || (w1 * w1 / (w0 * w2) - cos_half * cos_half).abs() > 1e-9 {
607 return None;
608 }
609 let cross = r0.dot(frame.x_axis) * r2.dot(frame.axis) - r0.dot(frame.axis) * r2.dot(frame.x_axis);
611 if cross.abs() <= tolerance * radius || (turn != 0.0 && cross.signum() != turn) {
612 return None;
613 }
614 turn = cross.signum();
615 }
616 Some((center, radius, turn < 0.0))
617}
618
619pub(crate) struct CircularArc {
624 pub(crate) center: Vec3,
625 pub(crate) axis: Vec3,
626 pub(crate) x_axis: Vec3,
627 pub(crate) y_axis: Vec3,
630 pub(crate) radius: f64,
631 pub(crate) sweep: f64,
633 spans: usize,
637}
638
639
640
641fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
645 if a.degree != b.degree
646 || a.knots.len() != b.knots.len()
647 || a.control_points.len() != b.control_points.len()
648 {
649 return false;
650 }
651 if a.knots
652 .iter()
653 .zip(&b.knots)
654 .any(|(x, y)| (x - y).abs() > 1e-12)
655 {
656 return false;
657 }
658 let tolerance = 1e-9 * scale.max(1.0);
659 a.control_points
660 .iter()
661 .zip(&b.control_points)
662 .all(|(p, q)| {
663 (p.x - q.x).abs() <= tolerance
664 && (p.y - q.y).abs() <= tolerance
665 && (p.z - q.z).abs() <= tolerance
666 && (p.w - q.w).abs() <= 1e-9
667 })
668}
669
670pub(crate) fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
675 if curve.degree != 2
676 || curve.control_points.len() < 3
677 || curve.control_points.len() % 2 == 0
678 || (curve.control_points.len() - 1) / 2 > 4
679 {
680 return None;
681 }
682 let [t0, t1] = curve.domain().ok()?;
683 let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
684 let p0 = at(0.0).ok()?;
687 let pa = at(0.35).ok()?;
688 let pb = at(0.7).ok()?;
689 let center = circumcenter(p0, pa, pb)?;
690 let radial = p0.sub(center);
691 let radius = radial.length();
692 let scale = curve_scale(curve);
693 if radius <= 1e-9 * scale.max(1.0) {
694 return None;
695 }
696 let x_axis = radial.scale(1.0 / radius);
697 let axis = radial.cross(pa.sub(center)).normalized().ok()?;
698 let y_axis = axis.cross(x_axis);
699 let p_end = at(1.0).ok()?;
700 let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
701 std::f64::consts::TAU
702 } else {
703 let closing = p_end.sub(center);
704 let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
705 if angle < 0.0 {
706 angle += std::f64::consts::TAU;
707 }
708 angle
709 };
710 let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
711 curves_match(curve, &rebuilt, scale).then_some(CircularArc {
712 center,
713 axis,
714 x_axis,
715 y_axis,
716 radius,
717 sweep,
718 spans: (curve.control_points.len() - 1) / 2,
719 })
720}
721
722fn write_analytic_curve(
729 writer: &mut StepWriter,
730 curve: &NurbsCurve,
731) -> Result<Option<(usize, EmittedCurve)>, String> {
732 if curve.degree == 1
733 && curve.control_points.len() == 2
734 && curve
735 .control_points
736 .iter()
737 .all(|control| (control.w - 1.0).abs() <= 1e-12)
738 {
739 let start = curve.control_points[0].point()?;
740 let end = curve.control_points[1].point()?;
741 let Ok(direction) = end.sub(start).normalized() else {
742 return Ok(None);
743 };
744 let point = write_point(writer, start)?;
745 let step_direction = write_direction(writer, direction)?;
746 let vector = writer.add(format!(
747 "VECTOR('',#{step_direction},{})",
748 real(end.sub(start).length())?
749 ));
750 return Ok(Some((
751 writer.add(format!("LINE('',#{point},#{vector})")),
752 EmittedCurve::Line { start, end },
756 )));
757 }
758 if let Some(arc) = recognize_circular_arc(curve) {
759 let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
763 return Ok(Some((
764 writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
765 EmittedCurve::Circle {
766 center: arc.center,
767 x_axis: arc.x_axis,
768 y_axis: arc.y_axis,
769 radius: arc.radius,
770 sweep: arc.sweep,
771 spans: arc.spans,
772 },
773 )));
774 }
775 Ok(None)
776}
777
778fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
779 let points = curve
780 .control_points
781 .iter()
782 .map(|control| write_point(writer, control.point()?))
783 .collect::<Result<Vec<_>, _>>()?;
784 write_bspline_curve(writer, curve, &points)
785}
786
787fn write_bspline_curve(
792 writer: &mut StepWriter,
793 curve: &NurbsCurve,
794 points: &[usize],
795) -> Result<usize, String> {
796 let (knot_values, multiplicities) = knot_runs(&curve.knots);
797 let multiplicities = format!(
798 "({})",
799 multiplicities
800 .iter()
801 .map(usize::to_string)
802 .collect::<Vec<_>>()
803 .join(",")
804 );
805 let knots = format!(
806 "({})",
807 knot_values
808 .iter()
809 .map(|value| real(*value))
810 .collect::<Result<Vec<_>, _>>()?
811 .join(",")
812 );
813 let rational = curve
814 .control_points
815 .iter()
816 .any(|control| (control.w - 1.0).abs() > 1e-12);
817 if !rational {
818 return Ok(writer.add(format!(
819 "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
820 curve.degree,
821 id_list(points),
822 )));
823 }
824 let weights = format!(
825 "({})",
826 curve
827 .control_points
828 .iter()
829 .map(|control| real(control.w))
830 .collect::<Result<Vec<_>, _>>()?
831 .join(",")
832 );
833 Ok(writer.add(format!(
834 "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
835 B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
836 CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
837 REPRESENTATION_ITEM(''))",
838 curve.degree,
839 id_list(points),
840 )))
841}
842
843fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
844 Ok(writer.add(format!(
845 "CARTESIAN_POINT('',({},{}))",
846 real(point[0])?,
847 real(point[1])?
848 )))
849}
850
851fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
852 Ok(writer.add(format!(
853 "DIRECTION('',({},{}))",
854 real(direction[0])?,
855 real(direction[1])?
856 )))
857}
858
859fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
869 match curve {
870 Pcurve2d::Line { point, vector } => {
871 let magnitude = vector[0].hypot(vector[1]);
872 if magnitude <= 0.0 {
873 return Err("export_step: degenerate 2D line pcurve".into());
874 }
875 let point_id = write_point_2d(writer, *point)?;
876 let direction =
877 write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
878 let vector_id = writer.add(format!(
879 "VECTOR('',#{direction},{})",
880 real(magnitude)?
881 ));
882 Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
883 }
884 Pcurve2d::Circle {
885 center,
886 ref_direction,
887 radius,
888 } => {
889 let center_id = write_point_2d(writer, *center)?;
890 let direction = write_direction_2d(writer, *ref_direction)?;
891 let placement = writer.add(format!(
892 "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
893 ));
894 Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
895 }
896 Pcurve2d::Spline(spline) => {
897 let points = spline
898 .control_points
899 .iter()
900 .map(|control| {
901 let point = control.point()?;
902 write_point_2d(writer, [point.x, point.y])
903 })
904 .collect::<Result<Vec<_>, String>>()?;
905 write_bspline_curve(writer, spline, &points)
906 }
907 }
908}
909
910fn write_pcurve_entity(
913 writer: &mut StepWriter,
914 surface_id: usize,
915 context_2d: usize,
916 curve: &Pcurve2d,
917) -> Result<usize, String> {
918 let geometry = write_pcurve_geometry(writer, curve)?;
919 let representation = writer.add(format!(
920 "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
921 ));
922 Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
923}
924
925fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
926 let rows = surface
927 .control_points
928 .iter()
929 .map(|row| {
930 row.iter()
931 .map(|control| write_point(writer, control.point()?))
932 .collect::<Result<Vec<_>, _>>()
933 .map(|ids| id_list(&ids))
934 })
935 .collect::<Result<Vec<_>, _>>()?;
936 let grid = format!("({})", rows.join(","));
937 let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
938 let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
939 let multiplicities = |values: &[usize]| {
940 format!(
941 "({})",
942 values
943 .iter()
944 .map(usize::to_string)
945 .collect::<Vec<_>>()
946 .join(",")
947 )
948 };
949 let knots = |values: &[f64]| -> Result<String, String> {
950 Ok(format!(
951 "({})",
952 values
953 .iter()
954 .map(|value| real(*value))
955 .collect::<Result<Vec<_>, _>>()?
956 .join(",")
957 ))
958 };
959 let u_mults = multiplicities(&u_multiplicities);
960 let v_mults = multiplicities(&v_multiplicities);
961 let u_knots = knots(&u_values)?;
962 let v_knots = knots(&v_values)?;
963 let rational = surface
964 .control_points
965 .iter()
966 .flatten()
967 .any(|control| (control.w - 1.0).abs() > 1e-12);
968 if !rational {
969 return Ok(writer.add(format!(
970 "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
971 {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
972 surface.degree_u, surface.degree_v,
973 )));
974 }
975 let weights = format!(
976 "({})",
977 surface
978 .control_points
979 .iter()
980 .map(|row| {
981 row.iter()
982 .map(|control| real(control.w))
983 .collect::<Result<Vec<_>, _>>()
984 .map(|values| format!("({})", values.join(",")))
985 })
986 .collect::<Result<Vec<_>, _>>()?
987 .join(",")
988 );
989 Ok(writer.add(format!(
990 "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
991 B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
992 GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
993 REPRESENTATION_ITEM('')SURFACE())",
994 surface.degree_u, surface.degree_v,
995 )))
996}
997
998fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
999 let normalized = unit.to_lowercase();
1000 if normalized == "meter" || normalized == "metre" {
1001 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
1002 }
1003 if normalized == "centimeter" || normalized == "centimetre" {
1004 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
1005 }
1006 if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
1007 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
1008 }
1009 if normalized == "inch" || normalized == "foot" {
1010 let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
1011 let (factor, name) = if normalized == "inch" {
1012 (0.0254, "INCH")
1013 } else {
1014 (0.3048, "FOOT")
1015 };
1016 let measure = writer.add(format!(
1017 "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
1018 real(factor)?
1019 ));
1020 return Ok(writer.add(format!(
1021 "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
1022 )));
1023 }
1024 Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
1025}
1026
1027fn void_owner(
1032 solid: &BrepSolid,
1033 void: usize,
1034 outer: &[usize],
1035 shells: &[(usize, bool, f64)],
1036) -> Result<usize, String> {
1037 let probe = solid.shells[void]
1038 .faces
1039 .iter()
1040 .flat_map(|face| &face.loops)
1041 .flat_map(|lp| &lp.coedges)
1042 .find_map(|coedge| {
1043 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1044 (!edge.degenerate).then(|| edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()).flatten()
1045 })
1046 .ok_or("export_step: a void shell with no edge to place it by")?;
1047 let mut best: Option<usize> = None;
1048 for &candidate in outer {
1049 let alone = BrepSolid {
1050 shells: vec![solid.shells[candidate].clone()],
1051 ..solid.clone()
1052 };
1053 let class = crate::classify_point(probe, &alone, 1e-7)?.class;
1054 if class == crate::PointClass::In && best.is_none_or(|b| shells[candidate].2 < shells[b].2) {
1055 best = Some(candidate);
1056 }
1057 }
1058 best.ok_or_else(|| "export_step: a void shell lies inside no outward shell".into())
1059}
1060
1061fn shell_is_inward(solid: &BrepSolid, shell: &crate::topology::ShellRecord) -> Result<bool, String> {
1067 let alone = BrepSolid {
1068 shells: vec![shell.clone()],
1069 mass_properties_cache: Default::default(),
1070 ..solid.clone()
1071 };
1072 if let Some(certificate) = crate::mass_properties::solid_sign_coarse_certificate(&alone, crate::mass_properties::COARSE_SIGN_DEPTH) {
1073 if certificate.reading - certificate.bound > 0.0 {
1074 return Ok(false);
1075 }
1076 if certificate.reading + certificate.bound < 0.0 {
1077 return Ok(true);
1078 }
1079 }
1080 if crate::mass_properties::solid_signed_volume_for_sign(&alone, 0.0)? > 0.0 {
1081 return Ok(false);
1082 }
1083 let below = -f64::MIN_POSITIVE;
1084 if !(crate::mass_properties::solid_signed_volume_for_sign(&alone, below)? > below) {
1085 return Ok(true);
1086 }
1087 Ok(crate::mass_properties::shell_signed_volume(shell)? < 0.0)
1088}
1089
1090fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
1091 solid
1092 .vertices
1093 .iter()
1094 .find(|vertex| vertex.id == id)
1095 .ok_or_else(|| format!("export_step: missing vertex {id}"))
1096}
1097
1098fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
1099 solid
1100 .edges
1101 .iter()
1102 .find(|edge| edge.id == id)
1103 .ok_or_else(|| format!("export_step: missing edge {id}"))
1104}
1105
1106fn surface_key(face: &FaceRecord) -> usize {
1107 face as *const FaceRecord as usize
1108}
1109
1110struct CoedgeUse<'a> {
1114 surface_key: usize,
1115 face: &'a FaceRecord,
1116 coedge: &'a CoedgeRecord,
1117}
1118
1119#[derive(Clone, Debug, Default)]
1128pub struct StepExportReport {
1129 pub text: String,
1131 pub pcurves_written: usize,
1134 pub pcurves_omitted: usize,
1137 pub surface_curves: usize,
1139 pub seam_curves: usize,
1142 pub bare_curves: usize,
1145 pub vertex_loops: usize,
1148 pub max_pcurve_deviation: f64,
1151 pub worst_omitted_deviation: f64,
1162 pub pmi_unresolved_references: usize,
1169 pub products: usize,
1172 pub occurrences: usize,
1175 pub styled_items: usize,
1180}
1181
1182pub fn export_step(
1191 solids: &[BrepSolid],
1192 name: &str,
1193 unit: &str,
1194 timestamp: &str,
1195) -> Result<String, String> {
1196 export_step_report(solids, name, unit, timestamp).map(|report| report.text)
1197}
1198
1199pub fn export_step_report(
1202 solids: &[BrepSolid],
1203 name: &str,
1204 unit: &str,
1205 timestamp: &str,
1206) -> Result<StepExportReport, String> {
1207 let named: Vec<(String, &BrepSolid)> = solids
1208 .iter()
1209 .map(|solid| (name.to_string(), solid))
1210 .collect();
1211 export_step_report_named(&named, name, unit, timestamp, None, None)
1212}
1213
1214#[derive(Clone, Copy)]
1223pub(crate) struct StepItemOwner {
1224 pub product_shape: usize,
1225 pub representation: usize,
1226}
1227
1228#[derive(Default)]
1232pub(crate) struct ProductGeometry {
1233 pub solids: Vec<(String, usize)>,
1238 pub faces: Vec<(String, usize)>,
1240 pub edges: Vec<(String, usize)>,
1242 pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
1244}
1245
1246#[derive(Default)]
1251pub(crate) struct StepNameMaps {
1252 pub faces: HashMap<String, (usize, StepItemOwner)>,
1253 pub edges: HashMap<String, (usize, StepItemOwner)>,
1254 pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
1257}
1258
1259impl StepNameMaps {
1260 pub(crate) fn register(
1264 &mut self,
1265 geometry: &ProductGeometry,
1266 owner: StepItemOwner,
1267 prefix: &str,
1268 world: &Mat4,
1269 ) {
1270 for (name, id) in &geometry.faces {
1271 self.faces
1272 .entry(format!("{prefix}{name}"))
1273 .or_insert((*id, owner));
1274 }
1275 for (name, id) in &geometry.edges {
1276 self.edges
1277 .entry(format!("{prefix}{name}"))
1278 .or_insert((*id, owner));
1279 }
1280 for (name, points) in &geometry.vertices {
1281 let placed = points
1282 .iter()
1283 .map(|(point, id)| (transform_point(world, *point), *id))
1284 .collect();
1285 self.vertices
1286 .entry(format!("{prefix}{name}"))
1287 .or_insert((owner, placed));
1288 }
1289 }
1290}
1291
1292pub(crate) struct StepFileContexts {
1295 pub product_context: usize,
1296 pub definition_context: usize,
1297 pub geometry_context: usize,
1298 pub parametric_context: usize,
1299 pub length_unit: usize,
1300 pub angle_unit: usize,
1301 pub axis: usize,
1305}
1306
1307pub(crate) fn write_file_contexts(
1309 writer: &mut StepWriter,
1310 unit: &str,
1311) -> Result<StepFileContexts, String> {
1312 let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
1313 writer.add(format!(
1314 "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
1315 ));
1316 let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
1317 let definition_context = writer.add(format!(
1318 "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
1319 ));
1320 let length_unit = write_length_unit(writer, unit)?;
1321 let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
1322 let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
1323 let uncertainty = writer.add(format!(
1324 "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
1325 ));
1326 let geometry_context = writer.add(format!(
1327 "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
1328 GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
1329 GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
1330 REPRESENTATION_CONTEXT('',''))"
1331 ));
1332 let parametric_context = writer.add(
1337 "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
1338 PARAMETRIC_REPRESENTATION_CONTEXT()\
1339 REPRESENTATION_CONTEXT('2D SPACE',''))",
1340 );
1341 let origin = write_point(writer, Vec3::default())?;
1342 let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
1343 let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
1344 let axis = writer.add(format!(
1345 "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
1346 ));
1347 Ok(StepFileContexts {
1348 product_context,
1349 definition_context,
1350 geometry_context,
1351 parametric_context,
1352 length_unit,
1353 angle_unit,
1354 axis,
1355 })
1356}
1357
1358pub(crate) struct ProductIds {
1362 pub definition: usize,
1363 pub product_shape: usize,
1364}
1365
1366pub(crate) fn write_product(
1372 writer: &mut StepWriter,
1373 contexts: &StepFileContexts,
1374 name: &str,
1375 id: &str,
1376 category: &str,
1377) -> ProductIds {
1378 let safe_name = step_string(name);
1379 let safe_id = step_string(if id.is_empty() { name } else { id });
1380 let product_context = contexts.product_context;
1381 let definition_context = contexts.definition_context;
1382 let product = writer.add(format!(
1383 "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1384 ));
1385 writer.add(format!(
1386 "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1387 step_string(category)
1388 ));
1389 let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1390 let definition = writer.add(format!(
1391 "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1392 ));
1393 let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1394 ProductIds {
1395 definition,
1396 product_shape,
1397 }
1398}
1399
1400pub(crate) fn write_product_geometry(
1408 writer: &mut StepWriter,
1409 contexts: &StepFileContexts,
1410 bodies: &[(String, &BrepSolid)],
1411 report: &mut StepExportReport,
1412) -> Result<ProductGeometry, String> {
1413 for (_, solid) in bodies {
1414 let policy = KernelTolerances::for_solid(solid, 1e-7);
1415 let issues = solid.validate_with_tolerances(&KernelTolerances {
1416 pcurve_consistency: policy.export_knit,
1417 ..policy
1418 });
1419 if !issues.is_empty() {
1420 return Err(format!("export_step: invalid solid: {issues:?}"));
1421 }
1422 }
1423 let parametric_context = contexts.parametric_context;
1424 let mut written = ProductGeometry::default();
1425 for (solid_name, solid) in bodies {
1426 let solid = *solid;
1427 let solid_name = solid_name.as_str();
1428 let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1429 let retain_extrusion_charts = crate::switch!("BREP_EXTRUSION_EXPORT", true)
1433 && solid.shells.iter().flat_map(|s|&s.faces)
1434 .filter(|face|face.surface.analytic().is_none() && face.surface.linear_extrusion().is_some())
1435 .any(|face|face.loops.iter().flat_map(|l|&l.coedges).any(|coedge| {
1436 let Ok(edge) = edge_for(solid,coedge.edge_id) else { return true; };
1437 crate::measure_edge_against_pcurve_image(&face.surface,&coedge.pcurve,
1438 edge,coedge.forward,band).map_or(true,|m|m.deviation()>band)
1439 }));
1440 let mut vertex_ids = HashMap::<u64, usize>::default();
1441 let mut edge_ids = HashMap::<u64, usize>::default();
1442 let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1443 let mut emitted_shells = Vec::new();
1444 for shell in &solid.shells {
1445 for face in &shell.faces {
1450 let key = surface_key(face);
1451 if surfaces.contains_key(&key) {
1452 continue;
1453 }
1454 let analytic = if retain_extrusion_charts && face.surface.analytic().is_none() {
1455 None
1456 } else { write_analytic_surface(writer, &face.surface)? };
1457 let entry = match analytic {
1458 Some(triple) => triple,
1459 None => (
1460 write_surface(writer, &face.surface)?,
1461 false,
1462 EmittedSurface::Spline,
1463 ),
1464 };
1465 surfaces.insert(key, entry);
1466 }
1467
1468 let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1471 let mut edge_order: Vec<u64> = Vec::new();
1472 for face in &shell.faces {
1473 for loop_record in &face.loops {
1474 for coedge in &loop_record.coedges {
1475 let edge = edge_for(solid, coedge.edge_id)?;
1476 if edge.degenerate {
1477 continue;
1478 }
1479 let uses = edge_uses.entry(edge.id).or_default();
1480 if uses.is_empty() {
1481 edge_order.push(edge.id);
1482 }
1483 uses.push(CoedgeUse {
1484 surface_key: surface_key(face),
1485 face,
1486 coedge,
1487 });
1488 }
1489 }
1490 }
1491
1492 for edge_id in &edge_order {
1494 if edge_ids.contains_key(edge_id) {
1495 continue;
1496 }
1497 let edge = edge_for(solid, *edge_id)?;
1498 let subcurve = edge_subcurve(edge)?;
1499 let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1500 Some(pair) => pair,
1501 None => (
1502 write_curve(writer, &subcurve)?,
1503 EmittedCurve::Spline { curve: subcurve },
1504 ),
1505 };
1506 let uses = &edge_uses[edge_id];
1507 let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1511 let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1512 let mut omitted = 0usize;
1513 if uses.len() == 2 {
1514 let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1518 if seam && !ordered[0].coedge.forward {
1519 ordered.swap(0, 1);
1520 }
1521 for coedge_use in ordered {
1522 let oriented = if coedge_use.coedge.forward {
1527 coedge_use.coedge.pcurve.clone()
1528 } else {
1529 coedge_use.coedge.pcurve.reversed()?
1530 };
1531 let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1532 let outcome = build_pcurve(
1533 &coedge_use.face.surface,
1534 emitted_surface,
1535 &emitted_curve,
1536 &oriented,
1537 band,
1538 )?;
1539 match outcome.curve {
1540 Some(curve_2d) => {
1541 report.max_pcurve_deviation =
1542 report.max_pcurve_deviation.max(outcome.deviation);
1543 pcurves.push((*surface_id, curve_2d));
1544 }
1545 None => {
1546 omitted += 1;
1547 if outcome.deviation.is_finite() {
1548 report.worst_omitted_deviation =
1549 report.worst_omitted_deviation.max(outcome.deviation);
1550 } else {
1551 report.worst_omitted_deviation = f64::INFINITY;
1552 }
1553 }
1554 }
1555 }
1556 }
1557 if seam && pcurves.len() != 2 {
1561 omitted += pcurves.len();
1562 pcurves.clear();
1563 }
1564 report.pcurves_omitted += omitted;
1565 report.pcurves_written += pcurves.len();
1566 let geometry = if pcurves.is_empty() {
1567 report.bare_curves += 1;
1568 curve
1569 } else {
1570 let ids = pcurves
1571 .iter()
1572 .map(|(surface_id, curve_2d)| {
1573 write_pcurve_entity(
1574 writer,
1575 *surface_id,
1576 parametric_context,
1577 curve_2d,
1578 )
1579 })
1580 .collect::<Result<Vec<_>, String>>()?;
1581 let keyword = if seam {
1582 report.seam_curves += 1;
1583 "SEAM_CURVE"
1584 } else {
1585 report.surface_curves += 1;
1586 "SURFACE_CURVE"
1587 };
1588 writer.add(format!(
1594 "{keyword}('',#{curve},{},.CURVE_3D.)",
1595 id_list(&ids)
1596 ))
1597 };
1598 let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1599 let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1600 let step_id =
1601 writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1602 edge_ids.insert(edge.id, step_id);
1603 if let Some(edge_name) = edge.name.as_deref() {
1604 written.edges.push((edge_name.to_string(), step_id));
1605 }
1606 }
1607
1608 let mut face_ids = Vec::new();
1610 for face in &shell.faces {
1611 let mut bound_ids = Vec::new();
1612 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1613 let mut oriented_edges = Vec::new();
1614 for coedge in &loop_record.coedges {
1615 let edge = edge_for(solid, coedge.edge_id)?;
1616 if edge.degenerate {
1617 continue;
1618 }
1619 let edge_id = *edge_ids
1620 .get(&edge.id)
1621 .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1622 let orientation = if coedge.forward { ".T." } else { ".F." };
1623 oriented_edges.push(
1624 writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1625 );
1626 }
1627 let kind = if loop_index == 0 {
1628 "FACE_OUTER_BOUND"
1629 } else {
1630 "FACE_BOUND"
1631 };
1632 if oriented_edges.is_empty() {
1633 let Some(coedge) = loop_record.coedges.first() else {
1646 continue;
1647 };
1648 let collapsed = edge_for(solid, coedge.edge_id)?;
1649 let vertex = vertex_step_id(
1650 writer,
1651 &mut vertex_ids,
1652 solid,
1653 collapsed.start_vertex_id,
1654 )?;
1655 let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1656 report.vertex_loops += 1;
1657 bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1658 continue;
1659 }
1660 let edge_loop =
1661 writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1662 bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1663 }
1664 let (surface, flipped, _) = surfaces[&surface_key(face)];
1665 let sense = if face.same_sense != flipped {
1669 ".T."
1670 } else {
1671 ".F."
1672 };
1673 let face_step_id = writer.add(format!(
1674 "ADVANCED_FACE('',{},#{surface},{sense})",
1675 id_list(&bound_ids)
1676 ));
1677 if let Some(face_name) = face.name.as_deref() {
1678 written.faces.push((face_name.to_string(), face_step_id));
1679 }
1680 face_ids.push(face_step_id);
1681 }
1682 let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1683 let inward = solid.shells.len() > 1 && shell_is_inward(solid, shell)?;
1686 emitted_shells.push((closed_shell, inward, f64::NAN));
1687 }
1688 if emitted_shells.iter().any(|&(_, inward, _)| inward) {
1689 let outer: Vec<usize> = (0..emitted_shells.len()).filter(|&i| !emitted_shells[i].1).collect();
1690 if outer.is_empty() {
1691 return Err("export_step: a solid with voids must have an outward shell".into());
1692 }
1693 let mut owned: Vec<Vec<usize>> = vec![Vec::new(); emitted_shells.len()];
1697 if outer.len() > 1 {
1698 for (index, shell) in solid.shells.iter().enumerate() {
1699 emitted_shells[index].2 = crate::mass_properties::shell_signed_volume(shell)?.abs();
1700 }
1701 }
1702 for void in (0..emitted_shells.len()).filter(|&i| emitted_shells[i].1) {
1703 let owner = if outer.len() == 1 {
1704 outer[0]
1705 } else {
1706 void_owner(solid, void, &outer, &emitted_shells)?
1707 };
1708 owned[owner].push(void);
1709 }
1710 for &shell in &outer {
1711 let closed_shell = emitted_shells[shell].0;
1712 let body_id = if owned[shell].is_empty() {
1713 writer.add(format!("MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)))
1714 } else {
1715 let voids = owned[shell].iter()
1716 .map(|&void| writer.add(format!("ORIENTED_CLOSED_SHELL('',*,#{},.T.)", emitted_shells[void].0)))
1717 .collect::<Vec<_>>();
1718 writer.add(format!(
1719 "BREP_WITH_VOIDS('{}',#{closed_shell},{})", step_string(solid_name), id_list(&voids)
1720 ))
1721 };
1722 written.solids.push((solid_name.to_string(), body_id));
1723 }
1724 } else {
1725 for (closed_shell, _, _) in emitted_shells {
1726 let body_id = writer.add(format!(
1727 "MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)
1728 ));
1729 written.solids.push((solid_name.to_string(), body_id));
1730 }
1731 }
1732 let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1734 for (vertex_id, step_id) in &vertex_ids {
1735 points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1736 }
1737 written.vertices.push((solid_name.to_string(), points));
1738 }
1739 Ok(written)
1740}
1741
1742pub(crate) fn finish_step_file(
1745 writer: StepWriter,
1746 name: &str,
1747 timestamp: &str,
1748 report: &mut StepExportReport,
1749) -> Result<(), String> {
1750 let safe_name = step_string(name);
1751 let safe_timestamp = step_string(timestamp);
1752 let output = [
1753 "ISO-10303-21;".to_string(),
1754 "HEADER;".to_string(),
1755 "FILE_DESCRIPTION((''),'2;1');".to_string(),
1756 format!(
1757 "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1758 ),
1759 "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1760 "ENDSEC;".to_string(),
1761 "DATA;".to_string(),
1762 writer.data(),
1763 "ENDSEC;".to_string(),
1764 "END-ISO-10303-21;".to_string(),
1765 String::new(),
1766 ]
1767 .join("\n");
1768 let manifold_issues = audit_step_manifold(&output);
1769 if !manifold_issues.is_empty() {
1770 return Err(format!(
1771 "export_step: emitted AP242 manifold audit failed: {}",
1772 manifold_issues.join("; ")
1773 ));
1774 }
1775 let pcurve_issues = audit_step_pcurves(&output);
1776 if !pcurve_issues.is_empty() {
1777 return Err(format!(
1778 "export_step: emitted AP242 pcurve audit failed: {}",
1779 pcurve_issues.join("; ")
1780 ));
1781 }
1782 report.text = output;
1783 Ok(())
1784}
1785
1786pub fn export_step_report_named(
1795 solids: &[(String, &BrepSolid)],
1796 name: &str,
1797 unit: &str,
1798 timestamp: &str,
1799 pmi: Option<&StepPmi<'_>>,
1800 colors: Option<&StepColors>,
1801) -> Result<StepExportReport, String> {
1802 if solids.is_empty() {
1803 return Err("export_step: at least one solid is required".into());
1804 }
1805 let mut report = StepExportReport {
1806 products: 1,
1807 ..StepExportReport::default()
1808 };
1809 let mut writer = StepWriter::default();
1810 let contexts = write_file_contexts(&mut writer, unit)?;
1811 let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1812 let mut items = vec![contexts.axis];
1813 items.extend(geometry.solids.iter().map(|(_, id)| *id));
1814 let geometry_context = contexts.geometry_context;
1815 let representation = writer.add(format!(
1816 "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1817 id_list(&items)
1818 ));
1819 let product = write_product(&mut writer, &contexts, name, "", "part");
1820 let product_shape = product.product_shape;
1821 writer.add(format!(
1822 "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1823 ));
1824 if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1829 let items = styles::styled_items(&geometry, colors, &[String::new()]);
1830 report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1831 }
1832 if let Some(pmi) = pmi {
1833 let mut names = StepNameMaps::default();
1834 names.register(
1835 &geometry,
1836 StepItemOwner {
1837 product_shape,
1838 representation,
1839 },
1840 "",
1841 &MAT4_IDENTITY,
1842 );
1843 let context = pmi::StepContext {
1844 product_shape,
1845 representation,
1846 geometry_context,
1847 length_unit: contexts.length_unit,
1848 angle_unit: contexts.angle_unit,
1849 faces: &names.faces,
1850 edges: &names.edges,
1851 vertices: &names.vertices,
1852 };
1853 report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1854 }
1855 finish_step_file(writer, name, timestamp, &mut report)?;
1856 Ok(report)
1857}
1858
1859fn vertex_step_id(
1861 writer: &mut StepWriter,
1862 vertex_ids: &mut HashMap<u64, usize>,
1863 solid: &BrepSolid,
1864 id: u64,
1865) -> Result<usize, String> {
1866 if let Some(step_id) = vertex_ids.get(&id) {
1867 return Ok(*step_id);
1868 }
1869 let point = write_point(writer, vertex_for(solid, id)?.point)?;
1870 let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1871 vertex_ids.insert(id, step_id);
1872 Ok(step_id)
1873}
1874
1875fn step_entity_bodies(step: &str) -> EntityBodies<'_> {
1878 let mut dense: Vec<Option<&str>> = Vec::new();
1879 let mut sparse: HashMap<u64, &str> = HashMap::default();
1880 for (id, body) in step.lines().filter_map(entity_line) {
1881 match usize::try_from(id).ok().filter(|&index| index <= dense.len() + 1024) {
1885 Some(index) if sparse.is_empty() => {
1886 if index >= dense.len() {
1887 dense.resize(index + 1, None);
1888 }
1889 dense[index] = Some(body);
1890 }
1891 _ => {
1892 if sparse.is_empty() {
1893 sparse.extend(dense.drain(..).enumerate().filter_map(|(index, body)| body.map(|body| (index as u64, body))));
1894 }
1895 sparse.insert(id, body);
1896 }
1897 }
1898 }
1899 EntityBodies { dense, sparse }
1900}
1901
1902struct EntityBodies<'a> {
1905 dense: Vec<Option<&'a str>>,
1906 sparse: HashMap<u64, &'a str>,
1907}
1908
1909impl<'a> EntityBodies<'a> {
1910 fn get(&self, id: &u64) -> Option<&&'a str> {
1911 if !self.sparse.is_empty() {
1912 return self.sparse.get(id);
1913 }
1914 usize::try_from(*id).ok().and_then(|index| self.dense.get(index)).and_then(Option::as_ref)
1915 }
1916
1917 fn iter(&self) -> Box<dyn Iterator<Item = (u64, &'a str)> + '_> {
1918 if self.sparse.is_empty() {
1919 Box::new(self.dense.iter().enumerate().filter_map(|(index, body)| body.map(|body| (index as u64, body))))
1920 } else {
1921 Box::new(self.sparse.iter().map(|(id, body)| (*id, *body)))
1922 }
1923 }
1924}
1925
1926impl<'a> std::ops::Index<&u64> for EntityBodies<'a> {
1927 type Output = &'a str;
1928 fn index(&self, id: &u64) -> &&'a str {
1929 self.get(id).expect("an entity with that id")
1930 }
1931}
1932
1933fn entity_line(line: &str) -> Option<(u64, &str)> {
1937 let bytes = line.as_bytes();
1938 if bytes.first() != Some(&b'#') {
1939 return None;
1940 }
1941 let mut index = 1;
1942 if bytes.get(index) == Some(&b'+') {
1943 index += 1;
1944 }
1945 let start = index;
1946 let mut id: u64 = 0;
1947 while let Some(&byte) = bytes.get(index) {
1948 if !byte.is_ascii_digit() {
1949 break;
1950 }
1951 id = id.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
1952 index += 1;
1953 }
1954 if index == start || bytes.get(index) != Some(&b'=') {
1955 return None;
1956 }
1957 Some((id, line[index + 1..].trim_end().trim_end_matches(';')))
1958}
1959
1960fn find_bytes(haystack: &str, needle: &str) -> Option<usize> {
1963 let first = needle.chars().next()?;
1964 let rest = &needle.as_bytes()[first.len_utf8()..];
1965 let bytes = haystack.as_bytes();
1966 let mut from = 0;
1967 while let Some(offset) = haystack.get(from..)?.find(first) {
1968 let at = from + offset;
1969 let after = at + first.len_utf8();
1970 if bytes.get(after..after + rest.len()) == Some(rest) {
1971 return Some(at);
1972 }
1973 from = after;
1974 }
1975 None
1976}
1977
1978fn step_entity_refs(body: &str) -> Vec<u64> {
1982 let mut refs = Vec::new();
1983 let bytes = body.as_bytes();
1984 let mut index = 0;
1985 while index < bytes.len() {
1986 if bytes[index] == b'#' {
1987 let start = index + 1;
1988 let mut end = start;
1989 while end < bytes.len() && bytes[end].is_ascii_digit() {
1990 end += 1;
1991 }
1992 if end > start {
1993 if let Ok(id) = body[start..end].parse::<u64>() {
1994 refs.push(id);
1995 }
1996 }
1997 index = end;
1998 } else {
1999 index += 1;
2000 }
2001 }
2002 refs
2003}
2004
2005pub fn audit_step_pcurves(step: &str) -> Vec<String> {
2018 let bodies = step_entity_bodies(step);
2019 let mut issues = Vec::new();
2020 for (id, body) in bodies.iter() {
2021 if !body.starts_with("EDGE_CURVE(") {
2022 continue;
2023 }
2024 let refs = step_entity_refs(body);
2025 let Some(geometry) = refs.get(2) else {
2026 issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
2027 continue;
2028 };
2029 let Some(wrapper) = bodies.get(geometry) else {
2030 issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
2031 continue;
2032 };
2033 let seam = wrapper.starts_with("SEAM_CURVE(");
2034 if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
2035 continue;
2036 }
2037 let wrapper_refs = step_entity_refs(wrapper);
2038 let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
2039 if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
2040 issues.push(format!(
2041 "#{geometry} carries {} associated geometries",
2042 pcurves.len()
2043 ));
2044 continue;
2045 }
2046 let mut surfaces = Vec::new();
2047 for pcurve in pcurves {
2048 let Some(pcurve_body) = bodies.get(pcurve) else {
2049 issues.push(format!("#{geometry} references missing #{pcurve}"));
2050 continue;
2051 };
2052 if !pcurve_body.starts_with("PCURVE(") {
2053 issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
2054 continue;
2055 }
2056 let pcurve_refs = step_entity_refs(pcurve_body);
2057 let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
2058 if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
2059 {
2060 issues.push(format!(
2061 "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
2062 ));
2063 }
2064 if let Some(surface) = pcurve_refs.first() {
2065 surfaces.push(*surface);
2066 }
2067 }
2068 if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
2069 issues.push(format!(
2070 "#{geometry} pcurves name {} surface(s) but it is a {}",
2071 if surfaces[0] == surfaces[1] { 1 } else { 2 },
2072 if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
2073 ));
2074 }
2075 }
2076 issues.sort();
2077 issues
2078}
2079
2080pub fn audit_step_manifold(step: &str) -> Vec<String> {
2085 let marker = "ORIENTED_EDGE('',*,*,#";
2086 let mut uses = HashMap::<u64, Vec<bool>>::default();
2087 for line in step.lines() {
2088 let Some(offset) = find_bytes(line, marker) else {
2089 continue;
2090 };
2091 let rest = &line[offset + marker.len()..];
2092 let length = rest.bytes().take_while(u8::is_ascii_digit).count();
2093 let Ok(edge_id) = rest[..length].parse::<u64>() else {
2094 continue;
2095 };
2096 let suffix = &rest[length..];
2097 let sense = suffix.starts_with(",.T.");
2098 uses.entry(edge_id).or_default().push(sense);
2099 }
2100 let mut issues = uses
2101 .into_iter()
2102 .filter_map(|(edge, senses)| {
2103 (senses.len() != 2 || senses[0] == senses[1]).then(|| {
2104 format!(
2105 "EDGE_CURVE #{edge} has {} uses with senses {:?}",
2106 senses.len(),
2107 senses
2108 )
2109 })
2110 })
2111 .collect::<Vec<_>>();
2112 issues.sort();
2113 issues
2114}
2115
2116