Skip to main content

brep_kernel/io/
step.rs

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    if !value.is_finite() {
42        return Err(format!("export_step: non-finite number {value}"));
43    }
44    // Analytic frame axes come from cross products that can round to -0.0;
45    // normalize so directions never print a negative zero component.
46    if value == 0.0 {
47        return Ok("0.".into());
48    }
49    if value.fract() == 0.0 && value.abs() < 1e15 {
50        return Ok(format!("{value:.0}."));
51    }
52    let mut output = format!("{value:.15}");
53    while output.ends_with('0') {
54        output.pop();
55    }
56    if output.ends_with('.') {
57        output.push('0');
58    }
59    if output == "-0.0" {
60        output = "0.0".into();
61    }
62    Ok(output)
63}
64
65fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
66    let mut values = Vec::new();
67    let mut multiplicities = Vec::new();
68    for &knot in knots {
69        if values
70            .last()
71            .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
72        {
73            *multiplicities.last_mut().unwrap() += 1;
74        } else {
75            values.push(knot);
76            multiplicities.push(1);
77        }
78    }
79    (values, multiplicities)
80}
81pub(crate) use crate::edge_subcurve::edge_subcurve;
82
83
84#[derive(Default)]
85pub(crate) struct StepWriter {
86    lines: Vec<String>,
87}
88
89impl StepWriter {
90    pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
91        let id = self.lines.len() + 1;
92        self.lines.push(format!("#{id}={};", body.into()));
93        id
94    }
95
96    fn data(&self) -> String {
97        self.lines.join("\n")
98    }
99}
100
101pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
102    Ok(writer.add(format!(
103        "CARTESIAN_POINT('',({},{},{}))",
104        real(point.x)?,
105        real(point.y)?,
106        real(point.z)?
107    )))
108}
109
110pub(crate) fn id_list(ids: &[usize]) -> String {
111    format!(
112        "({})",
113        ids.iter()
114            .map(|id| format!("#{id}"))
115            .collect::<Vec<_>>()
116            .join(",")
117    )
118}
119
120pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
121    Ok(writer.add(format!(
122        "DIRECTION('',({},{},{}))",
123        real(direction.x)?,
124        real(direction.y)?,
125        real(direction.z)?
126    )))
127}
128
129pub(crate) fn write_placement(
130    writer: &mut StepWriter,
131    origin: Vec3,
132    axis: Vec3,
133    ref_direction: Vec3,
134) -> Result<usize, String> {
135    let origin = write_point(writer, origin)?;
136    let axis = write_direction(writer, axis)?;
137    let ref_direction = write_direction(writer, ref_direction)?;
138    Ok(writer.add(format!(
139        "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
140    )))
141}
142
143/// Emit the analytic AP242 surface entity (PLANE / CYLINDRICAL_SURFACE /
144/// CONICAL_SURFACE / SPHERICAL_SURFACE / TOROIDAL_SURFACE) for a recognized
145/// carrier, or `None` when the surface must stay a B-spline. The second value
146/// reports whether the STEP-standard orientation of the emitted entity (plane
147/// normal along the placement axis; revolution normal outward) is the REVERSE
148/// of the stored NURBS orientation, so ADVANCED_FACE can invert `same_sense`
149/// and the face normal survives the round trip. The third describes the
150/// emitted entity's own (u,v) parameterization for the pcurve writer.
151fn write_analytic_surface(
152    writer: &mut StepWriter,
153    surface: &NurbsSurface,
154) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
155    let Some(analytic) = surface.analytic() else {
156        return Ok(None);
157    };
158    match analytic {
159        AnalyticSurface::Plane {
160            origin,
161            u_dir,
162            v_dir,
163            ..
164        } => {
165            // STEP planes are unbounded; the importer re-sizes the patch from
166            // the face's edges, so only origin/normal/ref matter.
167            let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
168            else {
169                return Ok(None);
170            };
171            let placement = write_placement(writer, *origin, normal, x_axis)?;
172            // The reader derives the plane's second parameter axis as
173            // normal × ref_direction, so S(x,y) = origin + x·x̂ + y·ŷ with
174            // those exact vectors — an orthonormal frame regardless of how the
175            // stored patch scaled or sheared its own u_dir/v_dir.
176            Ok(Some((
177                writer.add(format!("PLANE('',#{placement})")),
178                false,
179                EmittedSurface::Plane {
180                    origin: *origin,
181                    x_axis,
182                    y_axis: normal.cross(x_axis),
183                },
184            )))
185        }
186        AnalyticSurface::RuledRevolution {
187            frame,
188            rho0,
189            rho1,
190            height,
191        } => {
192            // The recognizer allows height < 0 (descending generatrix), whose
193            // normal is the reverse of the standard outward convention the
194            // importer reconstructs; report that so the face sense compensates.
195            let flipped = *height < 0.0;
196            let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
197            if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
198                if *rho0 <= 0.0 {
199                    return Ok(None);
200                }
201                let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
202                return Ok(Some((
203                    writer.add(format!(
204                        "CYLINDRICAL_SURFACE('',#{placement},{})",
205                        real(*rho0)?
206                    )),
207                    flipped,
208                    EmittedSurface::Cylinder {
209                        frame: EmittedFrame {
210                            origin: frame.origin,
211                            x_axis: frame.x_axis,
212                            y_axis: frame.y_axis,
213                            axis: frame.axis,
214                            azimuth_sign: 1.0,
215                        },
216                        radius: *rho0,
217                    },
218                )));
219            }
220            // Cone. The importer re-sizes the carrier from edge samples with a
221            // 1e-4-scaled axial margin and clamps a negative extended-end
222            // radius to zero — which BENDS the rebuilt slope when the apex sits
223            // at an end of the face's axial range. Keep apex-touching cones as
224            // exact NURBS instead of exporting a distorted carrier.
225            let slope = (rho1 - rho0) / height;
226            let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
227            if rho0.min(*rho1) <= apex_margin {
228                return Ok(None);
229            }
230            // Orient the placement axis so the radius grows along +axis: STEP
231            // semi-angles are positive. Radius at the placement origin stays
232            // rho0 either way because the origin is on-axis at the v = 0 base.
233            let axis = if slope >= 0.0 {
234                frame.axis
235            } else {
236                frame.axis.scale(-1.0)
237            };
238            let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
239            Ok(Some((
240                writer.add(format!(
241                    "CONICAL_SURFACE('',#{placement},{},{})",
242                    real(*rho0)?,
243                    real(slope.abs().atan())?
244                )),
245                flipped,
246                EmittedSurface::Cone {
247                    frame: EmittedFrame {
248                        origin: frame.origin,
249                        x_axis: frame.x_axis,
250                        // Reversing the placement axis reverses the derived
251                        // second axis with it, so the emitted azimuth runs
252                        // opposite the stored carrier's u.
253                        y_axis: axis.cross(frame.x_axis),
254                        axis,
255                        azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
256                    },
257                    radius: *rho0,
258                    semi_angle: slope.abs().atan(),
259                },
260            )))
261        }
262        AnalyticSurface::Sphere { frame, radius } => {
263            // Recognition template and importer reconstruction share the same
264            // south-to-north meridian construction, so the rebuild is exact.
265            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
266            Ok(Some((
267                writer.add(format!(
268                    "SPHERICAL_SURFACE('',#{placement},{})",
269                    real(*radius)?
270                )),
271                false,
272                EmittedSurface::Sphere {
273                    frame: EmittedFrame {
274                        origin: frame.origin,
275                        x_axis: frame.x_axis,
276                        y_axis: frame.y_axis,
277                        axis: frame.axis,
278                        azimuth_sign: 1.0,
279                    },
280                    radius: *radius,
281                },
282            )))
283        }
284        AnalyticSurface::Torus {
285            frame,
286            major_radius,
287            minor_radius,
288        } => {
289            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
290            Ok(Some((
291                writer.add(format!(
292                    "TOROIDAL_SURFACE('',#{placement},{},{})",
293                    real(*major_radius)?,
294                    real(*minor_radius)?
295                )),
296                false,
297                EmittedSurface::Torus {
298                    frame: EmittedFrame {
299                        origin: frame.origin,
300                        x_axis: frame.x_axis,
301                        y_axis: frame.y_axis,
302                        axis: frame.axis,
303                        azimuth_sign: 1.0,
304                    },
305                    major_radius: *major_radius,
306                    minor_radius: *minor_radius,
307                },
308            )))
309        }
310        // No SURFACE_OF_REVOLUTION reader exists yet; general revolutions keep
311        // their exact NURBS form — except a sphere, which a reader knows.
312        AnalyticSurface::Revolution { frame, generatrix, .. } => {
313            let Some((center, radius, reversed)) = polar_meridian_sphere(frame, generatrix) else {
314                return Ok(None);
315            };
316            let placement = write_placement(writer, center, frame.axis, frame.x_axis)?;
317            Ok(Some((
318                writer.add(format!(
319                    "SPHERICAL_SURFACE('',#{placement},{})",
320                    real(radius)?
321                )),
322                reversed,
323                EmittedSurface::Sphere {
324                    frame: EmittedFrame {
325                        origin: center,
326                        x_axis: frame.x_axis,
327                        y_axis: frame.y_axis,
328                        axis: frame.axis,
329                        azimuth_sign: 1.0,
330                    },
331                    radius,
332                },
333            )))
334        }
335    }
336}
337
338/// `BREP_STEP_SPHERE_OF_REVOLUTION` (default on, `=0` restores the B-spline):
339/// a revolution whose generatrix is an arc of a circle centred on the axis is
340/// written as a SPHERICAL_SURFACE, whatever its sweep, whichever way the arc
341/// runs and whether or not it reaches a pole.
342fn sphere_of_revolution_on() -> bool {
343    crate::switch!("BREP_STEP_SPHERE_OF_REVOLUTION", true)
344}
345
346/// The centre and radius of the sphere a general revolution lies on when its
347/// generatrix is an arc of a circle centred on the axis, in the meridian
348/// half-plane, and whether the arc runs north to south there, which makes the
349/// stored normal point inward. A part turn of a half circle about its own
350/// chord is such a surface: a lune between the two poles, which a reader can
351/// bound on a sphere but not on a B-spline patch whose two pole sides have no
352/// length.
353///
354/// The arc is read span by span, so a piece split out of a longer circle
355/// (knots and end weights no longer `make_arc`'s) is taken too: each rational
356/// quadratic span is a circular arc about `centre` exactly when its ends are
357/// at the radius, its middle control point is where the end tangents meet,
358/// and its weights satisfy w1² = w0·w2·cos²(half the span's angle).
359fn polar_meridian_sphere(
360    frame: &crate::analytic_surface::RevolutionFrame,
361    generatrix: &NurbsCurve,
362) -> Option<(Vec3, f64, bool)> {
363    if !sphere_of_revolution_on() {
364        return None;
365    }
366    let controls = &generatrix.control_points;
367    let count = controls.len();
368    if generatrix.degree != 2 || count < 3 || count % 2 == 0 || generatrix.knots.len() != count + 3 {
369        return None;
370    }
371    // Bezier spans: every interior knot twice.
372    let knots = &generatrix.knots;
373    let span_knots = (count - 1) / 2;
374    for span in 1..span_knots {
375        if (knots[1 + 2 * span] - knots[2 + 2 * span]).abs() > 1e-12 {
376            return None;
377        }
378    }
379    let scale = curve_scale(generatrix);
380    let tolerance = 1e-9 * scale.max(1.0);
381    let mut points = Vec::with_capacity(count);
382    for control in controls {
383        if control.w <= 0.0 {
384            return None;
385        }
386        let point = control.point().ok()?;
387        // in the meridian half-plane the frame's x axis and its axis span
388        let d = point.sub(frame.origin);
389        if d.dot(frame.y_axis).abs() > tolerance || d.dot(frame.x_axis) < -tolerance {
390            return None;
391        }
392        points.push(point);
393    }
394    // The centre is on the axis at height `t` above the frame's origin; every
395    // span gives linear conditions on it (ends equidistant, end tangents
396    // square to the radii).
397    let (mut num, mut den) = (0.0, 0.0);
398    for span in 0..span_knots {
399        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
400        for (direction, through) in [
401            (p2.sub(p0), p0.add(p2).scale(0.5)),
402            (p1.sub(p0), p0),
403            (p1.sub(p2), p2),
404        ] {
405            // direction · (through − origin − t·axis) = 0
406            let a = direction.dot(frame.axis);
407            let b = direction.dot(through.sub(frame.origin));
408            num += a * b;
409            den += a * a;
410        }
411    }
412    if den <= tolerance * tolerance {
413        return None;
414    }
415    let center = frame.origin.add(frame.axis.scale(num / den));
416    let radius = points[0].sub(center).length();
417    if radius <= tolerance {
418        return None;
419    }
420    let mut turn = 0.0;
421    for span in 0..span_knots {
422        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
423        let (r0, r1, r2) = (p0.sub(center), p1.sub(center), p2.sub(center));
424        if (r0.length() - radius).abs() > tolerance
425            || (r2.length() - radius).abs() > tolerance
426            || p1.sub(p0).dot(r0).abs() > tolerance * radius
427            || p1.sub(p2).dot(r2).abs() > tolerance * radius
428        {
429            return None;
430        }
431        // cos(half the span's angle) = radius / |r1|
432        let cos_half = radius / r1.length();
433        let (w0, w1, w2) = (controls[2 * span].w, controls[2 * span + 1].w, controls[2 * span + 2].w);
434        if !(cos_half > 1e-6) || (w1 * w1 / (w0 * w2) - cos_half * cos_half).abs() > 1e-9 {
435            return None;
436        }
437        // which way the span turns in the (x, axis) half-plane
438        let cross = r0.dot(frame.x_axis) * r2.dot(frame.axis) - r0.dot(frame.axis) * r2.dot(frame.x_axis);
439        if cross.abs() <= tolerance * radius || (turn != 0.0 && cross.signum() != turn) {
440            return None;
441        }
442        turn = cross.signum();
443    }
444    Some((center, radius, turn < 0.0))
445}
446
447/// A curve recognized as an exact `make_arc` product: a circular arc of
448/// `radius` about `axis`, starting at angle 0 on `x_axis` and travelling
449/// counterclockwise through `sweep` — exactly the CIRCLE parameterization the
450/// importer trims between the edge's vertices.
451struct CircularArc {
452    center: Vec3,
453    axis: Vec3,
454    x_axis: Vec3,
455    /// axis × x_axis — the second placement axis a STEP reader derives, so the
456    /// emitted parameterization is C(a) = center + r(cos a·x̂ + sin a·ŷ).
457    y_axis: Vec3,
458    radius: f64,
459    /// Total swept angle: the emitted entity's parameter range is [0, sweep].
460    sweep: f64,
461    /// Rational-quadratic span count of the kernel arc this was recognized
462    /// from — the bridge from the emitted ANGLE back to the kernel's own
463    /// parameter, which a fitted pcurve on a B-spline carrier needs.
464    spans: usize,
465}
466
467
468
469/// Homogeneous-net equality to a scale-relative tolerance (the same
470/// reconstruction contract analytic_surface.rs uses): matching nets mean the
471/// curves are the SAME exact rational arc, not merely close.
472fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
473    if a.degree != b.degree
474        || a.knots.len() != b.knots.len()
475        || a.control_points.len() != b.control_points.len()
476    {
477        return false;
478    }
479    if a.knots
480        .iter()
481        .zip(&b.knots)
482        .any(|(x, y)| (x - y).abs() > 1e-12)
483    {
484        return false;
485    }
486    let tolerance = 1e-9 * scale.max(1.0);
487    a.control_points
488        .iter()
489        .zip(&b.control_points)
490        .all(|(p, q)| {
491            (p.x - q.x).abs() <= tolerance
492                && (p.y - q.y).abs() <= tolerance
493                && (p.z - q.z).abs() <= tolerance
494                && (p.w - q.w).abs() <= 1e-9
495        })
496}
497
498/// Recognition by exact reconstruction: extract a candidate circle from three
499/// curve points, rebuild it with `make_arc`, and demand the identical net.
500/// Split subranges of a circle (whose knots are no longer the pristine
501/// make_arc pattern) are rejected and honestly stay NURBS.
502fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
503    if curve.degree != 2
504        || curve.control_points.len() < 3
505        || curve.control_points.len() % 2 == 0
506        || (curve.control_points.len() - 1) / 2 > 4
507    {
508        return None;
509    }
510    let [t0, t1] = curve.domain().ok()?;
511    let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
512    // Three points at < 74% of the sweep apart, so consecutive pairs subtend
513    // less than pi and the cross product below gives the travel direction.
514    let p0 = at(0.0).ok()?;
515    let pa = at(0.35).ok()?;
516    let pb = at(0.7).ok()?;
517    let center = circumcenter(p0, pa, pb)?;
518    let radial = p0.sub(center);
519    let radius = radial.length();
520    let scale = curve_scale(curve);
521    if radius <= 1e-9 * scale.max(1.0) {
522        return None;
523    }
524    let x_axis = radial.scale(1.0 / radius);
525    let axis = radial.cross(pa.sub(center)).normalized().ok()?;
526    let y_axis = axis.cross(x_axis);
527    let p_end = at(1.0).ok()?;
528    let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
529        std::f64::consts::TAU
530    } else {
531        let closing = p_end.sub(center);
532        let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
533        if angle < 0.0 {
534            angle += std::f64::consts::TAU;
535        }
536        angle
537    };
538    let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
539    curves_match(curve, &rebuilt, scale).then_some(CircularArc {
540        center,
541        axis,
542        x_axis,
543        y_axis,
544        radius,
545        sweep,
546        spans: (curve.control_points.len() - 1) / 2,
547    })
548}
549
550/// Emit LINE or CIRCLE for a recognized analytic edge curve (already oriented
551/// start-to-end by `edge_subcurve`), or `None` for the B-spline fallback.
552///
553/// The second value describes the parameterization ISO 10303-42 gives the
554/// entity that was written, because a pcurve on this edge has to share THAT
555/// parameter — not the kernel's knot values (see `step/pcurve.rs`).
556fn write_analytic_curve(
557    writer: &mut StepWriter,
558    curve: &NurbsCurve,
559) -> Result<Option<(usize, EmittedCurve)>, String> {
560    if curve.degree == 1
561        && curve.control_points.len() == 2
562        && curve
563            .control_points
564            .iter()
565            .all(|control| (control.w - 1.0).abs() <= 1e-12)
566    {
567        let start = curve.control_points[0].point()?;
568        let end = curve.control_points[1].point()?;
569        let Ok(direction) = end.sub(start).normalized() else {
570            return Ok(None);
571        };
572        let point = write_point(writer, start)?;
573        let step_direction = write_direction(writer, direction)?;
574        let vector = writer.add(format!(
575            "VECTOR('',#{step_direction},{})",
576            real(end.sub(start).length())?
577        ));
578        return Ok(Some((
579            writer.add(format!("LINE('',#{point},#{vector})")),
580            // The VECTOR carries the full chord length, so the STEP parameter
581            // of this line is the fraction along the chord: C(s) = start +
582            // s·(end − start) over [0, 1].
583            EmittedCurve::Line { start, end },
584        )));
585    }
586    if let Some(arc) = recognize_circular_arc(curve) {
587        // ref_direction points at the edge's start vertex and the arc runs
588        // counterclockwise about the axis, so the importer's vertex-trimmed
589        // CCW rebuild reproduces the same directed curve with sense .T.
590        let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
591        return Ok(Some((
592            writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
593            EmittedCurve::Circle {
594                center: arc.center,
595                x_axis: arc.x_axis,
596                y_axis: arc.y_axis,
597                radius: arc.radius,
598                sweep: arc.sweep,
599                spans: arc.spans,
600            },
601        )));
602    }
603    Ok(None)
604}
605
606fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
607    let points = curve
608        .control_points
609        .iter()
610        .map(|control| write_point(writer, control.point()?))
611        .collect::<Result<Vec<_>, _>>()?;
612    write_bspline_curve(writer, curve, &points)
613}
614
615/// The B_SPLINE_CURVE_WITH_KNOTS entity (or its rational complex form) over
616/// control points that have ALREADY been written — shared by the 3D edge
617/// curves and by the 2D pcurves, whose CARTESIAN_POINTs carry two coordinates
618/// instead of three but whose degree/knots/weights are written identically.
619fn write_bspline_curve(
620    writer: &mut StepWriter,
621    curve: &NurbsCurve,
622    points: &[usize],
623) -> Result<usize, String> {
624    let (knot_values, multiplicities) = knot_runs(&curve.knots);
625    let multiplicities = format!(
626        "({})",
627        multiplicities
628            .iter()
629            .map(usize::to_string)
630            .collect::<Vec<_>>()
631            .join(",")
632    );
633    let knots = format!(
634        "({})",
635        knot_values
636            .iter()
637            .map(|value| real(*value))
638            .collect::<Result<Vec<_>, _>>()?
639            .join(",")
640    );
641    let rational = curve
642        .control_points
643        .iter()
644        .any(|control| (control.w - 1.0).abs() > 1e-12);
645    if !rational {
646        return Ok(writer.add(format!(
647            "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
648            curve.degree,
649            id_list(points),
650        )));
651    }
652    let weights = format!(
653        "({})",
654        curve
655            .control_points
656            .iter()
657            .map(|control| real(control.w))
658            .collect::<Result<Vec<_>, _>>()?
659            .join(",")
660    );
661    Ok(writer.add(format!(
662        "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
663         B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
664         CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
665         REPRESENTATION_ITEM(''))",
666        curve.degree,
667        id_list(points),
668    )))
669}
670
671fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
672    Ok(writer.add(format!(
673        "CARTESIAN_POINT('',({},{}))",
674        real(point[0])?,
675        real(point[1])?
676    )))
677}
678
679fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
680    Ok(writer.add(format!(
681        "DIRECTION('',({},{}))",
682        real(direction[0])?,
683        real(direction[1])?
684    )))
685}
686
687/// Write the 2D geometry of one pcurve.
688///
689/// The `VECTOR` of a 2D LINE carries its TRUE magnitude rather than being
690/// normalized to 1: ISO 10303-42 parameterizes a line as pnt + u·(magnitude ×
691/// orientation), so the magnitude is what makes the 2D parameter equal the 3D
692/// entity's parameter exactly.  (OpenCASCADE normalizes every VECTOR it writes
693/// and then loses that agreement wherever the two speeds differ — its own cone
694/// ruling pcurves are off by cos(semi-angle) — so this is strictly the more
695/// faithful of the two conventions, and identical wherever the speeds agree.)
696fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
697    match curve {
698        Pcurve2d::Line { point, vector } => {
699            let magnitude = vector[0].hypot(vector[1]);
700            if magnitude <= 0.0 {
701                return Err("export_step: degenerate 2D line pcurve".into());
702            }
703            let point_id = write_point_2d(writer, *point)?;
704            let direction =
705                write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
706            let vector_id = writer.add(format!(
707                "VECTOR('',#{direction},{})",
708                real(magnitude)?
709            ));
710            Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
711        }
712        Pcurve2d::Circle {
713            center,
714            ref_direction,
715            radius,
716        } => {
717            let center_id = write_point_2d(writer, *center)?;
718            let direction = write_direction_2d(writer, *ref_direction)?;
719            let placement = writer.add(format!(
720                "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
721            ));
722            Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
723        }
724        Pcurve2d::Spline(spline) => {
725            let points = spline
726                .control_points
727                .iter()
728                .map(|control| {
729                    let point = control.point()?;
730                    write_point_2d(writer, [point.x, point.y])
731                })
732                .collect::<Result<Vec<_>, String>>()?;
733            write_bspline_curve(writer, spline, &points)
734        }
735    }
736}
737
738/// `PCURVE('', surface, DEFINITIONAL_REPRESENTATION('', (2d curve), ctx))` —
739/// the association of one 2D curve with the surface it parameterizes.
740fn write_pcurve_entity(
741    writer: &mut StepWriter,
742    surface_id: usize,
743    context_2d: usize,
744    curve: &Pcurve2d,
745) -> Result<usize, String> {
746    let geometry = write_pcurve_geometry(writer, curve)?;
747    let representation = writer.add(format!(
748        "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
749    ));
750    Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
751}
752
753fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
754    let rows = surface
755        .control_points
756        .iter()
757        .map(|row| {
758            row.iter()
759                .map(|control| write_point(writer, control.point()?))
760                .collect::<Result<Vec<_>, _>>()
761                .map(|ids| id_list(&ids))
762        })
763        .collect::<Result<Vec<_>, _>>()?;
764    let grid = format!("({})", rows.join(","));
765    let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
766    let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
767    let multiplicities = |values: &[usize]| {
768        format!(
769            "({})",
770            values
771                .iter()
772                .map(usize::to_string)
773                .collect::<Vec<_>>()
774                .join(",")
775        )
776    };
777    let knots = |values: &[f64]| -> Result<String, String> {
778        Ok(format!(
779            "({})",
780            values
781                .iter()
782                .map(|value| real(*value))
783                .collect::<Result<Vec<_>, _>>()?
784                .join(",")
785        ))
786    };
787    let u_mults = multiplicities(&u_multiplicities);
788    let v_mults = multiplicities(&v_multiplicities);
789    let u_knots = knots(&u_values)?;
790    let v_knots = knots(&v_values)?;
791    let rational = surface
792        .control_points
793        .iter()
794        .flatten()
795        .any(|control| (control.w - 1.0).abs() > 1e-12);
796    if !rational {
797        return Ok(writer.add(format!(
798            "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
799             {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
800            surface.degree_u, surface.degree_v,
801        )));
802    }
803    let weights = format!(
804        "({})",
805        surface
806            .control_points
807            .iter()
808            .map(|row| {
809                row.iter()
810                    .map(|control| real(control.w))
811                    .collect::<Result<Vec<_>, _>>()
812                    .map(|values| format!("({})", values.join(",")))
813            })
814            .collect::<Result<Vec<_>, _>>()?
815            .join(",")
816    );
817    Ok(writer.add(format!(
818        "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
819         B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
820         GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
821         REPRESENTATION_ITEM('')SURFACE())",
822        surface.degree_u, surface.degree_v,
823    )))
824}
825
826fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
827    let normalized = unit.to_lowercase();
828    if normalized == "meter" || normalized == "metre" {
829        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
830    }
831    if normalized == "centimeter" || normalized == "centimetre" {
832        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
833    }
834    if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
835        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
836    }
837    if normalized == "inch" || normalized == "foot" {
838        let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
839        let (factor, name) = if normalized == "inch" {
840            (0.0254, "INCH")
841        } else {
842            (0.3048, "FOOT")
843        };
844        let measure = writer.add(format!(
845            "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
846            real(factor)?
847        ));
848        return Ok(writer.add(format!(
849            "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
850        )));
851    }
852    Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
853}
854
855/// The outward shell (an index into `shells`, one of `outer`) that owns the
856/// void `void`: the smallest by volume of those its shell lies inside. The
857/// shells of a valid solid do not meet, so one point of the void (the middle
858/// of its first proper edge) is inside or outside each of them throughout.
859fn void_owner(
860    solid: &BrepSolid,
861    void: usize,
862    outer: &[usize],
863    shells: &[(usize, bool, f64)],
864) -> Result<usize, String> {
865    let probe = solid.shells[void]
866        .faces
867        .iter()
868        .flat_map(|face| &face.loops)
869        .flat_map(|lp| &lp.coedges)
870        .find_map(|coedge| {
871            let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
872            (!edge.degenerate).then(|| edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()).flatten()
873        })
874        .ok_or("export_step: a void shell with no edge to place it by")?;
875    let mut best: Option<usize> = None;
876    for &candidate in outer {
877        let alone = BrepSolid {
878            shells: vec![solid.shells[candidate].clone()],
879            ..solid.clone()
880        };
881        let class = crate::classify_point(probe, &alone, 1e-7)?.class;
882        if class == crate::PointClass::In && best.is_none_or(|b| shells[candidate].2 < shells[b].2) {
883            best = Some(candidate);
884        }
885    }
886    best.ok_or_else(|| "export_step: a void shell lies inside no outward shell".into())
887}
888
889fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
890    solid
891        .vertices
892        .iter()
893        .find(|vertex| vertex.id == id)
894        .ok_or_else(|| format!("export_step: missing vertex {id}"))
895}
896
897fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
898    solid
899        .edges
900        .iter()
901        .find(|edge| edge.id == id)
902        .ok_or_else(|| format!("export_step: missing edge {id}"))
903}
904
905fn surface_key(face: &FaceRecord) -> usize {
906    face as *const FaceRecord as usize
907}
908
909/// One use of an edge by a face's loop.  Curve-on-surface geometry is written
910/// per USE — a pcurve names the surface it lives on — so the writer needs the
911/// full adjacency of an edge before it can emit that edge.
912struct CoedgeUse<'a> {
913    surface_key: usize,
914    face: &'a FaceRecord,
915    coedge: &'a CoedgeRecord,
916}
917
918/// The AP242 document plus what the writer measured while producing it.
919///
920/// The pcurve counters are the honest half of the verify-or-omit contract in
921/// `step/pcurve.rs`: a pcurve is written only when the emitted 2D geometry was
922/// proved to reproduce the emitted 3D curve, and every one that could not be
923/// proved is COUNTED here rather than guessed into the file.  A reader
924/// reprojects an omitted pcurve exactly as it must reproject every pcurve in
925/// the files this exporter wrote before curve-on-surface geometry existed.
926#[derive(Clone, Debug, Default)]
927pub struct StepExportReport {
928    /// The Part 21 text.
929    pub text: String,
930    /// `PCURVE` entities written — at most one per coedge use of a
931    /// non-degenerate edge.
932    pub pcurves_written: usize,
933    /// Coedge uses left without a pcurve because no candidate 2D geometry
934    /// verified inside the export band.
935    pub pcurves_omitted: usize,
936    /// Edges written as `SURFACE_CURVE` (their two uses sit on two surfaces).
937    pub surface_curves: usize,
938    /// Edges written as `SEAM_CURVE` (both uses on ONE surface — a periodic
939    /// seam, the case an importer otherwise has to re-detect geometrically).
940    pub seam_curves: usize,
941    /// Edges that kept a bare 3D curve for `edge_geometry`, because no pcurve
942    /// survived (or a seam lost one of the pair it is required to carry).
943    pub bare_curves: usize,
944    /// Collapsed face boundaries written as `VERTEX_LOOP` — cone apexes and
945    /// sphere poles, which this writer used to drop entirely.
946    pub vertex_loops: usize,
947    /// Largest verified ‖S(c₂d(s)) − c₃d(s)‖ among the pcurves actually
948    /// written, in model units.
949    pub max_pcurve_deviation: f64,
950    /// Largest deviation among the BEST candidate for each OMITTED pcurve —
951    /// how far the closest miss was, so an omission can be diagnosed as "a
952    /// candidate applied and missed the band by this much" rather than only
953    /// counted. Zero when nothing was omitted.
954    ///
955    /// It is infinite when ANY omission had no candidate proposed at all, which
956    /// then hides the finite misses behind it — the two omission classes share
957    /// one counter. Splitting them is a follow-up; the max is the useful half,
958    /// because it is the finite value that says whether widening the band would
959    /// have helped.
960    pub worst_omitted_deviation: f64,
961    /// DISTINCT PMI reference names (`{body}`, `{body}:face`, `{body}@x,y,z`)
962    /// that named no entity in the written file, so every annotation on them
963    /// was skipped. Zero for a file whose PMI all resolved. The structured
964    /// (assembly) lane is what can move a reference: a component's geometry is
965    /// written into the PART's product, and a stale reference to a body that no
966    /// longer exists is counted here rather than dropped in silence.
967    pub pmi_unresolved_references: usize,
968    /// PRODUCTs written. `1` for the flat lane; the structured lane writes one
969    /// per distinct part plus one for the root document.
970    pub products: usize,
971    /// `NEXT_ASSEMBLY_USAGE_OCCURRENCE` edges written — the placed component
972    /// instances. Zero for the flat lane.
973    pub occurrences: usize,
974    /// `STYLED_ITEM`s written for GEOMETRY colour — one per coloured body and
975    /// per coloured face (`step/styles.rs`). Zero when the caller passed no
976    /// colours, or when none of the names it passed named written geometry;
977    /// the PMI block's own styled item is not counted here.
978    pub styled_items: usize,
979}
980
981/// Serialize exact NURBS BREP topology as an AP242 STEP Part 21 document.
982///
983/// `unit` LABELS the caller's coordinates (`SI_UNIT($,.METRE.)`, `.MILLI.`,
984/// inch and foot conversion factors): the writer does not scale them. A
985/// kernel body is in millimetres, so a metre-unit file wants the body
986/// pre-scaled by 1e-3 (`transform_brep` with a uniform scale) first; a
987/// millimetre body written under `"meter"` re-imports at 1e9 × its volume
988/// (measured 2026-10-03).
989pub fn export_step(
990    solids: &[BrepSolid],
991    name: &str,
992    unit: &str,
993    timestamp: &str,
994) -> Result<String, String> {
995    export_step_report(solids, name, unit, timestamp).map(|report| report.text)
996}
997
998/// [`export_step`] plus the pcurve-coverage measurements behind the file.
999/// Every body is written under the part name; no PMI.
1000pub fn export_step_report(
1001    solids: &[BrepSolid],
1002    name: &str,
1003    unit: &str,
1004    timestamp: &str,
1005) -> Result<StepExportReport, String> {
1006    let named: Vec<(String, &BrepSolid)> = solids
1007        .iter()
1008        .map(|solid| (name.to_string(), solid))
1009        .collect();
1010    export_step_report_named(&named, name, unit, timestamp, None, None)
1011}
1012
1013/// The full writer: each body carries its SCENE NAME (`MANIFOLD_SOLID_BREP`
1014/// name — and the key the PMI references resolve through), and an optional
1015/// PMI block is written as AP242 semantic representation + polyline
1016/// presentation + saved views ([`pmi`]).
1017/// Where an exported geometry entity lives: the product whose shape it helps
1018/// define, and the representation that carries it. PMI attaches a shape aspect
1019/// to the OWNING product, which in a structured (assembly) export is the part's
1020/// own product, not the root document's.
1021#[derive(Clone, Copy)]
1022pub(crate) struct StepItemOwner {
1023    pub product_shape: usize,
1024    pub representation: usize,
1025}
1026
1027/// One product's geometry, written but not yet bound to a product definition.
1028/// The name lists are flat (not maps) because the same part can be reachable
1029/// under several occurrence paths, and each path registers its own alias.
1030#[derive(Default)]
1031pub(crate) struct ProductGeometry {
1032    /// Body name -> its STEP solid entity, in emission order. Inward shells
1033    /// belong to one `BREP_WITH_VOIDS`; independent outward shells each emit a
1034    /// `MANIFOLD_SOLID_BREP`. A coloured body is styled on this entity
1035    /// (`step/styles.rs`), and the representation's item list is the ids alone.
1036    pub solids: Vec<(String, usize)>,
1037    /// Face name -> its `ADVANCED_FACE`.
1038    pub faces: Vec<(String, usize)>,
1039    /// Edge name -> its `EDGE_CURVE`.
1040    pub edges: Vec<(String, usize)>,
1041    /// Body name -> that body's `VERTEX_POINT`s (LOCAL point, entity id).
1042    pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
1043}
1044
1045/// The PMI reference maps, folded from every product's [`ProductGeometry`] once
1046/// its owner is known. A structured export registers each product's entities
1047/// under EVERY occurrence path that reaches it (`ACOMP3:`, `ACOMP5:ACOMP1:`),
1048/// which is exactly how the document names a component's geometry.
1049#[derive(Default)]
1050pub(crate) struct StepNameMaps {
1051    pub faces: HashMap<String, (usize, StepItemOwner)>,
1052    pub edges: HashMap<String, (usize, StepItemOwner)>,
1053    /// Body name -> its owner and its `VERTEX_POINT`s in ROOT (document) space,
1054    /// because that is the frame a `{body}@x,y,z` PMI reference is written in.
1055    pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
1056}
1057
1058impl StepNameMaps {
1059    /// Register one product's entities under an occurrence path: `prefix` is the
1060    /// chained component namespace (`""` at the root), `world` maps the
1061    /// product's local frame into root space.
1062    pub(crate) fn register(
1063        &mut self,
1064        geometry: &ProductGeometry,
1065        owner: StepItemOwner,
1066        prefix: &str,
1067        world: &Mat4,
1068    ) {
1069        for (name, id) in &geometry.faces {
1070            self.faces
1071                .entry(format!("{prefix}{name}"))
1072                .or_insert((*id, owner));
1073        }
1074        for (name, id) in &geometry.edges {
1075            self.edges
1076                .entry(format!("{prefix}{name}"))
1077                .or_insert((*id, owner));
1078        }
1079        for (name, points) in &geometry.vertices {
1080            let placed = points
1081                .iter()
1082                .map(|(point, id)| (transform_point(world, *point), *id))
1083                .collect();
1084            self.vertices
1085                .entry(format!("{prefix}{name}"))
1086                .or_insert((owner, placed));
1087        }
1088    }
1089}
1090
1091/// The file-wide entities every product's geometry is expressed against. One
1092/// set per FILE, shared by every product a structured export writes.
1093pub(crate) struct StepFileContexts {
1094    pub product_context: usize,
1095    pub definition_context: usize,
1096    pub geometry_context: usize,
1097    pub parametric_context: usize,
1098    pub length_unit: usize,
1099    pub angle_unit: usize,
1100    /// The IDENTITY `AXIS2_PLACEMENT_3D` — the first item of every shape
1101    /// representation, and `item_1` of every assembly placement's
1102    /// `ITEM_DEFINED_TRANSFORMATION` (the child frame's own origin).
1103    pub axis: usize,
1104}
1105
1106/// Write the header entities every AP242 body in this file shares.
1107pub(crate) fn write_file_contexts(
1108    writer: &mut StepWriter,
1109    unit: &str,
1110) -> Result<StepFileContexts, String> {
1111    let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
1112    writer.add(format!(
1113        "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
1114    ));
1115    let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
1116    let definition_context = writer.add(format!(
1117        "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
1118    ));
1119    let length_unit = write_length_unit(writer, unit)?;
1120    let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
1121    let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
1122    let uncertainty = writer.add(format!(
1123        "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
1124    ));
1125    let geometry_context = writer.add(format!(
1126        "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
1127         GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
1128         GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
1129         REPRESENTATION_CONTEXT('',''))"
1130    ));
1131    // ONE parametric context for every DEFINITIONAL_REPRESENTATION in the file.
1132    // It carries no unit assignment, so the importer's file-scale search
1133    // (`derive_length_scale_mm`, which keys on GLOBAL_UNIT_ASSIGNED_CONTEXT /
1134    // LENGTH_UNIT) cannot mistake it for the geometric context.
1135    let parametric_context = writer.add(
1136        "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
1137         PARAMETRIC_REPRESENTATION_CONTEXT()\
1138         REPRESENTATION_CONTEXT('2D SPACE',''))",
1139    );
1140    let origin = write_point(writer, Vec3::default())?;
1141    let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
1142    let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
1143    let axis = writer.add(format!(
1144        "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
1145    ));
1146    Ok(StepFileContexts {
1147        product_context,
1148        definition_context,
1149        geometry_context,
1150        parametric_context,
1151        length_unit,
1152        angle_unit,
1153        axis,
1154    })
1155}
1156
1157/// The product-definition chain of ONE product: what a `NEXT_ASSEMBLY_USAGE_
1158/// OCCURRENCE` references and what a `SHAPE_DEFINITION_REPRESENTATION` binds to
1159/// its geometry.
1160pub(crate) struct ProductIds {
1161    pub definition: usize,
1162    pub product_shape: usize,
1163}
1164
1165/// PRODUCT -> PRODUCT_DEFINITION -> PRODUCT_DEFINITION_SHAPE for one product.
1166/// `id` is the vendor part number (`PRODUCT.id`); the name is used when empty.
1167/// `category` is the `PRODUCT_RELATED_PRODUCT_CATEGORY` name — `'part'` for a
1168/// leaf, `'assembly'` for a product that places others, which is the
1169/// distinction a receiving system reads to build its own structure tree.
1170pub(crate) fn write_product(
1171    writer: &mut StepWriter,
1172    contexts: &StepFileContexts,
1173    name: &str,
1174    id: &str,
1175    category: &str,
1176) -> ProductIds {
1177    let safe_name = step_string(name);
1178    let safe_id = step_string(if id.is_empty() { name } else { id });
1179    let product_context = contexts.product_context;
1180    let definition_context = contexts.definition_context;
1181    let product = writer.add(format!(
1182        "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1183    ));
1184    writer.add(format!(
1185        "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1186        step_string(category)
1187    ));
1188    let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1189    let definition = writer.add(format!(
1190        "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1191    ));
1192    let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1193    ProductIds {
1194        definition,
1195        product_shape,
1196    }
1197}
1198
1199/// Validate every body the way the export gate requires, then write each one's
1200/// exact topology as a `MANIFOLD_SOLID_BREP` named by its scene name.
1201///
1202/// This is the whole geometry writer, factored out of the single-product lane so
1203/// the structured (assembly) lane can call it once PER PRODUCT into the same
1204/// file. It appends to `writer` and reads only file-wide entities, so products
1205/// share surfaces with nothing and cannot collide.
1206pub(crate) fn write_product_geometry(
1207    writer: &mut StepWriter,
1208    contexts: &StepFileContexts,
1209    bodies: &[(String, &BrepSolid)],
1210    report: &mut StepExportReport,
1211) -> Result<ProductGeometry, String> {
1212    for (_, solid) in bodies {
1213        let policy = KernelTolerances::for_solid(solid, 1e-7);
1214        let issues = solid.validate_with_tolerances(&KernelTolerances {
1215            pcurve_consistency: policy.export_knit,
1216            ..policy
1217        });
1218        if !issues.is_empty() {
1219            return Err(format!("export_step: invalid solid: {issues:?}"));
1220        }
1221    }
1222    let parametric_context = contexts.parametric_context;
1223    let mut written = ProductGeometry::default();
1224    for (solid_name, solid) in bodies {
1225        let solid = *solid;
1226        let solid_name = solid_name.as_str();
1227        let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1228        let mut vertex_ids = HashMap::<u64, usize>::default();
1229        let mut edge_ids = HashMap::<u64, usize>::default();
1230        let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1231        let mut emitted_shells = Vec::new();
1232        for shell in &solid.shells {
1233            // Pass 1 — SURFACES. A pcurve references the surface entity it
1234            // parameterizes, so every surface id has to exist before the first
1235            // edge is written. (Before curve-on-surface geometry the writer
1236            // could emit surfaces after the loops; it no longer can.)
1237            for face in &shell.faces {
1238                let key = surface_key(face);
1239                if surfaces.contains_key(&key) {
1240                    continue;
1241                }
1242                let entry = match write_analytic_surface(writer, &face.surface)? {
1243                    Some(triple) => triple,
1244                    None => (
1245                        write_surface(writer, &face.surface)?,
1246                        false,
1247                        EmittedSurface::Spline,
1248                    ),
1249                };
1250                surfaces.insert(key, entry);
1251            }
1252
1253            // Pass 2 — ADJACENCY. Which faces use each edge, in first-encounter
1254            // order so the emitted entity numbering stays deterministic.
1255            let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1256            let mut edge_order: Vec<u64> = Vec::new();
1257            for face in &shell.faces {
1258                for loop_record in &face.loops {
1259                    for coedge in &loop_record.coedges {
1260                        let edge = edge_for(solid, coedge.edge_id)?;
1261                        if edge.degenerate {
1262                            continue;
1263                        }
1264                        let uses = edge_uses.entry(edge.id).or_default();
1265                        if uses.is_empty() {
1266                            edge_order.push(edge.id);
1267                        }
1268                        uses.push(CoedgeUse {
1269                            surface_key: surface_key(face),
1270                            face,
1271                            coedge,
1272                        });
1273                    }
1274                }
1275            }
1276
1277            // Pass 3 — EDGES with their curve-on-surface geometry.
1278            for edge_id in &edge_order {
1279                if edge_ids.contains_key(edge_id) {
1280                    continue;
1281                }
1282                let edge = edge_for(solid, *edge_id)?;
1283                let subcurve = edge_subcurve(edge)?;
1284                let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1285                    Some(pair) => pair,
1286                    None => (
1287                        write_curve(writer, &subcurve)?,
1288                        EmittedCurve::Spline { curve: subcurve },
1289                    ),
1290                };
1291                let uses = &edge_uses[edge_id];
1292                // Two uses on ONE surface is a periodic seam: the two halves of
1293                // the edge sit on opposite domain boundaries and the reader is
1294                // told so explicitly instead of having to rediscover it.
1295                let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1296                let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1297                let mut omitted = 0usize;
1298                if uses.len() == 2 {
1299                    // Slot order for a seam: the FORWARD-oriented coedge first,
1300                    // the reversed one second — the pairing OpenCASCADE writes
1301                    // and reads (BRep_CurveOnClosedSurface's PCurve1/PCurve2).
1302                    let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1303                    if seam && !ordered[0].coedge.forward {
1304                        ordered.swap(0, 1);
1305                    }
1306                    for coedge_use in ordered {
1307                        // The stored pcurve runs in LOOP direction; the edge's
1308                        // geometry runs in EDGE direction. Fraction-synchronised
1309                        // reversal is exact, so a reversed coedge's pcurve is
1310                        // simply flipped before it is expressed.
1311                        let oriented = if coedge_use.coedge.forward {
1312                            coedge_use.coedge.pcurve.clone()
1313                        } else {
1314                            coedge_use.coedge.pcurve.reversed()?
1315                        };
1316                        let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1317                        let outcome = build_pcurve(
1318                            &coedge_use.face.surface,
1319                            emitted_surface,
1320                            &emitted_curve,
1321                            &oriented,
1322                            band,
1323                        )?;
1324                        match outcome.curve {
1325                            Some(curve_2d) => {
1326                                report.max_pcurve_deviation =
1327                                    report.max_pcurve_deviation.max(outcome.deviation);
1328                                pcurves.push((*surface_id, curve_2d));
1329                            }
1330                            None => {
1331                                omitted += 1;
1332                                if outcome.deviation.is_finite() {
1333                                    report.worst_omitted_deviation =
1334                                        report.worst_omitted_deviation.max(outcome.deviation);
1335                                } else {
1336                                    report.worst_omitted_deviation = f64::INFINITY;
1337                                }
1338                            }
1339                        }
1340                    }
1341                }
1342                // A SEAM_CURVE is required to carry BOTH pcurves on the one
1343                // surface, so a seam that lost one falls all the way back to a
1344                // bare 3D curve rather than to a half-described seam.
1345                if seam && pcurves.len() != 2 {
1346                    omitted += pcurves.len();
1347                    pcurves.clear();
1348                }
1349                report.pcurves_omitted += omitted;
1350                report.pcurves_written += pcurves.len();
1351                let geometry = if pcurves.is_empty() {
1352                    report.bare_curves += 1;
1353                    curve
1354                } else {
1355                    let ids = pcurves
1356                        .iter()
1357                        .map(|(surface_id, curve_2d)| {
1358                            write_pcurve_entity(
1359                                writer,
1360                                *surface_id,
1361                                parametric_context,
1362                                curve_2d,
1363                            )
1364                        })
1365                        .collect::<Result<Vec<_>, String>>()?;
1366                    let keyword = if seam {
1367                        report.seam_curves += 1;
1368                        "SEAM_CURVE"
1369                    } else {
1370                        report.surface_curves += 1;
1371                        "SURFACE_CURVE"
1372                    };
1373                    // master_representation is .CURVE_3D.: our 3D curves are
1374                    // the exact authority the whole kernel and the export gate
1375                    // treat them as, and the pcurves above are verified AGAINST
1376                    // them. Promoting an approximation to master would be the
1377                    // one claim this writer must not make.
1378                    writer.add(format!(
1379                        "{keyword}('',#{curve},{},.CURVE_3D.)",
1380                        id_list(&ids)
1381                    ))
1382                };
1383                let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1384                let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1385                let step_id =
1386                    writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1387                edge_ids.insert(edge.id, step_id);
1388                if let Some(edge_name) = edge.name.as_deref() {
1389                    written.edges.push((edge_name.to_string(), step_id));
1390                }
1391            }
1392
1393            // Pass 4 — LOOPS and FACES over the ids the passes above fixed.
1394            let mut face_ids = Vec::new();
1395            for face in &shell.faces {
1396                let mut bound_ids = Vec::new();
1397                for (loop_index, loop_record) in face.loops.iter().enumerate() {
1398                    let mut oriented_edges = Vec::new();
1399                    for coedge in &loop_record.coedges {
1400                        let edge = edge_for(solid, coedge.edge_id)?;
1401                        if edge.degenerate {
1402                            continue;
1403                        }
1404                        let edge_id = *edge_ids
1405                            .get(&edge.id)
1406                            .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1407                        let orientation = if coedge.forward { ".T." } else { ".F." };
1408                        oriented_edges.push(
1409                            writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1410                        );
1411                    }
1412                    let kind = if loop_index == 0 {
1413                        "FACE_OUTER_BOUND"
1414                    } else {
1415                        "FACE_BOUND"
1416                    };
1417                    if oriented_edges.is_empty() {
1418                        // A bound left empty by the degenerate-edge skip is a
1419                        // COLLAPSED boundary — a cone apex, a sphere pole —
1420                        // and AP242 spells that `VERTEX_LOOP`, not nothing.
1421                        // Dropping it (what this writer did before) deletes the
1422                        // apex from the face's parameter domain, so an imported
1423                        // pointed cone lost its apex bound on re-export and
1424                        // every reader had to re-synthesise it from the
1425                        // surface's own degeneracy. A MIXED loop keeps the
1426                        // skip: that is OCCT's own write convention, both our
1427                        // importer and OCC's ShapeFix rebuild those, and the
1428                        // advanced-face conformance class permits vertex loops
1429                        // but not zero-length edge curves.
1430                        let Some(coedge) = loop_record.coedges.first() else {
1431                            continue;
1432                        };
1433                        let collapsed = edge_for(solid, coedge.edge_id)?;
1434                        let vertex = vertex_step_id(
1435                            writer,
1436                            &mut vertex_ids,
1437                            solid,
1438                            collapsed.start_vertex_id,
1439                        )?;
1440                        let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1441                        report.vertex_loops += 1;
1442                        bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1443                        continue;
1444                    }
1445                    let edge_loop =
1446                        writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1447                    bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1448                }
1449                let (surface, flipped, _) = surfaces[&surface_key(face)];
1450                // `flipped` analytic entities are written with the reverse of
1451                // the stored NURBS orientation, so invert the flag to keep the
1452                // face normal identical through the round trip.
1453                let sense = if face.same_sense != flipped {
1454                    ".T."
1455                } else {
1456                    ".F."
1457                };
1458                let face_step_id = writer.add(format!(
1459                    "ADVANCED_FACE('',{},#{surface},{sense})",
1460                    id_list(&bound_ids)
1461                ));
1462                if let Some(face_name) = face.name.as_deref() {
1463                    written.faces.push((face_name.to_string(), face_step_id));
1464                }
1465                face_ids.push(face_step_id);
1466            }
1467            let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1468            let signed_volume = if solid.shells.len() > 1 {
1469                crate::mass_properties::shell_signed_volume(shell)?
1470            } else {
1471                1.0
1472            };
1473            emitted_shells.push((closed_shell, signed_volume < 0.0, signed_volume.abs()));
1474        }
1475        if emitted_shells.iter().any(|&(_, inward, _)| inward) {
1476            let outer: Vec<usize> = (0..emitted_shells.len()).filter(|&i| !emitted_shells[i].1).collect();
1477            if outer.is_empty() {
1478                return Err("export_step: a solid with voids must have an outward shell".into());
1479            }
1480            // Each void belongs to the smallest outward shell around it: one
1481            // body per outward shell, its voids those it owns (several bodies
1482            // nested in each other's hollows are several solids in STEP).
1483            let mut owned: Vec<Vec<usize>> = vec![Vec::new(); emitted_shells.len()];
1484            for void in (0..emitted_shells.len()).filter(|&i| emitted_shells[i].1) {
1485                let owner = if outer.len() == 1 {
1486                    outer[0]
1487                } else {
1488                    void_owner(solid, void, &outer, &emitted_shells)?
1489                };
1490                owned[owner].push(void);
1491            }
1492            for &shell in &outer {
1493                let closed_shell = emitted_shells[shell].0;
1494                let body_id = if owned[shell].is_empty() {
1495                    writer.add(format!("MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)))
1496                } else {
1497                    let voids = owned[shell].iter()
1498                        .map(|&void| writer.add(format!("ORIENTED_CLOSED_SHELL('',*,#{},.T.)", emitted_shells[void].0)))
1499                        .collect::<Vec<_>>();
1500                    writer.add(format!(
1501                        "BREP_WITH_VOIDS('{}',#{closed_shell},{})", step_string(solid_name), id_list(&voids)
1502                    ))
1503                };
1504                written.solids.push((solid_name.to_string(), body_id));
1505            }
1506        } else {
1507            for (closed_shell, _, _) in emitted_shells {
1508                let body_id = writer.add(format!(
1509                    "MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)
1510                ));
1511                written.solids.push((solid_name.to_string(), body_id));
1512            }
1513        }
1514        // The vertices this solid wrote, for `{solid}@x,y,z` PMI references.
1515        let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1516        for (vertex_id, step_id) in &vertex_ids {
1517            points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1518        }
1519        written.vertices.push((solid_name.to_string(), points));
1520    }
1521    Ok(written)
1522}
1523
1524/// Wrap the written entities in the Part 21 envelope and run the emitted-text
1525/// audits — the last step of every export lane.
1526pub(crate) fn finish_step_file(
1527    writer: StepWriter,
1528    name: &str,
1529    timestamp: &str,
1530    report: &mut StepExportReport,
1531) -> Result<(), String> {
1532    let safe_name = step_string(name);
1533    let safe_timestamp = step_string(timestamp);
1534    let output = [
1535        "ISO-10303-21;".to_string(),
1536        "HEADER;".to_string(),
1537        "FILE_DESCRIPTION((''),'2;1');".to_string(),
1538        format!(
1539            "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1540        ),
1541        "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1542        "ENDSEC;".to_string(),
1543        "DATA;".to_string(),
1544        writer.data(),
1545        "ENDSEC;".to_string(),
1546        "END-ISO-10303-21;".to_string(),
1547        String::new(),
1548    ]
1549    .join("\n");
1550    let manifold_issues = audit_step_manifold(&output);
1551    if !manifold_issues.is_empty() {
1552        return Err(format!(
1553            "export_step: emitted AP242 manifold audit failed: {}",
1554            manifold_issues.join("; ")
1555        ));
1556    }
1557    let pcurve_issues = audit_step_pcurves(&output);
1558    if !pcurve_issues.is_empty() {
1559        return Err(format!(
1560            "export_step: emitted AP242 pcurve audit failed: {}",
1561            pcurve_issues.join("; ")
1562        ));
1563    }
1564    report.text = output;
1565    Ok(())
1566}
1567
1568/// The full single-product writer: each body carries its SCENE NAME
1569/// (`MANIFOLD_SOLID_BREP` name — and the key the PMI references resolve
1570/// through), and an optional PMI block is written as AP242 semantic
1571/// representation + polyline presentation + saved views (`pmi`).
1572///
1573/// This is the FLAT lane: one `PRODUCT`, every body in it, no assembly
1574/// structure. A document with components goes through
1575/// [`assembly::export_step_assembly_report`] instead.
1576pub fn export_step_report_named(
1577    solids: &[(String, &BrepSolid)],
1578    name: &str,
1579    unit: &str,
1580    timestamp: &str,
1581    pmi: Option<&StepPmi<'_>>,
1582    colors: Option<&StepColors>,
1583) -> Result<StepExportReport, String> {
1584    if solids.is_empty() {
1585        return Err("export_step: at least one solid is required".into());
1586    }
1587    let mut report = StepExportReport {
1588        products: 1,
1589        ..StepExportReport::default()
1590    };
1591    let mut writer = StepWriter::default();
1592    let contexts = write_file_contexts(&mut writer, unit)?;
1593    let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1594    let mut items = vec![contexts.axis];
1595    items.extend(geometry.solids.iter().map(|(_, id)| *id));
1596    let geometry_context = contexts.geometry_context;
1597    let representation = writer.add(format!(
1598        "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1599        id_list(&items)
1600    ));
1601    let product = write_product(&mut writer, &contexts, name, "", "part");
1602    let product_shape = product.product_shape;
1603    writer.add(format!(
1604        "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1605    ));
1606    // Geometry colour, before the PMI block so a file's presentation styles read
1607    // in geometry order. The flat lane's bodies carry their document names with
1608    // no component namespace, so the ONE prefix to resolve through is the empty
1609    // one.
1610    if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1611        let items = styles::styled_items(&geometry, colors, &[String::new()]);
1612        report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1613    }
1614    if let Some(pmi) = pmi {
1615        let mut names = StepNameMaps::default();
1616        names.register(
1617            &geometry,
1618            StepItemOwner {
1619                product_shape,
1620                representation,
1621            },
1622            "",
1623            &MAT4_IDENTITY,
1624        );
1625        let context = pmi::StepContext {
1626            product_shape,
1627            representation,
1628            geometry_context,
1629            length_unit: contexts.length_unit,
1630            angle_unit: contexts.angle_unit,
1631            faces: &names.faces,
1632            edges: &names.edges,
1633            vertices: &names.vertices,
1634        };
1635        report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1636    }
1637    finish_step_file(writer, name, timestamp, &mut report)?;
1638    Ok(report)
1639}
1640
1641/// VERTEX_POINT for a kernel vertex, written once per solid.
1642fn vertex_step_id(
1643    writer: &mut StepWriter,
1644    vertex_ids: &mut HashMap<u64, usize>,
1645    solid: &BrepSolid,
1646    id: u64,
1647) -> Result<usize, String> {
1648    if let Some(step_id) = vertex_ids.get(&id) {
1649        return Ok(*step_id);
1650    }
1651    let point = write_point(writer, vertex_for(solid, id)?.point)?;
1652    let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1653    vertex_ids.insert(id, step_id);
1654    Ok(step_id)
1655}
1656
1657/// Entity id -> body, for the serialized-text audits.  One entity per line is
1658/// this writer's own invariant, so the "parse" is a split.
1659fn step_entity_bodies(step: &str) -> HashMap<u64, &str> {
1660    step.lines()
1661        .filter_map(|line| {
1662            let rest = line.strip_prefix('#')?;
1663            let (digits, body) = rest.split_once('=')?;
1664            Some((
1665                digits.parse::<u64>().ok()?,
1666                body.trim_end().trim_end_matches(';'),
1667            ))
1668        })
1669        .collect()
1670}
1671
1672/// Every `#N` reference in an entity body, in order.  For the entities audited
1673/// below that order IS the attribute order (`SURFACE_CURVE` puts its 3D curve
1674/// first and its pcurves after; `PCURVE` puts its surface first).
1675fn step_entity_refs(body: &str) -> Vec<u64> {
1676    let mut refs = Vec::new();
1677    let bytes = body.as_bytes();
1678    let mut index = 0;
1679    while index < bytes.len() {
1680        if bytes[index] == b'#' {
1681            let start = index + 1;
1682            let mut end = start;
1683            while end < bytes.len() && bytes[end].is_ascii_digit() {
1684                end += 1;
1685            }
1686            if end > start {
1687                if let Ok(id) = body[start..end].parse::<u64>() {
1688                    refs.push(id);
1689                }
1690            }
1691            index = end;
1692        } else {
1693            index += 1;
1694        }
1695    }
1696    refs
1697}
1698
1699/// Audit the curve-on-surface half of the emitted graph, on the serialized
1700/// text, for the same reason `audit_step_manifold` exists: valid in-memory
1701/// intent is not proof of a correctly written file.
1702///
1703/// An `EDGE_CURVE` whose geometry is a bare 3D curve is NOT an issue — that is
1704/// the counted, deliberate outcome of the verify-or-omit gate. What is an
1705/// issue is a malformed bundle: a `SURFACE_CURVE` with no or more than two
1706/// associated geometries, a `SEAM_CURVE` that does not carry exactly two, a
1707/// `SEAM_CURVE` whose two pcurves name DIFFERENT surfaces (it is by definition
1708/// one surface's seam), a `SURFACE_CURVE` whose two pcurves name the SAME
1709/// surface (that is a seam, and must say so), or a `PCURVE` that does not
1710/// point at both a surface and a `DEFINITIONAL_REPRESENTATION`.
1711pub fn audit_step_pcurves(step: &str) -> Vec<String> {
1712    let bodies = step_entity_bodies(step);
1713    let mut issues = Vec::new();
1714    for (id, body) in &bodies {
1715        if !body.starts_with("EDGE_CURVE(") {
1716            continue;
1717        }
1718        let refs = step_entity_refs(body);
1719        let Some(geometry) = refs.get(2) else {
1720            issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
1721            continue;
1722        };
1723        let Some(wrapper) = bodies.get(geometry) else {
1724            issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
1725            continue;
1726        };
1727        let seam = wrapper.starts_with("SEAM_CURVE(");
1728        if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
1729            continue;
1730        }
1731        let wrapper_refs = step_entity_refs(wrapper);
1732        let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
1733        if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
1734            issues.push(format!(
1735                "#{geometry} carries {} associated geometries",
1736                pcurves.len()
1737            ));
1738            continue;
1739        }
1740        let mut surfaces = Vec::new();
1741        for pcurve in pcurves {
1742            let Some(pcurve_body) = bodies.get(pcurve) else {
1743                issues.push(format!("#{geometry} references missing #{pcurve}"));
1744                continue;
1745            };
1746            if !pcurve_body.starts_with("PCURVE(") {
1747                issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
1748                continue;
1749            }
1750            let pcurve_refs = step_entity_refs(pcurve_body);
1751            let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
1752            if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
1753            {
1754                issues.push(format!(
1755                    "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
1756                ));
1757            }
1758            if let Some(surface) = pcurve_refs.first() {
1759                surfaces.push(*surface);
1760            }
1761        }
1762        if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
1763            issues.push(format!(
1764                "#{geometry} pcurves name {} surface(s) but it is a {}",
1765                if surfaces[0] == surfaces[1] { 1 } else { 2 },
1766                if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
1767            ));
1768        }
1769    }
1770    issues.sort();
1771    issues
1772}
1773
1774/// Audit the serialized entity graph rather than assuming that valid
1775/// in-memory topology was necessarily written correctly.  Every EDGE_CURVE
1776/// in a closed shell must have exactly two ORIENTED_EDGE users with opposite
1777/// senses.
1778pub fn audit_step_manifold(step: &str) -> Vec<String> {
1779    let marker = "ORIENTED_EDGE('',*,*,#";
1780    let mut uses = HashMap::<u64, Vec<bool>>::default();
1781    for line in step.lines() {
1782        let Some(offset) = line.find(marker) else {
1783            continue;
1784        };
1785        let rest = &line[offset + marker.len()..];
1786        let digits = rest
1787            .chars()
1788            .take_while(|character| character.is_ascii_digit())
1789            .collect::<String>();
1790        let Ok(edge_id) = digits.parse::<u64>() else {
1791            continue;
1792        };
1793        let suffix = &rest[digits.len()..];
1794        let sense = suffix.starts_with(",.T.");
1795        uses.entry(edge_id).or_default().push(sense);
1796    }
1797    let mut issues = uses
1798        .into_iter()
1799        .filter_map(|(edge, senses)| {
1800            (senses.len() != 2 || senses[0] == senses[1]).then(|| {
1801                format!(
1802                    "EDGE_CURVE #{edge} has {} uses with senses {:?}",
1803                    senses.len(),
1804                    senses
1805                )
1806            })
1807        })
1808        .collect::<Vec<_>>();
1809    issues.sort();
1810    issues
1811}
1812